### Register Tools with an Agent Source: https://github.com/feddelegrand7/mini007/blob/main/docs/tools.html Demonstrates how to register multiple tools with an agent using the `register_tools` method. This example registers weather-related tools for a weather assistant agent. ```r library(mini007) openai_4_1 <- ellmer::chat( name = "openai/gpt-4.1", credentials = function() {Sys.getenv("OPENAI_API_KEY")}, echo = "none" ) weather_agent <- Agent$new( name = "weather_assistant", instruction = "You are a weather assistant.", llm_object = openai_4_1 ) weather_function_algiers <- function() { msg <- glue::glue( "35 degrees Celcius, it's sunny and there's no precipitation." ) msg } get_weather_in_algiers <- ellmer::tool( fun = weather_function_algiers, name = "get_weather_in_algiers", description = "Provide the current weather in Algiers, Algeria." ) weather_function_berlin <- function() { msg <- glue::glue( "10 degrees Celcius, it's cold" ) msg } get_weather_in_berlin <- ellmer::tool( fun = weather_function_berlin, name = "get_weather_in_berlin", description = "Provide the current weather in Berlin, Germany" ) weather_agent$register_tools( tools = list( get_weather_in_algiers, get_weather_in_berlin ) ) ``` -------------------------------- ### Install mini007 Package Source: https://github.com/feddelegrand7/mini007/blob/main/README.md Install the mini007 package from CRAN. Ensure you have R installed. ```r install.packages("mini007") ``` -------------------------------- ### Initialize ClipboardJS Source: https://github.com/feddelegrand7/mini007/blob/main/docs/leadagent.html Initializes ClipboardJS for copying code. It handles both standard copy buttons and those within Quarto modals, using the 'getTextToCopy' function to get the content. ```javascript const clipboard = new window.ClipboardJS('.code-copy-button:not([data-in-quarto-modal])', { text: getTextToCopy }); clipboard.on('success', onCopySuccess); if (window.document.getElementById('quarto-embedded-source-code-modal')) { const clipboardModal = new window.ClipboardJS('.code-copy-button[data-in-quarto-modal]', { text: getTextToCopy, container: window.document.getElementById('quarto-embedded-source-code-modal') }); clipboardModal.on('success', onCopySuccess); } ``` -------------------------------- ### Manage Agents with LeadAgent Source: https://context7.com/feddelegrand7/mini007/llms.txt Demonstrates how to initialize agents, register them to a LeadAgent, and manage the agent collection through registration, removal, and clearing. ```r openai_4_1_mini <- ellmer::chat( name = "openai/gpt-4.1-mini", api_key = Sys.getenv("OPENAI_API_KEY"), echo = "none" ) researcher <- Agent$new( name = "researcher", instruction = "You are a research assistant.", llm_object = openai_4_1_mini ) summarizer <- Agent$new( name = "summarizer", instruction = "You summarize text.", llm_object = openai_4_1_mini ) translator <- Agent$new( name = "translator", instruction = "You translate to German.", llm_object = openai_4_1_mini ) lead_agent <- LeadAgent$new(name = "Leader", llm_object = openai_4_1_mini) # Register agents lead_agent$register_agents(c(researcher, summarizer, translator)) # Agent(s) successfully registered. # View registered agents lapply(lead_agent$agents, function(x) x$name) # [[1]] [1] "researcher" # [[2]] [1] "summarizer" # [[3]] [1] "translator" # Remove specific agent by ID lead_agent$remove_agents(translator$agent_id) lapply(lead_agent$agents, function(x) x$name) # [[1]] [1] "researcher" # [[2]] [1] "summarizer" # Clear all agents lead_agent$clear_agents() length(lead_agent$agents) # [1] 0 ``` -------------------------------- ### Highlight Code Lines Source: https://github.com/feddelegrand7/mini007/blob/main/docs/leadagent.html Selects and highlights specific lines of code based on annotation data. This is used for interactive code examples. ```javascript let selectedAnnoteEl; const selectorForAnnotation = ( cell, annotation) => { let cellAttr = 'data-code-cell="' + cell + '"'; let lineAttr = 'data-code-annotation="' + annotation + '"'; const selector = 'span[' + cellAttr + '][' + lineAttr + ']'; return selector; } const selectCodeLines = (annoteEl) => { const doc = window.document; const targetCell = annoteEl.getAttribute("data-target-cell"); const targetAnnotation = annoteEl.getAttribute("data-target-annotation"); const annoteSpan = window.document.querySelector(selectorForAnnotation(targetCell, targetAnnotation)); const lines = annoteSpan.getAttribute("data-code-lines").split(","); const lineIds = lines.map((line) => { return targetCell + "-" + line; }) let top = null; let height = null; let parent = null; if (lineIds.length > 0) { //compute the position of the single el (top and bottom and make a div) const el = window.document.getElementById(lineIds[0]); top = el.offsetTop; height = el.offsetHeight; parent = el.parentElement.parentElement; if (lineIds.length > 1) { const lastEl = window.document.getElementById(lineIds[lineIds.length - 1]); const bottom = lastEl.offsetTop + lastEl.offsetHeight; height = bottom - top; } if (top !== null && height !== null && parent !== null) { // cook up a div (if necessary) and position it let div = window.document.getElementById("code-annotation-line-highlight"); if (div === null) { div = window.document.createElement("div"); div.setAttribute("id", "code-annotat ``` -------------------------------- ### Visualize Orchestration Plan with LeadAgent$visualize_plan() Source: https://context7.com/feddelegrand7/mini007/llms.txt Generates a diagram of the agent sequence. Requires the DiagrammeR package to render the output. ```r openai_4_1_mini <- ellmer::chat( name = "openai/gpt-4.1-mini", api_key = Sys.getenv("OPENAI_API_KEY"), echo = "none" ) researcher <- Agent$new( name = "researcher", instruction = "You are a research assistant.", llm_object = openai_4_1_mini ) summarizer <- Agent$new( name = "summarizer", instruction = "You summarize text.", llm_object = openai_4_1_mini ) lead_agent <- LeadAgent$new(name = "Leader", llm_object = openai_4_1_mini) lead_agent$register_agents(c(researcher, summarizer)) # Generate a plan first lead_agent$generate_plan("Research quantum computing and summarize it") # Visualize the plan (requires DiagrammeR package) lead_agent$visualize_plan() # Displays a left-to-right diagram: [researcher] -> [summarizer] # Hovering shows the delegated prompt for each agent ``` -------------------------------- ### Agent Conversation Reset Source: https://context7.com/feddelegrand7/mini007/llms.txt Clear the conversation history while preserving the current system prompt. Starts a fresh conversation without recreating the agent. ```APIDOC ## Agent$reset_conversation_history() ### Description Clear the conversation history while preserving the current system prompt. Starts a fresh conversation without recreating the agent. ### Method `reset_conversation_history()` ### Parameters None ### Request Example ```r # Reset the conversation agent$reset_conversation_history() ``` ### Response Example - Confirmation message indicating that the conversation history has been reset and the system prompt is preserved. ``` -------------------------------- ### Code Annotation Helper Function Source: https://github.com/feddelegrand7/mini007/blob/main/docs/leadagent.html A helper function to determine if an element is part of a code annotation. It checks if any of the element's classes start with 'code-annotation-'. ```javascript const isCodeAnnotation = (el) => { for (const clz of el.classList) { if (clz.startsWith('code-annotation-')) { return true; } } return false; } ``` -------------------------------- ### Create an Agent instance Source: https://github.com/feddelegrand7/mini007/blob/main/docs/agents.html Instantiate an Agent object by providing a name, system instructions, and the underlying LLM object. ```R polar_bear_researcher <- Agent$new( name = "POLAR BEAR RESEARCHER", instruction = "You are an expert in polar bears, you task is to collect information about polar bears. Answer in 1 sentence max.", llm_object = openai_4_1_mini ) ``` -------------------------------- ### Initialize OpenAI Chat Client Source: https://github.com/feddelegrand7/mini007/blob/main/docs/leadagent.html Sets up an ellmer chat object using an OpenAI API key retrieved from environment variables. ```R library(mini007) retrieve_open_ai_credential <- function() { Sys.getenv("OPENAI_API_KEY") } openai_4_1_mini <- ellmer::chat( name = "openai/gpt-4.1-mini", credentials = retrieve_open_ai_credential, echo = "none" ) ``` -------------------------------- ### Initialize and Register Agents with LeadAgent Source: https://context7.com/feddelegrand7/mini007/llms.txt Create specialized agents and register them with a LeadAgent to enable automated task decomposition. ```r library(mini007) openai_4_1_mini <- ellmer::chat( name = "openai/gpt-4.1-mini", api_key = Sys.getenv("OPENAI_API_KEY"), echo = "none" ) # Create specialized agents researcher <- Agent$new( name = "researcher", instruction = "You are a research assistant. Answer factual questions with detailed and accurate information. Do not answer with more than 2 lines.", llm_object = openai_4_1_mini ) summarizer <- Agent$new( name = "summarizer", instruction = "You are an agent designed to summarise a given text into 3 distinct bullet points.", llm_object = openai_4_1_mini ) translator <- Agent$new( name = "translator", instruction = "Your role is to translate a text from English to German", llm_object = openai_4_1_mini ) # Create the LeadAgent (no instruction needed - it has built-in task decomposition) lead_agent <- LeadAgent$new( name = "Leader", llm_object = openai_4_1_mini ) # Register the specialized agents lead_agent$register_agents(c(researcher, summarizer, translator)) # Agent(s) successfully registered. # View registered agents lapply(lead_agent$agents, function(x) x$name) # [[1]] [1] "researcher" # [[2]] [1] "summarizer" # [[3]] [1] "translator" ``` -------------------------------- ### Get Color Scheme Sentinel Source: https://github.com/feddelegrand7/mini007/blob/main/docs/index.html Retrieves the current color scheme preference from localStorage or a local variable. Returns 'alternate' for dark mode, 'default' for light mode, or null if not set. ```javascript const getColorSchemeSentinel = () => { if (!isFileUrl()) { const storageValue = window.localStorage.getItem("quarto-color-scheme"); return storageValue != null ? storageValue : localAlternateSentinel; } else { return localAlternateSentinel; } } ``` -------------------------------- ### Create and Invoke an Agent Source: https://context7.com/feddelegrand7/mini007/llms.txt Demonstrates creating an Agent with a specific role and LLM, then invoking it with a prompt. Accesses agent ID and conversation history. ```r library(mini007) # Create an LLM object using ellmer openai_4_1_mini <- ellmer::chat( name = "openai/gpt-4.1-mini", api_key = Sys.getenv("OPENAI_API_KEY"), echo = "none" ) # Create an Agent with a specific role polar_bear_researcher <- Agent$new( name = "POLAR BEAR RESEARCHER", instruction = "You are an expert in polar bears. Answer in 1 sentence max.", llm_object = openai_4_1_mini ) # Each agent has a unique ID polar_bear_researcher$agent_id # [1] "a1b2c3d4-e5f6-7890-abcd-ef1234567890" # Invoke the agent with a prompt response <- polar_bear_researcher$invoke("Are polar bears dangerous for humans?") # [1] "Yes, polar bears can be extremely dangerous to humans..." # Access conversation history polar_bear_researcher$messages # [[1]] # $role # [1] "system" # $content # [1] "You are an expert in polar bears..." # [[2]] # $role # [1] "user" # $content # [1] "Are polar bears dangerous for humans?" # [[3]] # $role # [1] "assistant" # $content # [1] "Yes, polar bears can be extremely dangerous..." ``` -------------------------------- ### Configure and Register LeadAgent Source: https://github.com/feddelegrand7/mini007/blob/main/docs/leadagent.html Initializes the LeadAgent and registers the previously created agents to it for task orchestration. ```R lead_agent <- LeadAgent$new( name = "Leader", llm_object = openai_4_1_mini ) lead_agent$register_agents(c(researcher, summarizer, translator)) lapply(lead_agent$agents, function(x) {x$name}) ``` -------------------------------- ### Get Text to Copy for Clipboard Source: https://github.com/feddelegrand7/mini007/blob/main/docs/leadagent.html Retrieves the inner text of a code element, excluding any code annotation elements, for clipboard copying. It clones the parent element to avoid modifying the original DOM. ```javascript const getTextToCopy = function(trigger) { const outerScaffold = trigger.parentElement.cloneNode(true); const codeEl = outerScaffold.querySelector('code'); for (const childEl of codeEl.children) { if (isCodeAnnotation(childEl)) { childEl.remove(); } } return codeEl.innerText; } ``` -------------------------------- ### Agent Class Initialization Source: https://context7.com/feddelegrand7/mini007/llms.txt Defines how to instantiate a new Agent with a specific role, instruction, and LLM object. ```APIDOC ## Agent$new() ### Description Creates a new instance of an Agent with a unique identity and persistent message history. ### Parameters - **name** (string) - Required - The name of the agent. - **instruction** (string) - Required - The system prompt or role definition for the agent. - **llm_object** (object) - Required - An ellmer chat model object. ### Request Example agent <- Agent$new(name = "Researcher", instruction = "You are an expert.", llm_object = openai_model) ``` -------------------------------- ### CEO2's Second Response Source: https://github.com/feddelegrand7/mini007/blob/main/docs/leadagent.html The second CEO agent rejects CEO1's high-budget proposal due to cost constraints and suggests a phased, cost-effective strategy starting with digital marketing and micro-influencers. ```text Your large-scale, high-budget approach clearly conflicts with my core constraint of maintaining a low marketing spend; therefore, I counterpropose a phased strategy that begins with focused digital marketing and micro-influencer collaborations to build brand awareness cost-effectively in Germany, with potential gradual scaling depending on export growth and budget availability over the next two years. ``` -------------------------------- ### Get Color Scheme Sentinel Source: https://github.com/feddelegrand7/mini007/blob/main/docs/NEWS.html Retrieves the current color scheme preference from local storage or a local variable. Returns 'alternate' if the alternate theme is set, otherwise 'default'. Handles file URLs differently. ```javascript const getColorSchemeSentinel = () => { if (!isFileUrl()) { const storageValue = window.localStorage.getItem("quarto-color-scheme"); return storageValue != null ? storageValue : localAlternateSentinel; } else { return localAlternateSentinel; } } ``` -------------------------------- ### Initialize CEO Agents and Lead Agent Source: https://github.com/feddelegrand7/mini007/blob/main/docs/leadagent.html Initializes two CEO agents with distinct instructions regarding marketing strategy and budget, and a LeadAgent to manage their dialogue. Uses the openai_4_1_mini LLM object. ```R ceo1 <- Agent$new( name = "ceo1", instruction = paste0( "You are a CEO in a dates company based in Ouergla, Algeria, ", "You want to boost their exports to Germany. ", "You don't care about the budget. You want to spend as much as possible. " ), llm_object = openai_4_1_mini ) ceo2 <- Agent$new( name = "ceo2", instruction = paste0( "You are the CEO of a dates company based in Ouergla, Algeria. ", "You are considering starting a marketing compaign to boost the exports to Germany. ", "For you the marketing budget is super important and you don't want to spend too much. " ), llm_object = openai_4_1_mini ) lead_agent <- LeadAgent$new( name = "Leader", llm_object = openai_4_1_mini ) ``` -------------------------------- ### Initialize Quarto Document UI Source: https://github.com/feddelegrand7/mini007/blob/main/docs/testing.html Configures document-level UI elements including color scheme toggles, anchor links, and clipboard copy functionality. ```JavaScript window.document.addEventListener("DOMContentLoaded", function (event) { // Ensure there is a toggle, if there isn't float one in the top right if (window.document.querySelector('.quarto-color-scheme-toggle') === null) { const a = window.document.createElement('a'); a.classList.add('top-right'); a.classList.add('quarto-color-scheme-toggle'); a.href = ""; a.onclick = function() { try { window.quartoToggleColorScheme(); } catch {} return false; }; const i = window.document.createElement("i"); i.classList.add('bi'); a.appendChild(i); window.document.body.appendChild(a); } setColorSchemeToggle(hasAlternateSentinel()) const icon = ""; const anchorJS = new window.AnchorJS(); anchorJS.options = { placement: 'right', icon: icon }; anchorJS.add('.anchored'); const isCodeAnnotation = (el) => { for (const clz of el.classList) { if (clz.startsWith('code-annotation-')) { return true; } } return false; } const onCopySuccess = function(e) { // button target const button = e.trigger; // don't keep focus button.blur(); // flash "checked" button.classList.add('code-copy-button-checked'); var currentTitle = button.getAttribute("title"); button.setAttribute("title", "Copied!"); let tooltip; if (window.bootstrap) { button.setAttribute("data-bs-toggle", "tooltip"); button.setAttribute("data-bs-placement", "left"); button.setAttribute("data-bs-title", "Copied!"); tooltip = new bootstrap.Tooltip(button, { trigger: "manual", customClass: "code-copy-button-tooltip", offset: [0, -8]}); tooltip.show(); } setTimeout(function() { if (tooltip) { tooltip.hide(); button.removeAttribute("data-bs-title"); button.removeAttribute("data-bs-toggle"); button.removeAttribute("data-bs-placement"); } button.setAttribute("title", currentTitle); button.classList.remove('code-copy-button-checked'); }, 1000); // clear code selection e.clearSelection(); } const getTextToCopy = function(trigger) { const outerScaffold = trigger.parentElement.cloneNode(true); const codeEl = outerScaffold.querySelector('code'); for (const childEl of codeEl.children) { if (isCodeAnnotation(childEl)) { childEl.remove(); } } return codeEl.innerText; } const clipboard = new window.ClipboardJS('.code-copy-button:not([data-in-quarto-modal])', { text: getTextToCopy }); clipboard.on('success', onCopySuccess); if (window.document.getElementById('quarto-embedded-source-code-modal')) { const clipboardModal = new window.ClipboardJS('.code-copy-button[data-in-quarto-modal]', { text: getTextToCopy, container: window.document.getElementById('quarto-embedded-source-code-modal') }); clipboardModal.on('success', onCopySuccess); } var localhostRegex = new RegExp(/^(?:http|https):\/\/localhost\:?[0-9]*\//); var mailtoRegex = new RegExp(/^mailto:/); var filterRegex = new RegExp('/' + window.location.host + '/'); var isInternal = (href) => { return filterRegex.test(href) || localhostRegex.test(href) || mailtoRegex.test(href); } // Inspect non-navigation links and adorn them if external var links = window.document.querySelectorAll('a[href]:not(.nav-link):not(.navbar-brand):not(.toc-action):not(.sidebar-link):not(.sidebar-item-toggle):not(.pagination-link):not(.no-external):not([aria-hidden]):not(.dropdown-item):not(.quarto-navigation-tool):not(.about-link)'); for (var i=0; i res.text()) .then(html => { const parser = new DOMParser(); const htmlDoc = parser.parseFromString(html, "text/html"); const note = htmlDoc.getElementById(id); if (note !== null) { const html = processXRef(id, note); instance.setContent(html); } }).finally(() => { instance.enable(); instance.show(); }); } } else { // See if we can fetch a full url (with no hash to target) // This is a special case and we should probably do some content thinning / targeting fetch(url) .then(res => res.text()) .then(html => { const parser = new DOMParser(); const htmlDoc = parser.parseFromString(html, "text/html"); const note = htmlDoc.querySelector('main.content'); if (note !== null) { // This should only happen for chapter cross references // (since there is no id in the URL) // remove the first header if (note.children.length > 0 && note.children[0].tagName === "HEADER") { note.children[0].remove(); } const html = processXRef(null, note); instance.setContent(html); } }).finally(() => { instance.enable(); instance.show(); }); } }, function(instance) { }); } ``` -------------------------------- ### List Available Tools for an Agent Source: https://github.com/feddelegrand7/mini007/blob/main/docs/tools.html Lists all the tools that have been registered with an agent. This is useful for verifying which tools are currently available for the agent to use. ```r weather_agent$list_tools() ``` -------------------------------- ### Initialize Tippy.js Tooltips for Footnotes Source: https://github.com/feddelegrand7/mini007/blob/main/docs/NEWS.html Configures Tippy.js to display footnote content in tooltips when hovering over footnote references. Ensure Tippy.js is loaded before this script. ```javascript const tippyHover = (el, contentFn, onShowFn, onHideFn) => { const config = { allowHTML: true, content: 'A Tooltip', trigger: 'mouseenter focus', delay: [200, 0], offset: [0, 5], dragDelay: 100, maxWidth: 350, animation: 'scale', arrow: false, appendTo: function(el) { return el.parentElement; }, interactive: true, interactiveBorder: 10, theme: 'quarto', placement: 'bottom-start', }; if (contentFn) { config.content = contentFn; } if (onTriggerFn) { config.onTrigger = onTriggerFn; } if (onUntriggerFn) { config.onUntrigger = onUntriggerFn; } window.tippy(el, config); } ``` -------------------------------- ### Initialize Annotation and Citation Handlers Source: https://github.com/feddelegrand7/mini007/blob/main/docs/tools.html Event listeners for clicking annotation targets and logic to populate bibliographic reference popups. ```javascript window.addEventListener( "resize", throttle(() => { elRect = undefined; if (selectedAnnoteEl) { selectCodeLines(selectedAnnoteEl); } }, 10) ); // Attach click handler to the DT const annoteDls = window.document.querySelectorAll('dt[data-target-cell]'); for (const annoteDlNode of annoteDls) { annoteDlNode.addEventListener('click', (event) => { const clickedEl = event.target; if (clickedEl !== selectedAnnoteEl) { unselectCodeLines(); const activeEl = window.document.querySelector('dt[data-target-cell].code-annotation-active'); if (activeEl) { activeEl.classList.remove('code-annotation-active'); } selectCodeLines(clickedEl); clickedEl.classList.add('code-annotation-active'); } else { // Unselect the line unselectCodeLines(); clickedEl.classList.remove('code-annotation-active'); } }); } const findCites = (el) => { const parentEl = el.parentElement; if (parentEl) { const cites = parentEl.dataset.cites; if (cites) { return { el, cites: cites.split(' ') }; } else { return findCites(el.parentElement) } } else { return undefined; } }; var bibliorefs = window.document.querySelectorAll('a[role="doc-biblioref"]'); for (var i=0; i res.text()) .then(html => { const parser = new DOMParser(); const htmlDoc = parser.parseFromString(html, "text/html"); const note = htmlDoc.getElementById(id); if (note !== null) { const html = processXRef(id, note); instance.setContent(html); } }).finally(() => { instance.enable(); instance.show(); }); } } else { // See if we can fetch a full url (with no hash to target) // This is a special case and we should probably do some content thinning / targeting fetch(url) .then(res => res.text()) .then(html => { const parser = new DOMParser(); const htmlDoc = parser.parseFromString(html, "text/html"); const note = htmlDoc.querySelector('main.content'); if (note !== null) { // This should only happen for chapter cross references // (since there is no id in the URL) // remove the first header if (note.children.length > 0 && note.children[0].tagName === "HEADER") { note.children[0].remove(); } const html = processXRef(null, note); instance.setContent(html); } }).finally(() => { instance.enable(); instance.show(); }); } }, function(instance) { }); } ``` -------------------------------- ### Configure Navigation Bar Settings Source: https://github.com/feddelegrand7/mini007/blob/main/docs/leadagent.html Defines the JSON configuration for the project's navigation bar, including search settings and keyboard shortcuts. ```json { "location": "navbar", "copy-button": false, "collapse-after": 3, "panel-placement": "end", "type": "overlay", "limit": 50, "keyboard-shortcut": [ "f", "/", "s" ], "show-item-context": false, "language": { "search-no-results-text": "No results", "search-matching-documents-text": "matching documents", "search-copy-link-title": "Copy link to search", "search-hide-matches-text": "Hide additional matches", "search-more-match-text": "more match in this document", "search-more-matches-text": "more matches in this document", "search-clear-button-title": "Clear", "search-text-placeholder": "", "search-submit-button-title": "Submit", "search-label": "Search" } } ``` -------------------------------- ### Initialize Tooltips for Bibliographic References Source: https://github.com/feddelegrand7/mini007/blob/main/docs/index.html Iterates through all elements with the role 'doc-biblioref' and uses the 'findCites' function to locate associated citation data. For each reference, it initializes a 'tippyHover' tooltip that displays the full citation content fetched from corresponding 'ref-' elements. ```javascript var bibliorefs = window.document.querySelectorAll('a[role="doc-biblioref"]'); for (var i=0; i