### Build Visualization Agent Example Source: https://knowusuboaky.github.io/LLMAgentR/reference/build_visualization_agent.html Demonstrates how to load data, build a visualization agent with specific configurations, define an initial state including raw data and user instructions, and then run the agent to produce visualization results. This example requires a pre-defined `my_llm_wrapper` function. ```r if (FALSE) { # \dontrun{ # 1) Load the data data <- read.csv("tests/testthat/test-data/churn_data.csv") # 2) Create the visualization agent visualization_agent <- build_visualization_agent( model = my_llm_wrapper, human_validation = FALSE, bypass_recommended_steps = FALSE, bypass_explain_code = FALSE, verbose = FALSE ) # 3) Define the initial state initial_state <- list( data_raw = data, target_variable = "Churn", user_instructions = "Create a clean and visually appealing box plot to show the distribution of Monthly Charges across Churn categories. Use distinct colors for each Churn group, add clear axis labels, a legend, and a meaningful title.", max_retries = 3, retry_count = 0 ) # 4) Run the agent final_state <- visualization_agent(initial_state) } # } ``` -------------------------------- ### Example: Building and Running a Custom Multi-Agent Team Source: https://knowusuboaky.github.io/LLMAgentR/reference/build_custom_multi_agent.html Demonstrates how to define a supervisor function and worker functions, then use them to build a multi-agent team. The example shows how to generate Mermaid output for visualization and then run the team with an initial state. ```R if (FALSE) { # \dontrun{ supervisor_fn <- function(state) { if (is.null(state$turn) || state$turn == 0) "Researcher" else "FINISH" } workers <- list( Researcher = function(state) { list(result = "Research complete") }, Writer = function(state) { list(result = "Draft complete") } ) team <- build_custom_multi_agent( supervisor = supervisor_fn, workers = workers, output = "both" ) cat(team$mermaid) team$run(list()) } # } ``` -------------------------------- ### Prepare Example Data Source: https://knowusuboaky.github.io/LLMAgentR/articles/forecasting-agent.html Creates a sample data frame for forecasting. The data should include an 'id', 'date', and 'value' column. ```R set.seed(42) my_data <- data.frame( id = "series_1", date = seq.Date(as.Date("2024-01-01"), by = "day", length.out = 120), value = 100 + cumsum(rnorm(120, 0.1, 1)) ) ``` -------------------------------- ### Build Data Wrangling Agent Example Source: https://knowusuboaky.github.io/LLMAgentR/reference/build_data_wrangling_agent.html Demonstrates creating and running a data wrangling agent. It simulates data, combines it into a list, initializes the agent with specified parameters, sets up the initial state including raw data and user instructions, and then executes the agent to process the data. ```R if (FALSE) { # \dontrun{ # 1) Simulate multiple data frames with a common ID df1 <- data.frame( ID = c(1, 2, 3, 4), Name = c("John", "Jane", "Jim", "Jill"), stringsAsFactors = FALSE ) df2 <- data.frame( ID = c(1, 2, 3, 4), Age = c(25, 30, 35, 40), stringsAsFactors = FALSE ) df3 <- data.frame( ID = c(1, 2, 3, 4), Education = c("Bachelors", "Masters", "PhD", "MBA"), stringsAsFactors = FALSE ) # 2) Combine into a list data <- list(df1, df2, df3) # 3) Create the agent data_wrangling_agent <- build_data_wrangling_agent( model = my_llm_wrapper, human_validation = FALSE, bypass_recommended_steps = FALSE, bypass_explain_code = FALSE, verbose = FALSE ) # 4) Define the initial state initial_state <- list( data_raw = data, user_instructions = "Merge the data frames on the ID column.", max_retries = 3, retry_count = 0 ) # 5) Run the agent final_state <- data_wrangling } # } ``` -------------------------------- ### Build a Weather Agent Example Source: https://knowusuboaky.github.io/LLMAgentR/reference/build_weather_agent.html Demonstrates how to construct a weather agent. Ensure you have a valid OpenWeatherMap API key set as an environment variable or passed directly. The `my_llm_wrapper` function should be defined elsewhere to handle LLM interactions. ```r if (FALSE) { # \dontrun{ # Get weather information weather_agent <- build_weather_agent( llm = my_llm_wrapper, location_query = "Tokyo, Japan", system_prompt = NULL, weather_api_key = NULL, units = "metric", # metric or imperial n_tries = 3, backoff = 2, endpoint_url = NULL, verbose = FALSE ) } # } ``` -------------------------------- ### Install LLMAgentR Development Version Source: https://knowusuboaky.github.io/LLMAgentR/index.html Installs the development version of LLMAgentR from GitHub. This is useful for accessing the latest features or bug fixes. ```r # If needed install.packages("remotes") remotes::install_github("knowusuboaky/LLMAgentR") ``` -------------------------------- ### Example LLM Call with chatLLM Source: https://knowusuboaky.github.io/LLMAgentR/index.html Demonstrates a direct call to the call_llm function to get a summary of the capital of France using the Groq provider. ```r call_llm( prompt = "Summarize the capital of France.", provider = "groq", model = "llama3-8b", temperature = 0.7, max_tokens = 200, verbose = TRUE ) ``` -------------------------------- ### Example Usage of Data Cleaning Agent Source: https://knowusuboaky.github.io/LLMAgentR/reference/build_data_cleaning_agent.html Demonstrates the complete workflow of creating and running a data cleaning agent. This includes loading data, initializing the agent with specific parameters, defining the initial state with raw data and user instructions, and executing the agent to obtain the final cleaned state. ```r if (FALSE) { # \dontrun{ # 1) Load the data data <- read.csv("tests/testthat/test-data/churn_data.csv") # 2) Create the agent data_cleaner_agent <- build_data_cleaning_agent( model = my_llm_wrapper, human_validation = FALSE, bypass_recommended_steps = FALSE, bypass_explain_code = FALSE, verbose = FALSE ) # 3) Define the initial state initial_state <- list( data_raw = data, user_instructions = "Don't remove outliers when cleaning the data.", max_retries = 3, retry_count = 0 ) # 4) Run the agent final_state <- data_cleaner_agent(initial_state) } # } ``` -------------------------------- ### Minimal Multi-Agent Team Setup Source: https://knowusuboaky.github.io/LLMAgentR/articles/multi-agent-teams.html Demonstrates a basic supervisor-worker team where a supervisor function decides the next worker based on the shared state. Execution stops when the supervisor returns 'FINISH'. ```R library(LLMAgentR) supervisor_fn <- function(state) { if (is.null(state$research_done) || !isTRUE(state$research_done)) { return("Researcher") } if (is.null(state$draft_done) || !isTRUE(state$draft_done)) { return("Writer") } "FINISH" } workers <- list( Researcher = function(state) { old_log <- if (is.null(state$log)) character(0) else state$log list( research_done = TRUE, findings = c("Customer churn is highest in month 2."), log = c(old_log, "Researcher completed evidence gathering.") ) }, Writer = function(state) { old_log <- if (is.null(state$log)) character(0) else state$log draft <- paste( "Executive summary:", paste(state$findings, collapse = " ") ) list( draft_done = TRUE, draft = draft, log = c(old_log, "Writer produced first draft.") ) } ) team <- build_custom_multi_agent( supervisor = supervisor_fn, workers = workers, max_turns = 6L ) result <- team(list(log = character(0))) str(result) ``` -------------------------------- ### Install LLMAgentR Package Source: https://knowusuboaky.github.io/LLMAgentR/index.html Installs the LLMAgentR package from CRAN. Use this for the stable release. ```r install.packages("LLMAgentR") ``` -------------------------------- ### Summarize Document with Agent Source: https://knowusuboaky.github.io/LLMAgentR/reference/build_doc_summarizer_agent.html Example of building and then using the document summarizer agent to process a document. The agent takes a file path as input and returns a summary, metadata, chunk count, and success status. ```R if (FALSE) { # \dontrun{ # Build document summarizer agent summarizer_agent <- build_doc_summarizer_agent( llm = my_llm_wrapper, summary_template = NULL, chunk_size = 4000, overlap = 200, verbose = FALSE ) # Summarize document final_state <- summarizer_agent("https://github.com/knowusuboaky/LLMAgentR/raw/main/\tests/testthat/test-data/scrum.docx") } # } ``` -------------------------------- ### Compile Graph and Generate Mermaid Diagram Source: https://knowusuboaky.github.io/LLMAgentR/articles/custom-agents.html Shows how to use `compile_graph` to get a runnable function and graph artifacts. This example includes subgraphs for better visualization of the agent's structure. ```R library(LLMAgentR) compiled <- compile_graph( node_functions = list( start = function(state) make_command("classify"), classify = function(state) { q <- if (is.null(state$query)) "" else tolower(state$query) list(route = if (grepl("weather", q)) "weather" else "general") }, weather_handler = function(state) list(answer = "Weather path"), general_handler = function(state) list(answer = "General path") ), entry_point = "start", conditional_edges = list( list( from = "classify", condition = function(state) state$route, mapping = list( weather = "weather_handler", general = "general_handler" ) ) ), edges = list( c("weather_handler", "__end__"), c("general_handler", "__end__") ), subgraphs = list( Router = c("start", "classify"), Handlers = c("weather_handler", "general_handler") ) ) cat(compiled$mermaid) out <- compiled$run(list(query = "weather tomorrow")) str(out) # Optional PNG render (requires Mermaid CLI `mmdc`) # save_mermaid_png(compiled, file = "router_graph.png") ``` -------------------------------- ### Install chatLLM Package Source: https://knowusuboaky.github.io/LLMAgentR/index.html Installs the chatLLM package from CRAN, providing a modular interface for interacting with various LLM providers. ```r install.packages("chatLLM") ``` -------------------------------- ### One-Shot Pattern: Run a Single Request Immediately Source: https://knowusuboaky.github.io/LLMAgentR/reference/build_code_agent.html Use the one-shot pattern to execute a single coding request immediately. Provide the `user_input` to run the agent once and get the result. ```R one_shot <- build_code_agent( llm = my_llm_wrapper, user_input = "Create a ggplot2 bar chart of mpg by cyl in mtcars.", max_tries = 3, backoff = 2, verbose = FALSE ) ``` -------------------------------- ### Build Custom Agent with Node Functions and Edges Source: https://knowusuboaky.github.io/LLMAgentR/reference/build_custom_agent.html Defines a custom agent with a graph structure. Use 'output = "both"' to get the Mermaid graph and the runnable agent. The agent routes queries based on keywords. ```R if (FALSE) { # \dontrun{ custom <- build_custom_agent( node_functions = list( start = function(state) make_command("classify"), classify = function(state) { if (grepl("weather", state$query, ignore.case = TRUE)) { make_command("weather") } else { make_command("general") } }, weather = function(state) list(answer = "Routing to weather handler"), general = function(state) list(answer = "Routing to general handler") ), entry_point = "start", edges = list(c("weather", "__end__"), c("general", "__end__")), output = "both", subgraphs = list( Router = c("start", "classify"), Handlers = c("weather", "general") ) ) cat(custom$mermaid) custom$run(list(query = "weather in Accra")) } # } ``` -------------------------------- ### Build and Run SQL Agent Source: https://knowusuboaky.github.io/LLMAgentR/reference/build_sql_agent.html Demonstrates connecting to a database, building a SQL agent, defining an initial state with user instructions, and running the agent to process the instructions. ```R if (FALSE) { # \dontrun{ # 1) Connect to the database conn <- DBI::dbConnect(RSQLite::SQLite(), "tests/testthat/test-data/northwind.db") # 2) Create the SQL agent sql_agent <- build_sql_agent( model = my_llm_wrapper, connection = conn, human_validation = FALSE, bypass_recommended_steps = FALSE, bypass_explain_code = FALSE, verbose = FALSE ) # 3) Define the initial state initial_state <- list( user_instructions = "Identify the Regions (or Territories) with the highest CustomerCount and TotalSales. Return a table with columns: Region, CustomerCount, and TotalSales. Hint: (UnitPrice × Quantity).", max_retries = 3, retry_count = 0 ) # 4) Run the agent final_state <- sql_agent(initial_state) } # } ``` -------------------------------- ### Build and Run Forecasting Agent Source: https://knowusuboaky.github.io/LLMAgentR/reference/build_forecasting_agent.html Demonstrates the complete workflow of creating a forecasting agent, defining initial state, and running the agent to forecast sales data. Requires a pre-defined LLM wrapper function `my_llm_wrapper` and dataset `walmart_sales_weekly`. ```r if (FALSE) { # \dontrun{ # 2) Prepare the dataset my_data <- walmart_sales_weekly # 3) Create the forecasting agent forecasting_agent <- build_forecasting_agent( model = my_llm_wrapper, bypass_recommended_steps = FALSE, bypass_explain_code = FALSE, mode = "dark", # dark or light line_width = 3, verbose = FALSE ) # 4) Define the initial state initial_state <- list( user_instructions = "Forecast sales for the next 30 days, using `id` as the grouping variable, a forecasting horizon of 30, and a confidence level of 90%.", data_raw = my_data ) # 5) Run the agent final_state <- forecasting_agent(initial_state) } # } ``` -------------------------------- ### Build the Visualization Agent Source: https://knowusuboaky.github.io/LLMAgentR/articles/visualization-agent.html Initializes the visualization agent with specified parameters. Ensure the LLMAgentR library is loaded and a model wrapper function is defined. ```R library(LLMAgentR) my_llm_wrapper <- function(prompt, verbose = FALSE) "LLM response placeholder" viz_agent <- build_visualization_agent( model = my_llm_wrapper, human_validation = FALSE, bypass_recommended_steps = FALSE, bypass_explain_code = FALSE, function_name = "data_visualization", verbose = FALSE ) ``` -------------------------------- ### Build a Simple Linear Custom Agent Source: https://knowusuboaky.github.io/LLMAgentR/articles/custom-agents.html Demonstrates the basic structure of a custom agent with a linear workflow. It shows how to define nodes, use `make_command` for navigation, and return state updates. ```R library(LLMAgentR) agent <- build_custom_agent( node_functions = list( start = function(state) { make_command("answer") }, answer = function(state) { query <- if (is.null(state$query)) "" else state$query list( answer = paste("You asked:", query), handled = TRUE ) } ), entry_point = "start", edges = list( c("answer", "__end__") ), default_state = list(handled = FALSE) ) result <- agent(list(query = "How do I build a custom agent?")) str(result) ``` -------------------------------- ### Build and Save Visualization Agent Workflow Source: https://knowusuboaky.github.io/LLMAgentR/articles/agent-index.html Constructs a visualization agent workflow and saves it as a Mermaid PNG file. Requires a language model and specifies output and direction. ```r workflow <- build_visualization_agent( model = dummy_llm, output = "both", direction = "LR" ) save_mermaid_png(workflow, "pkgdown/assets/visualization-agent-workflow.png") ``` -------------------------------- ### Build and Run Feature Engineering Agent Source: https://knowusuboaky.github.io/LLMAgentR/reference/build_feature_engineering_agent.html Demonstrates the complete workflow of creating a feature engineering agent, defining its initial state, and running it to process data. This includes loading data, initializing the agent with specific parameters, and executing the agent with user instructions. ```r if (FALSE) { # \dontrun{ # 1) Load the data data <- read.csv("tests/testthat/test-data/churn_data.csv") # 2) Create the feature engineering agent feature_engineering_agent <- build_feature_engineering_agent( model = my_llm_wrapper, human_validation = FALSE, bypass_recommended_steps = FALSE, bypass_explain_code = FALSE, verbose = TRUE ) # 3) Define the initial state initial_state <- list( data_raw = data, target_variable = "Churn", user_instructions = "Inspect the data. Make any new features and transformations that you think will be useful for predicting the target variable.", max_retries = 3, retry_count = 0 ) # 4) Run the agent final_state <- feature_engineering_agent(initial_state) } # } ``` -------------------------------- ### build_interpreter_agent Source: https://knowusuboaky.github.io/LLMAgentR/reference/build_interpreter_agent.html Constructs an LLM-powered agent that explains plots, tables, text, or other outputs for both technical and non-technical audiences. It can be used in a builder pattern to create a reusable agent closure or in a one-shot pattern to get an immediate interpretation. ```APIDOC ## build_interpreter_agent Constructs an LLM-powered agent that explains plots, tables, text, or other outputs for both technical and non-technical audiences. ### Arguments * `llm` - Function that takes `prompt` and returns an LLM response (may or may not accept `verbose`). * `interpreter_prompt` - Optional template for the prompt (default supplied). * `code_output` - The output to interpret (plot caption, table text, model summary, etc.). **Default `NULL`**. * `max_tries` - Max LLM retry attempts (default `3`). * `backoff` - Seconds between retries (default `2`). * `verbose` - Logical; print progress (default `TRUE`). ### Value * If `code_output` is `NULL`: a **function** (closure). * Otherwise: a **list** with: * `prompt` - The full prompt sent to the LLM. * `interpretation` - The LLM’s explanation (or error). * `success` - Logical; did it succeed? * `attempts` - Number of attempts made. ### Details **Two calling patterns** * **Builder pattern** – omit `code_output`; a reusable **interpreter-agent closure** is returned. * **One-shot pattern** – provide `code_output`; the function runs immediately and returns the interpretation. ### Examples ```R if (FALSE) { # \dontrun{ ## 1) Builder pattern -------------------------------------------- interp <- build_interpreter_agent(llm = my_llm_wrapper, verbose = FALSE) table_txt <- " | Region | Sales | Profit | | North | 2000 | 300 | | South | 1500 | 250 |" res1 <- interp(table_txt) res2 <- interp("R² = 0.87 for the fitted model …") ## 2) One-shot pattern ------------------------------------------- build_interpreter_agent( llm = my_llm_wrapper, code_output = table_txt, verbose = FALSE ) } # } ``` ``` -------------------------------- ### Create a Quick Access LLM Shortcut Source: https://knowusuboaky.github.io/LLMAgentR/index.html Creates a shortcut 'my_llm_wrapper' that preconfigures a call to 'call_llm' for the OpenAI gpt-4o model, simplifying one-line LLM calls. ```r my_llm_wrapper <- call_llm( provider = "openai", model = "gpt-4o", max_tokens = 3000, verbose = TRUE ) ``` -------------------------------- ### Create a command for state transition Source: https://knowusuboaky.github.io/LLMAgentR/reference/state_graph_utils.html Use `make_command` to specify the next node to transition to and any state updates to apply before the transition. ```R make_command(goto = NULL, update = list()) ``` -------------------------------- ### Build the SQL Query Agent Source: https://knowusuboaky.github.io/LLMAgentR/articles/sql-agent.html This snippet shows how to construct the SQL agent, specifying the language model, database connection, and various operational parameters like human validation and retry settings. ```R library(LLMAgentR) my_llm_wrapper <- function(prompt, verbose = FALSE) "LLM response placeholder" sql_agent <- build_sql_agent( model = my_llm_wrapper, connection = conn, human_validation = FALSE, bypass_recommended_steps = FALSE, bypass_explain_code = FALSE, verbose = FALSE ) ``` -------------------------------- ### Build Data Wrangling Agent Source: https://knowusuboaky.github.io/LLMAgentR/articles/data-wrangling-agent.html Initializes the Data Wrangling Agent with specified parameters. Requires a custom LLM wrapper function. Human validation and code explanation steps can be bypassed. ```R library(LLMAgentR) my_llm_wrapper <- function(prompt, verbose = FALSE) "LLM response placeholder" wrangler <- build_data_wrangling_agent( model = my_llm_wrapper, human_validation = FALSE, bypass_recommended_steps = FALSE, bypass_explain_code = FALSE, verbose = FALSE ) ``` -------------------------------- ### Build the Document Summarizer Agent Source: https://knowusuboaky.github.io/LLMAgentR/articles/document-summarizer-agent.html Initializes the Document Summarizer Agent with a custom LLM wrapper and specifies chunk size and overlap for processing. Useful for setting up the agent for document summarization tasks. ```R library(LLMAgentR) my_llm_wrapper <- function(prompt, verbose = FALSE) "LLM response placeholder" summarizer <- build_doc_summarizer_agent( llm = my_llm_wrapper, chunk_size = 4000, overlap = 200, verbose = FALSE ) ``` -------------------------------- ### Generate Mermaid PNG Workflow Source: https://knowusuboaky.github.io/LLMAgentR/articles/visualization-agent.html Builds the visualization agent and saves its workflow as a Mermaid PNG. Requires the LLMAgentR library and a model wrapper function. ```R library(LLMAgentR) my_llm_wrapper <- function(prompt, verbose = FALSE) "LLM response placeholder" workflow <- build_visualization_agent( model = my_llm_wrapper, output = "both", direction = "LR" ) save_mermaid_png( x = workflow, file = "pkgdown/assets/visualization-agent-workflow.png" ) ``` -------------------------------- ### Prepare an In-Memory SQLite Database Source: https://knowusuboaky.github.io/LLMAgentR/articles/sql-agent.html This code prepares an in-memory SQLite database and populates it with a sample 'sales' table. It uses the DBI and RSQLite libraries for database operations. ```R library(DBI) library(RSQLite) conn <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(conn, "sales", data.frame( region = c("North", "North", "South"), amount = c(120, 80, 90) )) ``` -------------------------------- ### Generate Mermaid PNG for SQL Query Agent Source: https://knowusuboaky.github.io/LLMAgentR/articles/agent-index.html Builds the workflow diagram for the SQL Query Agent and saves it as a PNG file. Requires a dummy LLM function and can optionally take a connection object. ```R workflow <- build_sql_agent( model = dummy_llm, connection = NULL, output = "both", direction = "LR" ) save_mermaid_png(workflow, "pkgdown/assets/sql-agent-workflow.png") ``` -------------------------------- ### Build a Reusable Code Agent Source: https://knowusuboaky.github.io/LLMAgentR/articles/code-agent.html Initializes the Code Agent with a specified LLM wrapper and configuration for retries and backoff. The agent can be reused for multiple coding tasks. ```r library(LLMAgentR) coder <- build_code_agent( llm = my_llm_wrapper, max_tries = 3, backoff = 2, verbose = FALSE ) ``` -------------------------------- ### Build Weather Agent Source: https://knowusuboaky.github.io/LLMAgentR/reference/index.html Construct an agent designed to retrieve and provide weather information. ```python build_weather_agent() ``` -------------------------------- ### Build a Custom Agent with Conditional Routing Source: https://knowusuboaky.github.io/LLMAgentR/articles/custom-agents.html Illustrates how to implement conditional behavior in a custom agent using `conditional_edges`. This agent routes based on keywords in the query. ```R library(LLMAgentR) router_agent <- build_custom_agent( node_functions = list( start = function(state) { make_command("classify") }, classify = function(state) { q <- if (is.null(state$query)) "" else tolower(state$query) route <- if (grepl("weather", q)) "weather" else "general" list(route = route) }, weather_handler = function(state) { list(answer = "Routing to weather workflow.") }, general_handler = function(state) { list(answer = "Routing to general workflow.") } ), entry_point = "start", conditional_edges = list( list( from = "classify", condition = function(state) state$route, mapping = list( weather = "weather_handler", general = "general_handler" ) ) ), edges = list( c("weather_handler", "__end__"), c("general_handler", "__end__") ) ) router_agent(list(query = "weather in Accra")) router_agent(list(query = "summarize this report")) ``` -------------------------------- ### Build and Save Weather Agent Workflow Diagram Source: https://knowusuboaky.github.io/LLMAgentR/articles/weather-agent.html This snippet demonstrates how to build the weather agent, specifying an LLM wrapper, location, API key, output format, and direction. It then saves the generated workflow as a Mermaid PNG. ```R library(LLMAgentR) my_llm_wrapper <- function(prompt, verbose = FALSE) "LLM response placeholder" workflow <- build_weather_agent( llm = my_llm_wrapper, location_query = "Accra, Ghana", weather_api_key = "your-openweathermap-key", output = "both", direction = "LR" ) save_mermaid_png( x = workflow, file = "pkgdown/assets/weather-agent-workflow.png" ) ``` -------------------------------- ### Generate Mermaid PNG for SQL Agent Workflow Source: https://knowusuboaky.github.io/LLMAgentR/articles/sql-agent.html This snippet demonstrates how to build the SQL agent and save its workflow diagram as a Mermaid PNG. It requires the LLMAgentR library and a placeholder for the language model wrapper. ```R library(LLMAgentR) my_llm_wrapper <- function(prompt, verbose = FALSE) "LLM response placeholder" workflow <- build_sql_agent( model = my_llm_wrapper, connection = NULL, output = "both", direction = "LR" ) save_mermaid_png( x = workflow, file = "pkgdown/assets/sql-agent-workflow.png" ) ``` -------------------------------- ### Build Visualization Agent Source: https://knowusuboaky.github.io/LLMAgentR/reference/index.html Construct an agent focused on generating data visualizations. ```python build_visualization_agent() ``` -------------------------------- ### Build Custom Multi-Agent Team (Supervisor Style) Source: https://knowusuboaky.github.io/LLMAgentR/reference/index.html Create a custom team of multiple agents managed in a supervisor style. ```python build_custom_multi_agent() ``` -------------------------------- ### Generate Mermaid PNG for Interpreter Agent Workflow Source: https://knowusuboaky.github.io/LLMAgentR/articles/interpreter-agent.html Builds the Interpreter Agent and saves its workflow diagram as a Mermaid PNG. Requires the LLMAgentR library and a custom LLM wrapper function. ```R library(LLMAgentR) my_llm_wrapper <- function(prompt, verbose = FALSE) "LLM response placeholder" workflow <- build_interpreter_agent( llm = my_llm_wrapper, output = "both", direction = "LR" ) save_mermaid_png( x = workflow, file = "pkgdown/assets/interpreter-agent-workflow.png" ) ``` -------------------------------- ### Build SQL Agent Graph Source: https://knowusuboaky.github.io/LLMAgentR/reference/index.html Construct an agent designed to interact with and query SQL databases. ```python build_sql_agent() ``` -------------------------------- ### Set API Keys for LLM Providers Source: https://knowusuboaky.github.io/LLMAgentR/index.html Configures environment variables for various LLM API keys. Ensure you replace 'your-...' placeholders with your actual keys. ```r Sys.setenv( OPENAI_API_KEY = "your-openai-key", GROQ_API_KEY = "your-groq-key", ANTHROPIC_API_KEY = "your-anthropic-key", DEEPSEEK_API_KEY = "your-deepseek-key", DASHSCOPE_API_KEY = "your-dashscope-key", GH_MODELS_TOKEN = "your-github-models-token" ) ``` -------------------------------- ### build_sql_agent Source: https://knowusuboaky.github.io/LLMAgentR/reference/index.html Build a SQL Agent Graph. ```APIDOC ## build_sql_agent ### Description Build a SQL Agent Graph. ### Function Signature `build_sql_agent()` ``` -------------------------------- ### build_weather_agent Source: https://knowusuboaky.github.io/LLMAgentR/reference/index.html Build a Weather Agent. ```APIDOC ## build_weather_agent ### Description Build a Weather Agent. ### Function Signature `build_weather_agent()` ``` -------------------------------- ### Build a Reusable Interpreter Agent Source: https://knowusuboaky.github.io/LLMAgentR/articles/interpreter-agent.html Creates a reusable Interpreter Agent instance using a specified LLM wrapper. This agent can then be used to interpret various technical outputs. ```R library(LLMAgentR) my_llm_wrapper <- function(prompt, verbose = FALSE) "LLM response placeholder" interpreter <- build_interpreter_agent( llm = my_llm_wrapper, verbose = FALSE ) ``` -------------------------------- ### Generate Mermaid PNG for Interpreter Agent Source: https://knowusuboaky.github.io/LLMAgentR/articles/agent-index.html Builds the workflow diagram for the Interpreter Agent and saves it as a PNG file. Requires a dummy LLM function. ```R workflow <- build_interpreter_agent( llm = dummy_llm, output = "both", direction = "LR" ) save_mermaid_png(workflow, "pkgdown/assets/interpreter-agent-workflow.png") ``` -------------------------------- ### build_weather_agent Source: https://knowusuboaky.github.io/LLMAgentR/reference/build_weather_agent.html Constructs an LLM-powered weather assistant that fetches data from OpenWeatherMap and generates user-friendly reports. Handles location parsing, API calls, caching, and LLM-based summarization. ```APIDOC ## build_weather_agent ### Description Constructs an LLM-powered weather assistant that fetches data from OpenWeatherMap and generates user-friendly reports. Handles location parsing, API calls, caching, and LLM-based summarization. ### Arguments * **llm** (function) - A function that accepts a character prompt and returns an LLM response. * **location_query** (string) - Free-text location query (e.g., "weather in Toronto"). * **system_prompt** (string) - Optional LLM system prompt for weather reporting. * **weather_api_key** (string) - OpenWeatherMap API key (defaults to OPENWEATHERMAP_API_KEY env var). * **units** (string) - Unit system ("metric" or "imperial"). * **n_tries** (integer) - Number of retry attempts for API/LLM calls (default: 3). * **backoff** (numeric) - Base seconds to wait between retries (default: 2). * **endpoint_url** (string) - OpenWeatherMap endpoint URL. * **verbose** (logical) - Logical controlling progress messages (default: TRUE). ### Value A list containing: * success - Logical indicating if operation succeeded * location - Cleaned location string * weather_raw - Raw API response * weather_formatted - Formatted weather string * llm_response - Generated weather report * timestamp - Time of response * cache_hit - Logical indicating cache usage * attempts - Number of tries made ### Examples ```R if (FALSE) { # \dontrun{ # Get weather information weather_agent <- build_weather_agent( llm = my_llm_wrapper, location_query = "Tokyo, Japan", system_prompt = NULL, weather_api_key = NULL, units = "metric", # metric or imperial n_tries = 3, backoff = 2, endpoint_url = NULL, verbose = FALSE ) } ``` ``` -------------------------------- ### Generate Mermaid PNG for Data Wrangling Agent Source: https://knowusuboaky.github.io/LLMAgentR/articles/agent-index.html Builds the workflow diagram for the Data Wrangling Agent and saves it as a PNG file. Requires a dummy model function. ```R workflow <- build_data_wrangling_agent( model = dummy_llm, output = "both", direction = "LR" ) save_mermaid_png(workflow, "pkgdown/assets/data-wrangling-agent-workflow.png") ``` -------------------------------- ### build_sql_agent Source: https://knowusuboaky.github.io/LLMAgentR/reference/build_sql_agent.html Constructs a full SQL database agent using a graph-based workflow. It supports step recommendation, SQL code generation, error handling, optional human review, and automatic explanation of the final code. ```APIDOC ## Function: build_sql_agent ### Description This function constructs a full SQL database agent using a graph-based workflow. It supports step recommendation, SQL code generation, error handling, optional human review, and automatic explanation of the final code. ### Arguments * **model** (function) - A function that accepts prompts and returns LLM responses. * **connection** (DBI connection object) - A DBI connection object to the target SQL database. * **n_samples** (numeric) - Number of candidate SQL plans to consider (used in prompt). * **human_validation** (logical) - Whether to include a human review node. * **bypass_recommended_steps** (logical) - If TRUE, skip the step recommendation node. * **bypass_explain_code** (logical) - If TRUE, skip the final explanation step. * **verbose** (logical) - Logical indicating whether to print progress messages (default: TRUE). ### Value A compiled SQL agent function that runs via a state machine (graph execution). ### Examples ```R # 1) Connect to the database conn <- DBI::dbConnect(RSQLite::SQLite(), "tests/testthat/test-data/northwind.db") # 2) Create the SQL agent sql_agent <- build_sql_agent( model = my_llm_wrapper, connection = conn, human_validation = FALSE, bypass_recommended_steps = FALSE, bypass_explain_code = FALSE, verbose = FALSE ) # 3) Define the initial state initial_state <- list( user_instructions = "Identify the Regions (or Territories) with the highest CustomerCount and TotalSales. Return a table with columns: Region, CustomerCount, and TotalSales. Hint: (UnitPrice × Quantity).", max_retries = 3, retry_count = 0 ) # 4) Run the agent final_state <- sql_agent(initial_state) ``` ``` -------------------------------- ### Generate Mermaid Workflow PNG Source: https://knowusuboaky.github.io/LLMAgentR/articles/data-wrangling-agent.html Builds the Data Wrangling Agent and saves its workflow diagram as a Mermaid PNG. Requires a custom LLM wrapper function. ```R library(LLMAgentR) my_llm_wrapper <- function(prompt, verbose = FALSE) "LLM response placeholder" workflow <- build_data_wrangling_agent( model = my_llm_wrapper, output = "both", direction = "LR" ) save_mermaid_png( x = workflow, file = "pkgdown/assets/data-wrangling-agent-workflow.png" ) ``` -------------------------------- ### Build Data Cleaning Agent Source: https://knowusuboaky.github.io/LLMAgentR/articles/data-cleaning-agent.html Initializes the Data Cleaning Agent with specified parameters. Configure human validation, recommended steps, and code explanation settings. ```r library(LLMAgentR) my_llm_wrapper <- function(prompt, verbose = FALSE) "LLM response placeholder" data_cleaner <- build_data_cleaning_agent( model = my_llm_wrapper, human_validation = FALSE, bypass_recommended_steps = FALSE, bypass_explain_code = FALSE, verbose = FALSE ) ``` -------------------------------- ### Build the Feature Engineering Agent Source: https://knowusuboaky.github.io/LLMAgentR/articles/feature-engineering-agent.html Initializes the Feature Engineering Agent with specified parameters. Use `human_validation = FALSE` to bypass manual checks and `bypass_recommended_steps` or `bypass_explain_code` to skip certain agent processes. ```R library(LLMAgentR) my_llm_wrapper <- function(prompt, verbose = FALSE) "LLM response placeholder" feature_agent <- build_feature_engineering_agent( model = my_llm_wrapper, human_validation = FALSE, bypass_recommended_steps = FALSE, bypass_explain_code = FALSE, verbose = FALSE ) ``` -------------------------------- ### Initialize a StateGraph object Source: https://knowusuboaky.github.io/LLMAgentR/reference/state_graph_utils.html The `StateGraph` constructor initializes a new state graph object. It provides methods to add nodes, edges, set entry points, and compile the graph. ```R StateGraph() ``` -------------------------------- ### Generate Mermaid PNG for Document Summarizer Agent Source: https://knowusuboaky.github.io/LLMAgentR/articles/agent-index.html Builds the workflow diagram for the Document Summarizer Agent and saves it as a PNG file. Requires a dummy LLM function. ```R workflow <- build_doc_summarizer_agent( llm = dummy_llm, output = "both", direction = "LR" ) save_mermaid_png(workflow, "pkgdown/assets/document-summarizer-agent-workflow.png") ``` -------------------------------- ### Generate Mermaid PNG for Code Agent Source: https://knowusuboaky.github.io/LLMAgentR/articles/agent-index.html Builds the workflow diagram for the Code Generation Agent and saves it as a PNG file. Requires a dummy LLM function. ```R workflow <- build_code_agent( llm = dummy_llm, output = "both", direction = "LR" ) save_mermaid_png(workflow, "pkgdown/assets/code-agent-workflow.png") ``` -------------------------------- ### Build Document Summarizer Agent Source: https://knowusuboaky.github.io/LLMAgentR/reference/index.html Build an agent capable of summarizing documents. ```python build_doc_summarizer_agent() ``` -------------------------------- ### Generate Mermaid PNG for Data Cleaning Agent Workflow Source: https://knowusuboaky.github.io/LLMAgentR/articles/data-cleaning-agent.html Builds the Data Cleaning Agent and saves its workflow diagram as a Mermaid PNG. Requires the LLMAgentR library and a model wrapper function. ```r library(LLMAgentR) my_llm_wrapper <- function(prompt, verbose = FALSE) "LLM response placeholder" workflow <- build_data_cleaning_agent( model = my_llm_wrapper, output = "both", direction = "LR" ) save_mermaid_png( x = workflow, file = "pkgdown/assets/data-cleaning-agent-workflow.png" ) ``` -------------------------------- ### Build Data Wrangling Agent Source: https://knowusuboaky.github.io/LLMAgentR/reference/index.html Construct an agent focused on data wrangling tasks. ```python build_data_wrangling_agent() ``` -------------------------------- ### Build and Run Forecasting Agent Source: https://knowusuboaky.github.io/LLMAgentR/articles/forecasting-agent.html Builds and runs the forecasting agent with custom LLM, data, and instructions. Allows for various customization options like bypass flags and display modes. ```R library(LLMAgentR) my_llm_wrapper <- function(prompt, verbose = FALSE) "LLM response placeholder" forecast_agent <- build_forecasting_agent( model = my_llm_wrapper, bypass_recommended_steps = FALSE, bypass_explain_code = FALSE, mode = "dark", line_width = 3, verbose = FALSE ) initial_state <- list( user_instructions = "Forecast value for the next 30 days grouped by id.", data_raw = my_data ) final_state <- forecast_agent(initial_state) str(final_state) ``` -------------------------------- ### Run Data Wrangling Agent with State List Source: https://knowusuboaky.github.io/LLMAgentR/articles/data-wrangling-agent.html Executes the Data Wrangling Agent using an initial state list containing raw data, user instructions, and retry parameters. Returns the final state after processing. ```R initial_state <- list( data_raw = mtcars, user_instructions = "Group by cyl and return average mpg and hp.", max_retries = 3, retry_count = 0 ) final_state <- wrangler(initial_state) str(final_state) ``` -------------------------------- ### Generate Mermaid PNG for Weather Agent Source: https://knowusuboaky.github.io/LLMAgentR/articles/agent-index.html Builds the workflow diagram for the Weather Agent and saves it as a PNG file. Requires a dummy LLM function, a location query, and an OpenWeatherMap API key. ```R workflow <- build_weather_agent( llm = dummy_llm, location_query = "Accra, Ghana", weather_api_key = "your-openweathermap-key", output = "both", direction = "LR" ) save_mermaid_png(workflow, "pkgdown/assets/weather-agent-workflow.png") ``` -------------------------------- ### Run SQL Agent Workflow Source: https://knowusuboaky.github.io/LLMAgentR/articles/sql-agent.html This code executes the SQL agent with a specific user instruction to 'Return total sales by region'. It initializes the state with the instruction and maximum retries, then processes it through the agent. ```R initial_state <- list( user_instructions = "Return total sales by region.", max_retries = 3, retry_count = 0 ) final_state <- sql_agent(initial_state) str(final_state) ``` -------------------------------- ### Generate Mermaid PNG for Forecasting Agent Source: https://knowusuboaky.github.io/LLMAgentR/articles/agent-index.html Builds the workflow diagram for the Forecasting Agent and saves it as a PNG file. Requires a dummy model function. ```R workflow <- build_forecasting_agent( model = dummy_llm, output = "both", direction = "LR" ) save_mermaid_png(workflow, "pkgdown/assets/forecasting-agent-workflow.png") ``` -------------------------------- ### Interpret a Table Output with Interpreter Agent Source: https://knowusuboaky.github.io/LLMAgentR/articles/interpreter-agent.html Demonstrates how to use a configured Interpreter Agent to interpret a given table text. The result contains success status, attempts, and the plain-language interpretation. ```R table_txt <- " | Region | Sales | Profit | | North | 2000 | 300 | | South | 1500 | 250 |" result <- interpreter(table_txt) str(result) ``` -------------------------------- ### Generate Mermaid PNG for Feature Engineering Agent Workflow Source: https://knowusuboaky.github.io/LLMAgentR/articles/feature-engineering-agent.html Builds the Feature Engineering Agent and saves its workflow diagram as a Mermaid PNG. Requires the LLMAgentR library and a model wrapper function. ```R library(LLMAgentR) my_llm_wrapper <- function(prompt, verbose = FALSE) "LLM response placeholder" workflow <- build_feature_engineering_agent( model = my_llm_wrapper, output = "both", direction = "LR" ) save_mermaid_png( x = workflow, file = "pkgdown/assets/feature-engineering-agent-workflow.png" ) ``` -------------------------------- ### Generate Mermaid PNG for Data Cleaning Agent Source: https://knowusuboaky.github.io/LLMAgentR/articles/agent-index.html Builds the workflow diagram for the Data Cleaning Agent and saves it as a PNG file. Requires a dummy model function. ```R workflow <- build_data_cleaning_agent( model = dummy_llm, output = "both", direction = "LR" ) save_mermaid_png(workflow, "pkgdown/assets/data-cleaning-agent-workflow.png") ``` -------------------------------- ### Run a Query with the Research Agent Source: https://knowusuboaky.github.io/LLMAgentR/articles/research-agent.html Executes a research query using the initialized research agent and displays the structure of the result. Ensure the agent is built before running a query. ```R result <- researcher("What are recent trends in open-source LLM tooling?") str(result) ``` -------------------------------- ### build_data_wrangling_agent Source: https://knowusuboaky.github.io/LLMAgentR/reference/index.html Build a Data Wrangling Agent. ```APIDOC ## build_data_wrangling_agent ### Description Build a Data Wrangling Agent. ### Function Signature `build_data_wrangling_agent()` ``` -------------------------------- ### Generate Mermaid PNG for Research Agent Workflow Source: https://knowusuboaky.github.io/LLMAgentR/articles/research-agent.html Builds the research agent and saves its workflow diagram as a Mermaid PNG. Requires an LLM wrapper and Tavily API key. ```R library(LLMAgentR) my_llm_wrapper <- function(prompt, verbose = FALSE) "LLM response placeholder" workflow <- build_researcher_agent( llm = my_llm_wrapper, tavily_search = "your-tavily-key", output = "both", direction = "LR" ) save_mermaid_png( x = workflow, file = "pkgdown/assets/research-agent-workflow.png" ) ``` -------------------------------- ### State Graph Utilities for Custom Agents Source: https://knowusuboaky.github.io/LLMAgentR/reference/index.html Utilities for defining state graph components, including nodes, edges, and commands, for custom agents. ```python make_node() make_edge() make_command() interrupt() StateGraph() ``` -------------------------------- ### Generate Mermaid PNG for Document Summarizer Workflow Source: https://knowusuboaky.github.io/LLMAgentR/articles/document-summarizer-agent.html Builds the document summarizer agent and saves its workflow diagram as a Mermaid PNG. Requires the LLMAgentR library and a custom LLM wrapper function. ```R library(LLMAgentR) my_llm_wrapper <- function(prompt, verbose = FALSE) "LLM response placeholder" workflow <- build_doc_summarizer_agent( llm = my_llm_wrapper, output = "both", direction = "LR" ) save_mermaid_png( x = workflow, file = "pkgdown/assets/document-summarizer-agent-workflow.png" ) ``` -------------------------------- ### Build the Research Agent Source: https://knowusuboaky.github.io/LLMAgentR/articles/research-agent.html Initializes the research agent with specified LLM, search parameters, and retry configurations. The Tavily API key can be provided directly or via environment variable. ```R library(LLMAgentR) my_llm_wrapper <- function(prompt, verbose = FALSE) "LLM response placeholder" researcher <- build_researcher_agent( llm = my_llm_wrapper, tavily_search = NULL, # uses Sys.getenv("TAVILY_API_KEY") max_results = 5, max_tries = 3, backoff = 2, verbose = FALSE ) ``` -------------------------------- ### Run Visualization Agent with State Source: https://knowusuboaky.github.io/LLMAgentR/articles/visualization-agent.html Executes the visualization agent with an initial state object containing raw data, target variable, user instructions, and retry parameters. The agent returns the final state after processing. ```R initial_state <- list( data_raw = mtcars, target_variable = "mpg", user_instructions = "Create a clean scatter plot of wt vs mpg with color by cyl.", max_retries = 3, retry_count = 0 ) final_state <- viz_agent(initial_state) str(final_state) ``` -------------------------------- ### Build Document Summarizer Agent Source: https://knowusuboaky.github.io/LLMAgentR/reference/build_doc_summarizer_agent.html Builds the document summarizer agent. Specify the LLM function, optional summary template, chunk size, overlap, verbosity, output type, and diagram direction. The agent function returned accepts file paths or text input. ```R build_doc_summarizer_agent( llm, summary_template = NULL, chunk_size = 4000, overlap = 200, verbose = TRUE, output = c("agent", "mermaid", "both"), direction = c("TD", "LR"), subgraphs = NULL, style = TRUE ) ``` -------------------------------- ### Configure OpenWeatherMap API Key Source: https://knowusuboaky.github.io/LLMAgentR/articles/weather-agent.html Sets the OpenWeatherMap API key as an environment variable. This is a prerequisite for the weather agent to authenticate with the OpenWeatherMap API. ```R Sys.setenv(OPENWEATHERMAP_API_KEY = "your-key") ``` -------------------------------- ### Initialize and Use Researcher Agent Source: https://knowusuboaky.github.io/LLMAgentR/reference/build_researcher_agent.html Initializes the researcher agent with specified parameters and performs a research query. Ensure your Tavily API key is set as an environment variable or passed directly. ```r if (FALSE) { # \dontrun{ # Initialize researcher agent researcher_agent <- build_researcher_agent( llm = my_llm_wrapper, tavily_search = NULL, system_prompt = NULL, max_results = 5, max_tries = 3, backoff = 2, verbose = FALSE ) # Perform research result <- researcher_agent("Who is Messi?") } # } ```