<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Luis Majano on Medium]]></title>
        <description><![CDATA[Stories by Luis Majano on Medium]]></description>
        <link>https://medium.com/@lmajano?source=rss-6f061cffa24a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ZFvzA2JNLOoRJITE.</url>
            <title>Stories by Luis Majano on Medium</title>
            <link>https://medium.com/@lmajano?source=rss-6f061cffa24a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 21:06:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lmajano/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Develop AI Agents Using BoxLang AI: A Practical Guide]]></title>
            <link>https://medium.com/@lmajano/how-to-develop-ai-agents-using-boxlang-ai-a-practical-guide-3fd0bb19e71e?source=rss-6f061cffa24a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fd0bb19e71e</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[boxlang]]></category>
            <category><![CDATA[enterprise-ai]]></category>
            <category><![CDATA[jvm]]></category>
            <dc:creator><![CDATA[Luis Majano]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 12:38:56 GMT</pubDate>
            <atom:updated>2026-04-06T12:38:56.341Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MiB0pBGG6OTeMvg6ndNOCQ.jpeg" /></figure><p>AI agents are transforming how we build software. Unlike traditional chatbots that just answer questions, agents can reason about what tools they need, decide when to use them, chain multiple actions together, and remember what happened earlier in a conversation.</p><p>In this tutorial, I’ll show you how to build a real-world AI agent using [BoxLang AI](<a href="https://ai.boxlang.io/">https://ai.boxlang.io</a>) — the official AI framework for the BoxLang JVM language. We’ll build **SupportBot**, an e-commerce customer support agent that can look up orders, check inventory, issue refunds, and answer questions grounded in your knowledge base.</p><p>By the end you’ll understand how AI agents work under the hood, and you’ll have a fully working agent you can adapt for your own domain.</p><p>## What I’ll Cover</p><p>- [Prerequisites](#prerequisites)<br>- [What Are AI Agents?](#what-are-ai-agents)<br>- [What Is BoxLang AI?](#what-is-boxlang-ai)<br>- [Core Concept 1: Tools](#core-concept-1-tools)<br>- [Core Concept 2: Memory](#core-concept-2-memory)<br>- [Core Concept 3: The Agent](#core-concept-3-the-agent)<br>- [How to Put It All Together](#how-to-put-it-all-together)<br>- [Streaming Responses](#streaming-responses)<br>- [How the Agent Thinks](#how-the-agent-thinks)<br>- [Going Further](#going-further)<br>- [Conclusion](#conclusion)</p><p>— -</p><p>## Prerequisites</p><p>Before diving in, you should be comfortable with:</p><p>**BoxLang basics** — You should know how to write BoxLang scripts, work with structs and arrays, and understand closures. If you’re new, start with the [Quick Start Guide](<a href="https://boxlang.ortusbooks.com/getting-started/overview">https://boxlang.ortusbooks.com/getting-started/overview</a>).</p><p>**Basic LLM familiarity** — Knowing what a large language model is and having used one (via `aiChat()` or similar) will help you follow along.</p><p>### Step 1 — Install BoxLang</p><p>Download and install BoxLang from [boxlang.io](<a href="https://boxlang.io/">https://boxlang.io</a>), or use BVM (BoxLang Version Manager) to manage multiple versions:</p><p>```bash<br># Install BVM<br>/bin/bash -c “$(curl -fsSL <a href="https://downloads.ortussolutions.com/ortussolutions/bvm/install.sh">https://downloads.ortussolutions.com/ortussolutions/bvm/install.sh</a>)&quot;</p><p># Install the latest BoxLang<br>bvm install latest<br>bvm use latest</p><p># Verify<br>boxlang — version<br>```</p><p>### Step 2 — Install the `bx-ai` Module</p><p>Install `bx-ai` locally into your project using the built-in module installer:</p><p>```bash<br># Creates a boxlang_modules/ folder in your project<br>install-bx-module bx-ai — local<br>```</p><p>Your project structure will look like this:</p><p>```<br>my-project/<br>├── boxlang_modules/<br>│ └── bxai/ ← installed here<br>├── config/<br>│ └── boxlang.json ← BoxLang configuration<br>├── .env ← your API keys (never commit this)<br>├── .env.example ← template to share with your team<br>├── .gitignore<br>└── agent.bxs ← your BoxLang scripts<br>```</p><p>### Step 3 — Set Up Your `.env` File</p><p>Copy `.env.example` to `.env` and fill in at least one provider API key. Never commit `.env` to source control.</p><p>**`.env.example`** — commit this template so your team knows what keys are needed:</p><p>```bash<br># BoxLang Custom Configuration — points BoxLang at your config file<br>BOXLANG_CONFIG=./config/boxlang.json</p><p># AI Provider API Keys — fill in at least one<br>OPENAI_API_KEY=your-api-key<br>CLAUDE_API_KEY=your-api-key<br>GEMINI_API_KEY=your-api-key<br>GROK_API_KEY=your-api-key<br>GROQ_API_KEY=your-api-key<br>PERPLEXITY_API_KEY=your-api-key<br>OPENROUTER_API_KEY=your-api-key<br>MISTRAL_API_KEY=your-api-key<br>HUGGINGFACE_API_KEY=your-api-key<br>VOYAGE_API_KEY=your-api-key<br>COHERE_API_KEY=your-api-key<br># AWS Bedrock<br>AWS_ACCESS_KEY_ID=your-key<br>AWS_SECRET_ACCESS_KEY=your-secret<br>AWS_REGION=us-east-1<br>```</p><p>**`.env`** — your actual keys, never committed:</p><p>```bash<br>BOXLANG_CONFIG=./config/boxlang.json<br>OPENAI_API_KEY=sk-proj-…<br>```</p><p>Add `.env` to your `.gitignore`:</p><p>```<br>.env<br>boxlang_modules/<br>```</p><p>### Step 4 — Configure `config/boxlang.json`</p><p>BoxLang reads its configuration from the file pointed to by `BOXLANG_CONFIG`. The `${VAR_NAME}` syntax reads directly from your `.env` file — your keys never live in the config file itself.</p><p>**`config/boxlang.json`**:</p><p>```json<br>{<br> “modules”: {<br> “bxai”: {<br> “settings”: {<br> “provider”: “openai”,<br> “apiKey”: “${OPENAI_API_KEY}”,<br> “defaultParams”: {<br> “model”: “gpt-4o”,<br> “temperature”: 0.2<br> }<br> }<br> }<br> }<br>}<br>```</p><p>### Step 5 — Run Your First Script</p><p>Create `agent.bxs` and run it:</p><p>```js<br>// agent.bxs<br>answer = aiChat( “What is BoxLang AI in one sentence?” )<br>println( answer )<br>```</p><p>```bash<br>boxlang agent.bxs<br>```</p><p>That’s it — no build step, no compile, no server. BoxLang reads `.env` automatically, loads the `bxai` module from `boxlang_modules/`, and runs.</p><p>### Switching Providers</p><p>To switch from OpenAI to Claude, change two lines in `config/boxlang.json` and add the key to `.env`:</p><p>```json<br>{<br> “modules”: {<br> “bxai”: {<br> “settings”: {<br> “provider”: “claude”,<br> “apiKey”: “${CLAUDE_API_KEY}”,<br> “defaultParams”: {<br> “model”: “claude-sonnet-4–5–20251001”<br> }<br> }<br> }<br> }<br>}<br>```</p><p>Your `agent.bxs` code doesn’t change at all. This is the zero-vendor-lock-in promise in practice.</p><p>&gt; 💡 `bx-ai` supports 17 providers — OpenAI, Claude, Gemini, Ollama, Groq, and more. You can also run fully local AI with Ollama — no API key required, zero cost, complete privacy. See the [provider docs](<a href="https://ai.ortusbooks.com/">https://ai.ortusbooks.com</a>) for per-provider configuration.</p><p>— -</p><p>## What Are AI Agents?</p><p>Think of an AI agent as a chatbot that can *act*, not just respond. A traditional chatbot answers questions from what it knows. An agent can reach out and *do things* — query databases, call APIs, read files, send emails — and chain those actions together to solve multi-step problems.</p><p>```<br>┌─────────────────────────────────────────────────────────────┐<br>│ │<br>│ TRADITIONAL CHATBOT AI AGENT │<br>│ ────────────────── ──────── │<br>│ │<br>│ User ──► LLM ──► Answer User ──► Agent │<br>│ │ │<br>│ One shot. No tools. ├──► Tool A │<br>│ No memory. ├──► Tool B │<br>│ ├──► Memory │<br>│ └──► Answer │<br>│ │<br>│ Reasons. Acts. Remembers. │<br>└─────────────────────────────────────────────────────────────┘<br>```</p><p>Here’s a conversation with the SupportBot we’ll build:</p><p>```<br>User: “Where is order #ORD-78291? It was supposed to arrive yesterday.”</p><p>Agent: [Thinks: I need to look up that order]<br>Agent: [Calls get_order( orderId: “ORD-78291” )]<br>Agent: [Gets back: { status: “In Transit”, carrier: “FedEx”,<br> tracking: “794644792798”,<br> estimatedDelivery: “2026–04–04” }]</p><p>Agent: “Your order #ORD-78291 is in transit with FedEx<br> (tracking: 794644792798). It was delayed by one day<br> and is now estimated to arrive tomorrow, April 4th.”<br>```</p><p>The agent broke the problem down, picked the right tool, and synthesized the answer. This matters when:</p><p>- Queries don’t fit into predefined categories<br>- Answering requires combining data from multiple sources<br>- Users need to follow up on previous answers</p><p>— -</p><p>## What Is BoxLang AI?</p><p>BoxLang AI (`bx-ai`) is the official AI framework for BoxLang — a modern, dynamic JVM language. It provides a unified, fluent API for building AI agents, multi-model workflows, RAG pipelines, and AI-powered applications.</p><p>```<br>┌────────────────────────────────────────────────────────────────┐<br>│ BoxLang AI Stack │<br>├────────────────────────────────────────────────────────────────┤<br>│ │<br>│ Your Application Code │<br>│ ───────────────────────────────────────────────────────── │<br>│ aiAgent() aiChat() aiEmbed() aiMemory() aiTool() │<br>│ │<br>│ ───────────────────────────────────────────────────────── │<br>│ Skills │ Middleware │ Tool Registry │ Memory │ Pipelines │<br>│ │<br>│ ───────────────────────────────────────────────────────── │<br>│ OpenAI │ Claude │ Gemini │ Ollama │ Groq │ + 12 more │<br>│ │<br>└────────────────────────────────────────────────────────────────┘<br>```</p><p>Key properties that make it great for building agents:</p><p>- **One API, 17 providers** — switch from OpenAI to Claude by changing a config value, not code<br>- **`aiAgent()` BIF** — a fully featured agent with tools, memory, skills, and middleware<br>- **Fluent tool definition** — turn any closure into an AI-callable tool with `aiTool()`<br>- **Multi-tenant memory** — one agent instance safely handles thousands of concurrent users<br>- **JVM-native** — runs everywhere Java runs, with full Java interop</p><p>— -</p><p>## Core Concept 1: Tools</p><p>Tools are functions your AI agent can call. The framework passes the tool’s name, description, and parameter schema to the LLM, which decides when and how to call them. When the LLM decides to use a tool, BoxLang AI executes it and feeds the result back.</p><p>```<br>┌──────────────────────────────────────────────────────────────┐<br>│ How Tools Work │<br>│ │<br>│ ┌─────────┐ “I need order data” ┌──────────────────┐ │<br>│ │ LLM │ ─────────────────────── ► │ get_order() │ │<br>│ │ │ │ • name │ │<br>│ │ │ ◄─────────────────────── │ • description │ │<br>│ └─────────┘ { status, tracking } │ • parameters │ │<br>│ └──────────────────┘ │<br>│ │<br>│ The LLM reads the description to decide WHEN to call. │<br>│ BoxLang AI handles the execution and result passing. │<br>└──────────────────────────────────────────────────────────────┘<br>```</p><p>### Defining a Tool with `aiTool()`</p><p>The simplest way to create a tool is with the `aiTool()` BIF and a closure:</p><p>```js<br>getWeatherTool = aiTool(<br> “get_weather”,<br> “Get the current weather for a city. Use when the user asks about weather conditions.”,<br> ( required city ) =&gt; {<br> // In a real app you’d call a weather API here<br> return { temp: 72, condition: “sunny”, city: arguments.city }<br> }<br>)<br>```</p><p>The three arguments are: name, description, and callable. The description is what the LLM reads to decide whether this is the right tool — write it like you’re telling a colleague when to use it.</p><p>### A Real Tool: `get_order`</p><p>Here’s the first tool for our SupportBot. It looks up an order by ID:</p><p>```js<br>// OrderTools.bx<br>class {</p><p>property name=”orderService”;</p><p>function init( required any orderService ) {<br> variables.orderService = arguments.orderService<br> return this<br> }</p><p><a href="http://twitter.com/AITool">@AITool</a>( “Retrieve a single order by order ID. Use first when a customer mentions a specific order number. Always call this before attempting a refund or cancellation.” )<br> public struct function get_order( required string orderId ) {<br> var order = variables.orderService.findById( arguments.orderId )</p><p>if ( isNull( order ) ) {<br> return {<br> found : false,<br> orderId : arguments.orderId,<br> message : “Order #arguments.orderId# was not found. Please verify the order ID.”<br> }<br> }</p><p>return {<br> found : true,<br> orderId : order.getId(),<br> status : order.getStatus(),<br> carrier : order.getCarrier(),<br> trackingNumber : order.getTrackingNumber(),<br> estimatedDelivery: order.getEstimatedDelivery().dateFormat( “long” ),<br> items : order.getItems().map( item =&gt; {<br> return { name: item.getName(), qty: item.getQty(), price: item.getPrice() }<br> } ),<br> total : order.getTotal(),<br> summary : “Order ##arguments.orderId# — #order.getStatus()# — Est. delivery: #order.getEstimatedDelivery().dateFormat( ‘long’ )#”<br> }<br> }</p><p>}<br>```</p><p>A few things to notice:</p><p>**The `<a href="http://twitter.com/AITool">@AITool</a>` annotation** tells the `AIToolRegistry` scanner that this method is an AI-callable tool. The annotation value becomes the tool’s description. When you call `aiToolRegistry().scan( new OrderTools( orderService ), “support” )`, it registers `get_order@support` automatically.</p><p>**The return value includes a `summary` field.** Rather than making the LLM parse a raw struct, you pre-compute a one-sentence summary it can read directly. Return both the data (for detailed reasoning) and the summary (for quick reading).</p><p>**The not-found case returns a helpful struct instead of throwing.** The LLM sees `found: false` and the `message` and can relay that to the user clearly — far better than an unhandled exception.</p><p>### The Full `OrderTools` Class</p><p>```js<br>class {</p><p>property name=”orderService”;</p><p>function init( required any orderService ) {<br> variables.orderService = arguments.orderService<br> return this<br> }</p><p><a href="http://twitter.com/AITool">@AITool</a>( “Retrieve a single order by order ID. Use first when a customer mentions a specific order number.” )<br> public struct function get_order( required string orderId ) {<br> var order = variables.orderService.findById( arguments.orderId )<br> if ( isNull( order ) ) {<br> return { found: false, message: “Order #arguments.orderId# not found.” }<br> }<br> return {<br> found : true,<br> orderId : order.getId(),<br> status : order.getStatus(),<br> carrier : order.getCarrier(),<br> trackingNumber : order.getTrackingNumber(),<br> estimatedDelivery: order.getEstimatedDelivery().dateFormat( “long” ),<br> total : order.getTotal(),<br> summary : “Order ##arguments.orderId# — #order.getStatus()#”<br> }<br> }</p><p><a href="http://twitter.com/AITool">@AITool</a>( “Search a customer’s order history. Use when the customer asks about past orders, spending history, or recent purchases.” )<br> public struct function search_orders(<br> required string customerEmail,<br> string status = “”,<br> numeric limit = 10<br> ) {<br> var orders = variables.orderService.findByEmail(<br> email : arguments.customerEmail,<br> status : arguments.status,<br> limit : arguments.limit<br> )<br> return {<br> count : orders.len(),<br> orders : orders.map( o =&gt; { id: o.getId(), status: o.getStatus(), total: o.getTotal(), date: o.getCreatedAt().dateFormat( “short” ) } ),<br> summary: “Found #orders.len()# orders for #arguments.customerEmail#”<br> }<br> }</p><p><a href="http://twitter.com/AITool">@AITool</a>( “Issue a refund for a specific order. IMPORTANT: Only call this after confirming the order exists and the customer has explicitly requested a refund.” )<br> public struct function issue_refund(<br> required string orderId,<br> required string reason<br> ) {<br> var result = variables.orderService.refund(<br> orderId: arguments.orderId,<br> reason : arguments.reason<br> )<br> return {<br> success : result.isSuccess(),<br> refundId : result.getRefundId(),<br> amount : result.getAmount(),<br> processingDays: 5,<br> summary : result.isSuccess()<br> ? “Refund of $#result.getAmount()# issued for order ##arguments.orderId#. Allow 5 business days.”<br> : “Refund failed: #result.getError()#”<br> }<br> }</p><p>}<br>```</p><p>### Tool Design Principles</p><p>```<br>┌─────────────────────────────────────────────────────────────────┐<br>│ The 4 Tool Design Rules │<br>│ │<br>│ 1. DESCRIPTION ── Tell the LLM exactly when (and when NOT) │<br>│ to call this tool. Be specific. │<br>│ │<br>│ 2. SUMMARY ── Always return a pre-computed one-liner │<br>│ alongside raw data. Saves tokens. │<br>│ │<br>│ 3. NO THROWS ── Return { success: false, message: “…” } │<br>│ instead of throwing. LLM can relay errors. │<br>│ │<br>│ 4. CAP RESULTS ── Always use a limit param. Never return │<br>│ unbounded arrays to the LLM. │<br>└─────────────────────────────────────────────────────────────────┘<br>```</p><p>**Write the description like you’re training a new colleague:**</p><p>```js<br>// ❌ Vague — LLM won’t know when to call this<br><a href="http://twitter.com/AITool">@AITool</a>( “Gets order information” )</p><p>// ✅ Clear — tells the LLM exactly when and what<br><a href="http://twitter.com/AITool">@AITool</a>( “Retrieve a single order by order ID. Use first when a customer mentions<br> a specific order number. Do not call without an explicit order ID.” )<br>```</p><p>— -</p><p>## Core Concept 2: Memory</p><p>Memory is what separates a stateful agent from a stateless API call. Without memory, every message is processed in isolation. With memory, the agent carries the full conversation thread.</p><p>```<br>┌────────────────────────────────────────────────────────────────┐<br>│ Without Memory vs With Memory │<br>│ │<br>│ WITHOUT WITH │<br>│ ────────────────── ──────────────────── │<br>│ │<br>│ Turn 1: Turn 1: │<br>│ User: “My order is late” User: “My order is late” │<br>│ Agent: “Which order?” Agent: “Which order?” │<br>│ │<br>│ Turn 2: Turn 2: │<br>│ User: “ORD-78291” User: “ORD-78291” │<br>│ Agent: “Which order?” ❌ Agent: [looks up ORD-78291] ✅ │<br>│ │<br>│ Each call is isolated. Full context is preserved. │<br>└────────────────────────────────────────────────────────────────┘<br>```</p><p>BoxLang AI ships 20+ memory types. Here are the three you’ll use most.</p><p>### Window Memory — Short-Term Conversation History</p><p>Window memory keeps the last N messages. It’s the minimum you need for a coherent conversation:</p><p>```js<br>memory = aiMemory( “window”, config: { maxMessages: 20 } )<br>```</p><p>What the memory stores as a conversation builds:</p><p>```<br>After Turn 1:<br>┌─────────────────────────────────────────────────────┐<br>│ user │ “Where is order #ORD-78291?” │<br>│ assistant │ “Your order is in transit…” │<br>└─────────────────────────────────────────────────────┘</p><p>After Turn 2:<br>┌─────────────────────────────────────────────────────┐<br>│ user │ “Where is order #ORD-78291?” │<br>│ assistant │ “Your order is in transit…” │<br>│ user │ “When exactly will it arrive?” │<br>│ assistant │ “It’s estimated to arrive April 4th.” │<br>└─────────────────────────────────────────────────────┘<br>```</p><p>Without memory, “When exactly will it arrive?” has no context — “it” refers to nothing. With memory, the agent knows what “it” means.</p><p>### Cache Memory — Multi-Tenant Production</p><p>For web applications serving multiple users, you need one agent instance that’s safe across concurrent requests:</p><p>```js<br>memory = aiMemory( “cache” )<br>```</p><p>Every memory operation accepts `userId` and `conversationId` to route each read/write to the right isolated conversation:</p><p>```<br>┌──────────────────────────────────────────────────────────────┐<br>│ One Memory Instance, Many Users │<br>│ │<br>│ ┌──────────┐ │<br>│ │ Alice │──► add( msg, userId:”alice”, convId:”t-101&quot; ) │<br>│ └──────────┘ │ │<br>│ ▼ │<br>│ ┌────────────────┐ │<br>│ │ Cache Memory │ │<br>│ │ ──────────── │ │<br>│ ┌──────────┐ │ alice/t-101 │ │<br>│ │ Bob │──────────►│ bob/t-102 │ │<br>│ └──────────┘ │ carol/t-103 │ │<br>│ └────────────────┘ │<br>│ │ │<br>│ getAll( userId:”alice” ) ───────┘ Returns ONLY Alice’s │<br>│ messages. Bob isolated. │<br>└──────────────────────────────────────────────────────────────┘<br>```</p><p>When you pass `userId` and `conversationId` through `agent.run()` options, they flow automatically to all memory operations — no explicit wiring needed:</p><p>```js<br>// Same agent instance, fully isolated per user<br>agent.run( “My order is late.”, {}, { userId: “<a href="/service/mailto:alice@example.com">alice@example.com</a>”, conversationId: “ticket-101” } )<br>agent.run( “I need a refund.”, {}, { userId: “<a href="/service/mailto:bob@example.com">bob@example.com</a>”, conversationId: “ticket-102” } )<br>```</p><p>No per-user agent factories. No thread-local hacks. One instance handles thousands of concurrent users safely.</p><p>### Summary Memory — Long Conversations</p><p>For long support sessions, `summary` memory auto-compresses old messages to preserve context without token bloat:</p><p>```js<br>memory = aiMemory( “summary”, config: {<br> maxMessages : 40,<br> summaryThreshold : 20,<br> summaryModel : “gpt-4o-mini” // use a cheap model for summarization<br>} )<br>```</p><p>```<br> How Summary Memory Works</p><p>Messages 1–20 accumulate normally…</p><p>At message 21:<br> ┌──────────────────────────────────────────────────┐<br> │ Messages 1–20 ──► LLM summarizes ──► │<br> │ “Customer reported damaged item on order │<br> │ ORD-78291. Refund of $89.99 discussed.” │<br> └──────────────────────────────────────────────────┘<br> │<br> ▼<br> ┌──────────────────────────────────────────────────┐<br> │ [SUMMARY] + Messages 21–40 │<br> │ Full context preserved, fraction of the tokens │<br> └──────────────────────────────────────────────────┘<br>```</p><p>— -</p><p>## Core Concept 3: The Agent</p><p>With tools and memory defined, the agent is the piece that ties them together. In BoxLang AI, `aiAgent()` is a single BIF call that gives you a fully autonomous agent.</p><p>```<br>┌──────────────────────────────────────────────────────────────┐<br>│ The Agent is the Glue │<br>│ │<br>│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │<br>│ │ Tools │ │ Memory │ │ Skills │ │<br>│ └────┬─────┘ └────┬─────┘ └────┬─────┘ │<br>│ │ │ │ │<br>│ └──────────────┼──────────────┘ │<br>│ │ │<br>│ ┌────▼─────┐ │<br>│ │ Agent │◄── Instructions │<br>│ │ │◄── Middleware │<br>│ └────┬─────┘ │<br>│ │ │<br>│ ┌────▼─────┐ │<br>│ │ LLM │ (any of 17 providers) │<br>│ └──────────┘ │<br>└──────────────────────────────────────────────────────────────┘<br>```</p><p>### The Simplest Possible Agent</p><p>```js<br>// Window memory by default with 20 messages<br>agent = aiAgent(<br> name : “SupportBot”,<br> tools : [ getOrderTool, searchOrdersTool, issueRefundTool ]<br>)</p><p>response = agent.run( “Where is order #ORD-78291?” )<br>println( response )<br>```</p><p>That’s it. The agent handles the full reasoning loop: deciding when to call tools, passing results back to the LLM, and producing a final response.</p><p>### Giving the Agent an Identity</p><p>A well-defined `description` and `instructions` dramatically improve agent behavior:</p><p>```js<br>agent = aiAgent(<br> name : “SupportBot”,<br> description : “Customer support specialist for Acme Store. Expert in orders, shipping, returns, and product questions.”,<br> instructions : “<br> You are a friendly and efficient customer support agent.<br> Always look up order details before discussing specific orders.<br> Confirm refund requests explicitly before calling issue_refund.<br> Lead with the direct answer, then add supporting detail.<br> If you cannot resolve an issue, offer to escalate to a human agent.<br> “,<br> tools : [ getOrderTool, searchOrdersTool, issueRefundTool ],<br> memory : aiMemory( “cache” )<br>)<br>```</p><p>### The Agent Run Lifecycle</p><p>```<br>┌──────────────────────────────────────────────────────────────┐<br>│ Agent Run Lifecycle │<br>│ │<br>│ agent.run( “My order is late” ) │<br>│ │ │<br>│ ▼ │<br>│ ┌─────────────────────────────────────────────────────┐ │<br>│ │ 1. Resolve userId / conversationId for this call │ │<br>│ │ 2. Build system message (description + instructions│ │<br>│ │ + skills + tool list) │ │<br>│ │ 3. Load conversation history from memory │ │<br>│ │ 4. Assemble: [system, …history, user message] │ │<br>│ └────────────────────┬────────────────────────────────┘ │<br>│ │ │<br>│ ▼ │<br>│ ┌────────────────┐ │<br>│ │ LLM Call │ │<br>│ └───────┬────────┘ │<br>│ │ │<br>│ Tool calls? │<br>│ ┌───────┴────────┐ │<br>│ YES NO │<br>│ │ │ │<br>│ ▼ ▼ │<br>│ ┌────────────┐ ┌────────────────┐ │<br>│ │ Execute │ │ Store in memory│ │<br>│ │ each tool │ │ Return answer │ │<br>│ └─────┬──────┘ └────────────────┘ │<br>│ │ │<br>│ └──► back to LLM Call (loop) │<br>│ │<br>└──────────────────────────────────────────────────────────────┘<br>```</p><p>This loop is what makes the agent autonomous — it keeps calling tools until it has everything it needs to produce a final answer.</p><p>— -</p><p>## How to Put It All Together</p><p>Here’s the complete SupportBot:</p><p>```js<br>// SupportBot.bx<br>import bxModules.bxai.models.middleware.core.LoggingMiddleware;<br>import bxModules.bxai.models.middleware.core.GuardrailMiddleware;<br>import bxModules.bxai.models.middleware.core.MaxToolCallsMiddleware;</p><p>class {</p><p>property name=”agent”;</p><p>/**<br> * Wire up the agent with tools, memory, and middleware.<br> *<br> * <a href="http://twitter.com/orderService">@orderService</a> Your order data service<br> * <a href="http://twitter.com/kbVectorMemory">@kbVectorMemory</a> Vector memory backed by your knowledge base (optional)<br> */<br> function init( required any orderService, any kbVectorMemory ) {<br> // 1. Register tools by scanning the OrderTools class<br> aiToolRegistry().scan( new OrderTools( arguments.orderService ), “support” )</p><p>// 2. Build the agent<br> variables.agent = aiAgent(<br> name : “SupportBot”,<br> description : “Customer support specialist for Acme Store.”,<br> instructions: “<br> You are a friendly and efficient customer support agent.<br> Always call get_order before discussing a specific order.<br> Confirm refunds explicitly before calling issue_refund.<br> Lead with the direct answer, then add supporting detail.<br> If you cannot resolve an issue, offer to escalate.<br> “,<br> tools : [ “get_order@support”, “search_orders@support”, “issue_refund@support”, “now@bxai” ],<br> memory : aiMemory( “cache” ),<br> middleware : [<br> new LoggingMiddleware( logToConsole: true, prefix: “[SupportBot]” ),<br> new GuardrailMiddleware( blockedTools: [ “delete_order” ] ),<br> new MaxToolCallsMiddleware( maxCalls: 8 )<br> ]<br> )</p><p>// 3. Optionally seed with a knowledge base for RAG<br> if ( !isNull( arguments.kbVectorMemory ) ) {<br> variables.agent.addMemory( arguments.kbVectorMemory )<br> }</p><p>return this<br> }</p><p>/**<br> * Handle a customer message — returns the full response string.<br> */<br> string function handle(<br> required string message,<br> required string userId,<br> required string conversationId<br> ) {<br> return variables.agent.run(<br> arguments.message,<br> {},<br> {<br> userId : arguments.userId,<br> conversationId: arguments.conversationId<br> }<br> )<br> }</p><p>}<br>```</p><p>### What the Middleware Does</p><p>```<br>┌────────────────────────────────────────────────────────────────┐<br>│ Middleware Stack │<br>│ │<br>│ Every agent.run() call passes through: │<br>│ │<br>│ ┌──────────────────────────────────────────────────────────┐ │<br>│ │ LoggingMiddleware — logs every LLM call + tool call │ │<br>│ │ GuardrailMiddleware — blocks forbidden tools (delete_*) │ │<br>│ │ MaxToolCallsMiddleware — stops runaway loops at 8 calls │ │<br>│ └──────────────────────────────────────────────────────────┘ │<br>│ │ │ │ │<br>│ ▼ ▼ ▼ │<br>│ ai.log reject call cancel run │<br>│ with error gracefully │<br>└────────────────────────────────────────────────────────────────┘<br>```</p><p>**`LoggingMiddleware`** logs every agent run, LLM call, and tool invocation to BoxLang’s `ai` log file. In development you’ll see exactly what the agent is doing. In production, disable `logToConsole` and write to the log for observability.</p><p>**`GuardrailMiddleware`** blocks `delete_order` permanently — even if the LLM somehow decides to call it. Defense-in-depth for high-stakes operations.</p><p>**`MaxToolCallsMiddleware`** prevents runaway agents. If the agent gets stuck in a tool-calling loop, it hits the cap and stops with a clear error rather than burning tokens indefinitely.</p><p>— -</p><p>## Streaming Responses</p><p>For web UIs and real-time applications, you want the agent’s response to appear token-by-token as it’s generated — like typing. This is what makes AI feel alive rather than frozen.</p><p>BoxLang AI supports streaming at every level: direct model calls, agent runs, and web responses.</p><p>### How Streaming Works</p><p>```<br>┌──────────────────────────────────────────────────────────────┐<br>│ Streaming vs Blocking │<br>│ │<br>│ BLOCKING (default) │<br>│ ────────────────── │<br>│ User sends message │<br>│ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ (waiting 2–8 seconds) │<br>│ Full response arrives at once │<br>│ │<br>│ STREAMING │<br>│ ───────── │<br>│ User sends message │<br>│ “Your” ► “ order” ► “ #ORD” ► “-78291” ► “ is” ► … │<br>│ Response appears immediately, token by token │<br>└──────────────────────────────────────────────────────────────┘<br>```</p><p>### Simple Streaming with `aiChatStream()`</p><p>For basic streaming without an agent:</p><p>```js<br>// Stream a response token by token<br>aiChatStream(<br> messages : “Explain how BoxLang AI handles tool calling”,<br> callback : chunk =&gt; {<br> // Each chunk contains a delta with partial content<br> var token = chunk.choices?.first()?.delta?.content ?: “”<br> if ( token.len() ) {<br> writeOutput( token )<br> bx:flush; // push each token to the browser immediately<br> }<br> },<br> params : { model: “gpt-4o” }<br>)<br>```</p><p>### Agent Streaming with `agent.stream()`</p><p>The `stream()` method on `AiAgent` works exactly like `run()` but delivers the response token by token. Tool calls still execute synchronously under the hood — the streaming applies to the final text response:</p><p>```js<br>// SupportBot.bx — add this alongside the handle() method<br>void function handleStream(<br> required string message,<br> required string userId,<br> required string conversationId,<br> required function onChunk<br>) {<br> variables.agent.stream(<br> onChunk : arguments.onChunk,<br> input : arguments.message,<br> options : {<br> userId : arguments.userId,<br> conversationId: arguments.conversationId<br> }<br> )<br>}<br>```</p><p>### Streaming to a Web Browser (BoxLang Web)</p><p>Here’s how to wire streaming to a real HTTP response — tokens pushed to the browser as they arrive:</p><p>```js<br>// handlers/SupportStreamHandler.bx<br>class {</p><p>property name=”supportBot” inject=”SupportBot”;</p><p>function stream( event, rc, prc ) {<br> var userId = auth.getCurrentUser().getEmail()<br> var conversationId = rc.ticketId<br> <br> // Use BoxLang’s Native SSE Streamer<br> SSE(<br> callback : ( emitter ) =&gt; {<br> supportBot.handleStream(<br> message : rc.message,<br> userId : userId,<br> conversationId : conversationId,<br> onChunk : chunk =&gt; {<br> if ( emitter.isClosed() ) {<br> return<br> }<br> var token = chunk.choices?.first()?.delta?.content ?: “”<br> if ( token.len() ) {<br> emitter.send( token, “token” )<br> }<br> }<br> )<br> emitter.send( { complete: true }, “done” )<br> emitter.close()<br> },<br> keepAliveInterval : 30000,<br> cors : “”<br> )<br> }</p><p>}<br>```</p><p>### Consuming the Stream on the Frontend</p><p>On the client side, use the standard `EventSource` API or `fetch` with a readable stream:</p><p>```javascript<br>// JavaScript — connect to the SSE stream<br>const eventSource = new EventSource(<br> `/support/stream?ticketId=${ticketId}&amp;message=${encodeURIComponent(message)}`<br>);</p><p>const responseEl = document.getElementById( “agent-response” );</p><p>eventSource.onmessage = ( event ) =&gt; {<br> if ( event.data === “[DONE]” ) {<br> eventSource.close();<br> return;<br> }<br> // Append each token as it arrives<br> responseEl.textContent += event.data;<br>};</p><p>eventSource.onerror = () =&gt; eventSource.close();<br>```</p><p>### Streaming with Accumulated Memory</p><p>One important detail: even in streaming mode, the full response is stored in memory after the stream completes. The `AiAgent.stream()` method accumulates tokens internally and saves them when done:</p><p>```js<br>// From AiAgent.bx — the wrapped callback pattern<br>var accumulated = “”<br>var wrappedCallback = ( chunk ) =&gt; {<br> var content = chunk.choices?.first()?.delta?.content ?: “”<br> accumulated &amp;= content // accumulate for memory<br> userOnChunk( chunk ) // forward to your callback<br>}</p><p>// After streaming completes, store the full response<br>storeInMemory( userMessage, { role: “assistant”, content: accumulated }, userId, conversationId )<br>```</p><p>This means streaming and memory work seamlessly together — the user sees tokens as they arrive, and the next turn has the full conversation history.</p><p>### When to Use Streaming</p><p>```<br>┌──────────────────────────────────────────────────────────────┐<br>│ Streaming Decision Guide │<br>│ │<br>│ USE streaming when: │<br>│ • Building a chat UI where responsiveness matters │<br>│ • Responses are long (&gt; 2–3 sentences) │<br>│ • You want a “typing” feel for the user │<br>│ • Delivering to a browser over HTTP │<br>│ │<br>│ USE blocking (agent.run()) when: │<br>│ • Processing in a background job or batch pipeline │<br>│ • The caller needs the complete response before proceeding │<br>│ • Building an API that returns JSON │<br>│ • Writing tests (deterministic, easier to assert) │<br>└──────────────────────────────────────────────────────────────┘<br>```</p><p>— -</p><p>## How the Agent Thinks</p><p>Let’s trace exactly what happens for a real multi-step request: *”My order #ORD-78291 arrived damaged. I want a refund.”*</p><p>```<br>┌──────────────────────────────────────────────────────────────┐<br>│ Full Agent Execution Trace │<br>│ │<br>│ USER: “My order #ORD-78291 arrived damaged. I want │<br>│ a refund.” │<br>│ │ │<br>│ ▼ │<br>│ ┌─────────────────────────────────────────────────────┐ │<br>│ │ LLM CALL 1 │ │<br>│ │ “Customer wants refund. Look up order first.” │ │<br>│ │ → tool_call: get_order( “ORD-78291” ) │ │<br>│ └───────────────────┬─────────────────────────────────┘ │<br>│ │ │<br>│ ▼ ▼ │<br>│ ┌─────────────────────────────────────────────────────┐ │<br>│ │ TOOL: get_order │ │<br>│ │ { found: true, status: “Delivered”, │ │<br>│ │ total: 89.99, summary: “Order #ORD-78291…” } │ │<br>│ └───────────────────┬─────────────────────────────────┘ │<br>│ │ │<br>│ ▼ │<br>│ ┌─────────────────────────────────────────────────────┐ │<br>│ │ LLM CALL 2 │ │<br>│ │ “Order confirmed. Instructions say confirm │ │<br>│ │ before issuing refund.” │ │<br>│ │ → text: “Can you confirm the $89.99 refund?” │ │<br>│ └───────────────────┬─────────────────────────────────┘ │<br>│ │ │<br>│ USER: “Yes, please go ahead.” │<br>│ │ │<br>│ ▼ │<br>│ ┌─────────────────────────────────────────────────────┐ │<br>│ │ LLM CALL 3 │ │<br>│ │ “Customer confirmed. Issue the refund.” │ │<br>│ │ → tool_call: issue_refund( “ORD-78291”, │ │<br>│ │ “Item arrived damaged” )│ │<br>│ └───────────────────┬─────────────────────────────────┘ │<br>│ │ │<br>│ ▼ │<br>│ ┌─────────────────────────────────────────────────────┐ │<br>│ │ TOOL: issue_refund │ │<br>│ │ { success: true, refundId: “REF-44821”, │ │<br>│ │ amount: 89.99, processingDays: 5 } │ │<br>│ └───────────────────┬─────────────────────────────────┘ │<br>│ │ │<br>│ ▼ │<br>│ ┌─────────────────────────────────────────────────────┐ │<br>│ │ LLM CALL 4 │ │<br>│ │ “Refund confirmed. Compose final response.” │ │<br>│ │ → text: “Your refund of $89.99 has been │ │<br>│ │ processed (REF-44821)…” │ │<br>│ └──────────────────────────────────────────────────── ┘ │<br>│ │ │<br>│ ▼ │<br>│ ┌─────────────────────────────────────────────────────┐ │<br>│ │ STORE in memory (scoped to this user + ticket) │ │<br>│ │ RETURN to caller │ │<br>│ └─────────────────────────────────────────────────────┘ │<br>└──────────────────────────────────────────────────────────────┘<br>```</p><p>The agent confirms before acting (because the instructions say to), executes the tool only after explicit confirmation, and builds the full response from the tool result. This is the multi-step reasoning that makes agents genuinely useful.</p><p>**What the conversation history looks like at the end:**</p><p>```<br>┌────────────────────────────────────────────────────────────┐<br>│ Role │ Content │<br>├──────────────┼─────────────────────────────────────────────┤<br>│ system │ “You are SupportBot…” │<br>│ user │ “My order arrived damaged…” │<br>│ assistant │ [tool_call: get_order] │<br>│ tool │ { found:true, status:”Delivered”… } │<br>│ assistant │ “Can you confirm the $89.99 refund?” │<br>│ user │ “Yes, please go ahead.” │<br>│ assistant │ [tool_call: issue_refund] │<br>│ tool │ { success:true, refundId:”REF-44821&quot;… } │<br>│ assistant │ “Your refund of $89.99 has been issued…” │<br>└────────────────────────────────────────────────────────────┘<br>```</p><p>— -</p><p>## Going Further</p><p>The SupportBot above covers the essentials. Here’s what to add for production.</p><p>### Adding a Knowledge Base (RAG)</p><p>Ingest your documentation into vector memory and the agent retrieves relevant content automatically before answering:</p><p>```js<br>// One-time ingestion (run when docs change)<br>vectorMemory = aiMemory( “chroma”, config: {<br> collection : “support_kb”,<br> embeddingProvider: “openai”,<br> embeddingModel : “text-embedding-3-small”<br>} )</p><p>result = aiDocuments(<br> source : “/knowledge-base”,<br> config : { type: “directory”, recursive: true, extensions: [ “md”, “txt” ] }<br>).toMemory(<br> memory : vectorMemory,<br> options : { chunkSize: 800, overlap: 150 }<br>)<br>println( “Loaded #result.documentsIn# docs → #result.chunksOut# chunks” )<br>```</p><p>```<br>┌──────────────────────────────────────────────────────────────┐<br>│ RAG Pipeline │<br>│ │<br>│ INGESTION (run once) │<br>│ ───────────────────────────────────────────────────────── │<br>│ /knowledge-base/*.md │<br>│ │ │<br>│ ▼ │<br>│ aiDocuments() ──► chunk ──► embed ──► store in ChromaDB │<br>│ │<br>│ QUERY (every agent.run()) │<br>│ ───────────────────────────────────────────────────────── │<br>│ User: “What is your return policy?” │<br>│ │ │<br>│ ▼ │<br>│ Vector search: find top-5 semantically similar chunks │<br>│ │ │<br>│ ▼ │<br>│ Inject chunks into LLM context │<br>│ │ │<br>│ ▼ │<br>│ LLM answers from YOUR actual docs, not hallucinations │<br>└──────────────────────────────────────────────────────────────┘<br>```</p><p>### Human-in-the-Loop Approvals</p><p>For refunds above a threshold, require a supervisor to approve before the refund executes:</p><p>```js<br>import bxModules.bxai.models.middleware.core.HumanInTheLoopMiddleware;</p><p>agent = aiAgent(<br> name : “SupportBot”,<br> middleware : [<br> new LoggingMiddleware(),<br> new GuardrailMiddleware( blockedTools: [ “delete_order” ] ),<br> new MaxToolCallsMiddleware( maxCalls: 8 ),<br> new HumanInTheLoopMiddleware(<br> mode : “web”,<br> toolsRequiringApproval: [ “issue_refund” ]<br> )<br> ],<br> checkpointer: aiMemory( “cache” )<br>)<br>```</p><p>```<br>┌──────────────────────────────────────────────────────────────┐<br>│ Human-in-the-Loop Flow │<br>│ │<br>│ Agent reaches issue_refund tool call │<br>│ │ │<br>│ ▼ │<br>│ HumanInTheLoopMiddleware intercepts │<br>│ │ │<br>│ ▼ │<br>│ result.isSuspended() == true │<br>│ Agent saves checkpoint to cache memory │<br>│ │ │<br>│ ▼ │<br>│ Your code notifies supervisor (Slack, email, dashboard) │<br>│ │ │<br>│ ▼ │<br>│ Supervisor approves / rejects / edits args │<br>│ │ │<br>│ ├── approve ──► agent.resume( “approve”, threadId ) │<br>│ ├── reject ──► agent.resume( “reject”, threadId ) │<br>│ └── edit ──► agent.resume( “edit”, threadId, │<br>│ { correctedArgs: { amount:100 }}│<br>└──────────────────────────────────────────────────────────────┘<br>```</p><p>### Multi-Agent Escalation</p><p>For complex issues, automatically delegate to a specialist:</p><p>```js<br>billingAgent = aiAgent(<br> name : “BillingSpecialist”,<br> description : “Expert in billing disputes, chargebacks, and payment issues”,<br> tools : [ “get_payment_history@billing”, “dispute_charge@billing” ]<br>)</p><p>// SupportBot gets a delegate_to_billing-specialist tool automatically<br>supportBot = aiAgent(<br> name : “SupportBot”,<br> subAgents : [ billingAgent ]<br>)<br>```</p><p>```<br>┌──────────────────────────────────────────────────────────────┐<br>│ Multi-Agent Hierarchy │<br>│ │<br>│ ┌─────────────────┐ │<br>│ │ SupportBot │ (coordinator) │<br>│ │ (root agent) │ │<br>│ └────────┬────────┘ │<br>│ │ │<br>│ ┌──────────┴───────────┐ │<br>│ │ │ │<br>│ ┌───────┴───────┐ ┌─────────┴──────────┐ │<br>│ │ Billing │ │ Returns &amp; │ │<br>│ │ Specialist │ │ Shipping │ │<br>│ └───────────────┘ └────────────────────┘ │<br>│ │<br>│ Each sub-agent appears as a “delegate_to_*” tool. │<br>│ The LLM decides when to delegate — no routing code needed. │<br>└──────────────────────────────────────────────────────────────┘<br>```</p><p>— -</p><p>## Conclusion</p><p>Building an AI agent with BoxLang AI comes down to three concepts:</p><p>```<br>┌──────────────────────────────────────────────────────────────┐<br>│ The Three Core Concepts │<br>│ │<br>│ 1. TOOLS ── Functions your agent can call │<br>│ <a href="http://twitter.com/AITool">@AITool</a> annotation or aiTool() BIF │<br>│ Registered once, referenced by name │<br>│ │<br>│ 2. MEMORY ── Conversation history that makes it │<br>│ stateful and multi-tenant safe │<br>│ window / cache / summary / vector │<br>│ │<br>│ 3. AGENT ── The reasoning loop that ties it together │<br>│ aiAgent() with instructions + middleware │<br>│ Handles the tool-call loop automatically │<br>└──────────────────────────────────────────────────────────────┘<br>```</p><p>The framework handles the hard parts: the tool-calling loop, memory isolation, provider differences, lifecycle events, and cross-cutting concerns like logging and rate limiting. You focus on your domain logic — the tools that do the actual work.</p><p>The full SupportBot example shows how these pieces combine in a real application. The same patterns apply to any domain: financial assistants, developer tools, data analysis agents, document processors — whatever problem you’re solving, the architecture is the same.</p><p>— -</p><p>## Resources</p><p>- 📖 [BoxLang AI Documentation](<a href="https://ai.ortusbooks.com/">https://ai.ortusbooks.com</a>)<br>- 🐙 [BoxLang AI GitHub](<a href="https://github.com/ortus-boxlang/bx-ai">https://github.com/ortus-boxlang/bx-ai</a>)<br>- 🎓 [AI BootCamp](<a href="https://github.com/ortus-boxlang/bx-ai-bootcamp">https://github.com/ortus-boxlang/bx-ai-bootcamp</a>) — hands-on course covering all concepts in this guide<br>- 💬 [BoxLang Community Slack](<a href="https://boxteam.ortussolutions.com/">https://boxteam.ortussolutions.com</a>)<br>- 📦 [ForgeBox Package](<a href="https://forgebox.io/view/bx-ai">https://forgebox.io/view/bx-ai</a>)</p><p>```bash<br># Start building<br>install-bx-module bx-ai<br>boxlang my-agent.bxs<br>```</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fd0bb19e71e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>