<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Maham Codes - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Maham Codes - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 22:24:00 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/MahamCodes/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Create Serverless AI Agents with Langbase Docs MCP Server in Minutes ]]>
                </title>
                <description>
                    <![CDATA[ Building serverless AI agents has recently become a lot simpler. With the Langbase Docs MCP server, you can instantly connect AI models to Langbase documentation – making it easy to build composable, agentic AI systems with memory without complex inf... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-create-serverless-ai-agents-with-langbase-docs-mcp-server-in-minutes/</link>
                <guid isPermaLink="false">681a2ce0aebfc718f4e6da03</guid>
                
                    <category>
                        <![CDATA[ mcp ]]>
                    </category>
                
                    <category>
                        <![CDATA[ AI ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ai agents ]]>
                    </category>
                
                    <category>
                        <![CDATA[ LLM&#39;s  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Maham Codes ]]>
                </dc:creator>
                <pubDate>Tue, 06 May 2025 15:38:08 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1746545857204/6df2b802-a7dc-4745-ac64-117c1c0f7ee1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Building serverless AI agents has recently become a lot simpler. With the Langbase Docs MCP server, you can instantly connect AI models to Langbase documentation – making it easy to build composable, agentic AI systems with memory without complex infrastructure.</p>
<p>In this guide, you’ll learn how to set up the Langbase Docs MCP server inside Cursor (an AI code editor), and build a summary AI agent that uses Langbase docs as live, on-demand context.</p>
<h3 id="heading-heres-what-well-cover">Here’s what we’ll cover:</h3>
<ul>
<li><p><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-model-context-protocol-mcp">What is Model Context Protocol (MCP)?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-anthropics-role-in-launching-mcp">Anthropic’s role in launching MCP</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-cursor-ai-code-editor">Cursor AI code editor</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-langbase-and-why-is-its-docs-mcp-server-useful">What is Langbase and why is its Docs MCP server useful?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-set-up-the-langbase-docs-mcp-server-in-cursor">How to set up the Langbase Docs MCP server in Cursor</a>?</p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-langbase-docs-mcp-server-in-cursor-ai">How to use Langbase Docs MCP server in Cursor AI</a>?</p>
</li>
<li><p><a class="post-section-overview" href="#heading-use-case-build-a-summary-ai-agent-with-langbase-docs-mcp-server">Use case: Build a summary AI Agent with Langbase Docs MCP server</a></p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before we begin creating the agent, you’ll need to have some things setup and some tools ready to go.</p>
<p>In this tutorial, I’ll be using the following tech stack:</p>
<ul>
<li><p><a target="_blank" href="http://langbase.com">Langbase</a> – the platform to build and deploy your serverless AI agents.</p>
</li>
<li><p><a target="_blank" href="https://langbase.com/docs/sdk">Langbase SDK</a> – a TypeScript AI SDK, designed to work with JavaScript, TypeScript, Node.js, Next.js, React, and the like.</p>
</li>
<li><p><a target="_blank" href="http://cursor.com">Cursor</a> – An AI code editor just like VS Code.</p>
</li>
</ul>
<p>You’ll also need to:</p>
<ul>
<li><a target="_blank" href="https://langbase.com/signup">Sign up</a> on Langbase to get access to the API key.</li>
</ul>
<h2 id="heading-what-is-model-context-protocol-mcp"><strong>What is Model Context Protocol (MCP)?</strong></h2>
<p><a target="_blank" href="https://modelcontextprotocol.io/introduction"><strong>Model Context Protocol (MCP)</strong></a> is an open protocol that standardizes how applications provide external context to large language models (LLMs). With MCP, developers can connect AI models to various tools and data sources like documentation, APIs, and databases – in a clean, consistent way.</p>
<p>Instead of relying solely on prompts, MCP allows LLMs to call custom tools (like documentation fetchers or API explorers) during a conversation.</p>
<h3 id="heading-mcp-general-architecture">MCP General Architecture</h3>
<p>At its core, MCP follows a client-server architecture where a host application can connect to multiple servers.</p>
<p>Here’s the general architecture of what it looks like:</p>
<p><a target="_blank" href="https://modelcontextprotocol.io/introduction"><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdjfGegMH-jHoYjgT3dRPhigOoIz8em0NyexLrfqwNEwdX7rvnbnCxfJG7nKqLk5fYcFu0_D5D8-DMb3vg0nLF4r-N8LlfH6IyFz18HjGZYlZ2J2_cq-jKq3Y6X_LPVxIz3rPs7?key=aHnkCxEY2NrPpuL4oNSIQJNY" alt="AD_4nXdjfGegMH-jHoYjgT3dRPhigOoIz8em0NyexLrfqwNEwdX7rvnbnCxfJG7nKqLk5fYcFu0_D5D8-DMb3vg0nLF4r-N8LlfH6IyFz18HjGZYlZ2J2_cq-jKq3Y6X_LPVxIz3rPs7?key=aHnkCxEY2NrPpuL4oNSIQJNY" width="1378" height="950" loading="lazy"></a></p>
<p>The Model Context Protocol architecture lets AI clients (like Claude, IDEs, and developer tools) securely connect to multiple local or remote data sources in real time. MCP clients communicate with one or more MCP servers, which act as bridges to structured data – whether from local files, databases, or remote APIs.</p>
<p>This setup allows AI models to retrieve fresh, relevant context from different sources seamlessly, without embedding data directly into the model.</p>
<h2 id="heading-anthropics-role-in-launching-mcp"><strong>Anthropic’s Role in Launching MCP</strong></h2>
<p><a target="_blank" href="https://www.anthropic.com/news/model-context-protocol">Anthropic</a> introduced MCP as part of their vision to make LLMs tool-augmented by default. MCP was originally built to expand Claude’s capabilities, but it's now available more broadly and supported in developer-friendly environments like Cursor and Claude Desktop.</p>
<p>By standardizing how tools integrate into LLM workflows, MCP makes it easier for developers to extend AI systems without custom plugins or API hacks.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1746454175998/50ed79a0-3728-4cca-92a1-0f48ded38049.png" alt="50ed79a0-3728-4cca-92a1-0f48ded38049" class="image--center mx-auto" width="3456" height="1836" loading="lazy"></p>
<h2 id="heading-cursor-ai-code-editor"><strong>Cursor AI Code Editor</strong></h2>
<p><a target="_blank" href="https://www.cursor.com/"><strong>Cursor</strong></a> is a developer-first AI code editor that integrates LLMs (like Claude, GPT, and more) directly into your IDE. Cursor supports MCP, meaning you can quickly attach custom tool servers and make them accessible as AI-augmented tools while you code.</p>
<p>Think of Cursor as VS Code meets AI agents – with built-in support for smart tools like docs fetchers and code examples retrievers.</p>
<h2 id="heading-what-is-langbase-and-why-is-its-docs-mcp-server-useful"><strong>What is Langbase and Why is its Docs MCP Server Useful?</strong></h2>
<p><strong>Langbase</strong> is a powerful serverless AI platform for building AI agents with memory. It helps developers build AI-powered apps and assistants by connecting LLMs directly to their data, APIs, and documentation.</p>
<p>The <a target="_blank" href="https://langbase.com/docs/guides/docs-mcp-server">Langbase Docs MCP Server</a> provides access to the Langbase documentation and API reference. This server allows you to use the Langbase documentation as context for your LLMs.</p>
<p>By connecting this server to Cursor (or any MCP-supported IDE), you can make Langbase documentation available to your AI agents on demand. This means less context-switching, faster workflows, and smarter assistance when building serverless agentic applications.</p>
<h2 id="heading-how-to-set-up-the-langbase-docs-mcp-server-in-cursor"><strong>How to Set Up the Langbase Docs MCP Server in Cursor</strong></h2>
<p>Let’s walk through setting up the server step-by-step.</p>
<h3 id="heading-1-open-cursor-settings"><strong>1. Open Cursor Settings</strong></h3>
<p>Launch Cursor and open Settings. From the left sidebar, select MCP.</p>
<h3 id="heading-2-add-a-new-mcp-server"><strong>2. Add a New MCP Server</strong></h3>
<p>Click the yellow + Add new global MCP server button.</p>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdpv9IyBcpFfY9iUo9xk_hfhwhXmyx7JG_4hCPy8WhYC2dMyxHyCniTB147YnQrjGjjqOyvRQsFpHq5-rPVOz637fAwhlfil9ZFhcoicgy3ggriV4_D9mAcdMMTXXCC3gfQiZE?key=aHnkCxEY2NrPpuL4oNSIQJNY" alt="Add new global MCP server" width="1600" height="247" loading="lazy"></p>
<h3 id="heading-3-configure-the-langbase-docs-mcp-server"><strong>3. Configure the Langbase Docs MCP Server</strong></h3>
<p>Paste the following configuration into the <code>mcp.json</code> file:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"mcpServers"</span>: {
        <span class="hljs-attr">"Langbase"</span>: {
        <span class="hljs-attr">"command"</span>: <span class="hljs-string">"npx"</span>,
        <span class="hljs-attr">"args"</span>: [<span class="hljs-string">"@langbase/cli"</span>,<span class="hljs-string">"docs-mcp-server"</span>]
        }
    }
}
</code></pre>
<h3 id="heading-4-start-the-langbase-docs-mcp-server"><strong>4. Start the Langbase Docs MCP Server</strong></h3>
<p>In your terminal, run:</p>
<pre><code class="lang-bash">pnpm add @langbase/cli
</code></pre>
<p>And then run this command:</p>
<pre><code class="lang-bash">pnpm dlx @langbase/cli docs-mcp-server
</code></pre>
<h3 id="heading-5-enable-the-mcp-server-in-cursor"><strong>5. Enable the MCP Server in Cursor</strong></h3>
<p>In the MCP settings, make sure the Langbase server is toggled to Enabled.</p>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXebJ0x4bjv6jDtvfrHnzHo76upu7JyUxasbsrWu0SVxg-ZyA6qir3_8tnCqAK1d1FixOkOcl0oLJN2FopMJGGNAyHLQfmJvkd4ittBaQyOIz26JHgW36PXdduyRt2qD82qrToJC?key=aHnkCxEY2NrPpuL4oNSIQJNY" alt="Langbase server toggled to &quot;Enabled&quot; in Cursor" width="1600" height="531" loading="lazy"></p>
<h2 id="heading-how-to-use-langbase-docs-mcp-server-in-cursor-ai"><strong>How to Use Langbase Docs MCP Server in Cursor AI</strong></h2>
<p>Once everything’s all set up, Cursor’s AI agent can now call Langbase docs tools like:</p>
<ul>
<li><p><code>docs_route_finder</code></p>
</li>
<li><p><code>sdk_documentation_fetcher</code></p>
</li>
<li><p><code>examples_tool</code></p>
</li>
<li><p><code>guide_tool</code></p>
</li>
<li><p><code>api_reference_tool</code></p>
</li>
</ul>
<p>For example, you can ask the Cursor agent:</p>
<pre><code class="lang-bash">“Show me the API reference <span class="hljs-keyword">for</span> Langbase Memory”
 or
 “Find a code example of creating an AI agent pipe <span class="hljs-keyword">in</span> Langbase”
</code></pre>
<p>The AI will use the Docs MCP server to fetch precise documentation snippets – directly inside Cursor.</p>
<h2 id="heading-use-case-build-a-summary-ai-agent-with-langbase-docs-mcp-server"><strong>Use Case: Build a Summary AI Agent with Langbase Docs MCP Server</strong></h2>
<p>Let’s build a summary agent that summarizes context using the Langbase SDK, powered by the Langbase Docs MCP server inside the Cursor AI code editor.</p>
<ol>
<li><p>Open an empty folder in Cursor and launch the chat panel (<code>Cmd+Shift+I</code> on Mac or <code>Ctrl+Shift+I</code> on Windows).</p>
</li>
<li><p>Switch to Agent mode from the mode selector and pick your preferred LLM (we’ll use Claude 3.5 Sonnet for this demo).</p>
</li>
<li><p>In the chat input, enter the following prompt:<br> “<em>In this directory, using Langbase SDK, create the summary pipe agent. Use TypeScript and pnpm to run the agent in the terminal.“</em></p>
</li>
<li><p>Cursor will automatically invoke MCP calls, generate the required files and code using Langbase Docs as context, and suggest changes. Accept the changes, and your summary agent will be ready. You can run the agent using the commands provided by Cursor and view the results.</p>
</li>
</ol>
<p>Here’s a demo video of creating this summary agent with a single prompt and Langbase Docs MCP server:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/Pw6Su5hpWwU" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>By combining Langbase’s Docs MCP server with Cursor AI, you’ve learned how to build serverless AI agents in minutes – all without leaving your IDE.</p>
<p>If you’re building AI agents, tools, or apps with Langbase, this is one of the fastest ways to simplify your development process.</p>
<p>Happy building! 🚀</p>
<p>Connect with me by 🙌:</p>
<ul>
<li><p>Subscribing to my <a target="_blank" href="https://www.youtube.com/@AIwithMahamCodes">YouTube</a> Channel. If you are willing to learn about AI and agents.</p>
</li>
<li><p>Subscribing to my free newsletter <a target="_blank" href="https://mahamcodes.substack.com/">“The Agentic Engineer”</a> where I share all the latest AI and agents news/trends/jobs and much more.</p>
</li>
<li><p>Follow me on <a target="_blank" href="https://x.com/MahamDev">X (Twitter)</a>.</p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build Autonomous Agents using Prompt Chaining with AI Primitives (No Frameworks) ]]>
                </title>
                <description>
                    <![CDATA[ Autonomous agents might sound complex, but they don’t have to be. These are AI systems that can make decisions and take actions on their own to achieve a goal – usually by using LLMs, various tools, and memory to reason through a task. You can build ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/build-autonomous-agents-using-prompt-chaining-with-ai-primitives/</link>
                <guid isPermaLink="false">680662c3d6b81962a8fc5351</guid>
                
                    <category>
                        <![CDATA[ llm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ai-agent ]]>
                    </category>
                
                    <category>
                        <![CDATA[ AI ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Maham Codes ]]>
                </dc:creator>
                <pubDate>Mon, 21 Apr 2025 15:22:42 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1745248868960/12efd5ab-3d9b-4c93-979f-45bde796639b.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Autonomous agents might sound complex, but they don’t have to be. These are AI systems that can make decisions and take actions on their own to achieve a goal – usually by using LLMs, various tools, and memory to reason through a task.</p>
<p>You can build powerful agentic systems without heavyweight frameworks or orchestration engines. One of the simplest and most effective ways to do that is to use Langbase agentic architectures (built with AI primitives that don't require a framework to ship scalable AI agentic systems).</p>
<p>In this article, we’ll dive into one of Langbase's agentic architectures: prompt chaining. We’ll look at why it’s useful and how to implement it by building a prompt chaining agent.</p>
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ol>
<li><p><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-ai-primitives-agentic-architecture">AI primitives (agentic architecture)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-prompt-chaining">What is prompt chaining?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-prompt-chaining-architecture">Prompt chaining architecture</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-langbase-sdk">Langbase SDK</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-building-a-prompt-chaining-agent-using-httpslangbasecomlangbase-pipes">Building a prompt chaining agent using Langbase Pipes</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-step-1-setup-your-project">Step 1: Setup your project</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-2-get-langbase-api-key">Step 2: Get Langbase API Key</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-3-add-llm-api-keys">Step 3: Add LLM API keys</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-4-add-logic-in-prompt-chainingts-file">Step 4: Add logic in prompt-chaining.ts file</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-5-run-the-file">Step 5: Run the file</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-the-result">The result</a></p>
</li>
</ol>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before we begin creating a prompt chaining agent, you’ll need to have the following setup and tools ready to go.</p>
<p>In this tutorial, I’ll be using the following tech stack:</p>
<ul>
<li><p><a target="_blank" href="http://langbase.com/">Langbase</a> – the platform to build and deploy your serverless AI agents.</p>
</li>
<li><p><a target="_blank" href="https://langbase.com/docs/sdk">Langbase SDK</a> – a TypeScript AI SDK, designed to work with JavaScript, TypeScript, Node.js, Next.js, React, and the like.</p>
</li>
<li><p><a target="_blank" href="https://openai.com/">OpenAI</a> – to get the LLM key for the preferred model.</p>
</li>
</ul>
<p>You’ll also need to:</p>
<ul>
<li><p>Sign up on Langbase to get access to the API key.</p>
</li>
<li><p>Sign up on OpenAI to generate the LLM key for the model you want to use (for this demo, I’ll be using the <code>openai:gpt-4o-mini</code> model). You can generate the key <a target="_blank" href="https://platform.openai.com/api-keys">here</a>.</p>
</li>
</ul>
<h2 id="heading-ai-primitives-agentic-architecture">AI Primitives (Agentic Architecture)</h2>
<p>An AI primitive level approach means building AI systems using the most basic building blocks – without relying on heavy abstractions, orchestration engines, or full-blown frameworks.</p>
<p>Langbase Pipe and Memory agents serve as these building blocks.</p>
<p><a target="_blank" href="https://langbase.com/docs/pipe">Pipe agents</a> on Langbase are different from other agents. They are serverless AI agents with agentic tools that can work with any language or framework. Pipe agents are easily deployable, and with just one API they let you connect 250+ LLMs to any data to build any developer API workflow.</p>
<p><a target="_blank" href="https://langbase.com/docs/memory">Langbase memory agents</a> (long-term memory solution) are designed to acquire, process, retain, and retrieve information seamlessly. They dynamically attach private data to any LLM, enabling context-aware responses in real time and reducing hallucinations. Memory, when connected to a pipe agent, becomes a memory agent.</p>
<p>With these building blocks (AI primitives) you can build entire agentic workflows. For this, Langbase agentic architectures serves as a boilerplate in building, deploying, and scaling autonomous agents.</p>
<p>Let’s look at one of the agentic architectures: prompt chaining.</p>
<h2 id="heading-what-is-prompt-chaining">What is Prompt Chaining?</h2>
<p>Prompt chaining is an agent architecture where a task is broken down into a sequence of prompts. Each step passes its output to the next, enabling the LLM to handle more complex workflows with higher accuracy.</p>
<p>This is particularly useful for structured tasks like:</p>
<ul>
<li><p>Document summarization and analysis</p>
</li>
<li><p>Multi-step content generation</p>
</li>
<li><p>Data transformation and cleanup</p>
</li>
<li><p>Content validation and refinement</p>
</li>
</ul>
<p>Rather than relying on a single prompt to do everything, you split the work into focused steps. This makes it easier to debug, improves output quality, and introduces natural "checkpoints" in your AI workflow.</p>
<h2 id="heading-prompt-chaining-architecture">Prompt Chaining Architecture</h2>
<p>Here’s a reference architecture explaining the workflow:</p>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXchmBDXvU8DXnQu7EjqKoSUTdxQ__KsTZemZ9yaTGpeCAMUc1RX_Swby9NOtxXwONFdKGPrjFcjVZhQmQoKe1eu2nceFWGLaPA8bpu-JYB7rh4ChJmExLRRWJzjB4686HjUsP_t?key=l4b_IFG3ufUXGX7WLcs4Dknq" alt="AD_4nXchmBDXvU8DXnQu7EjqKoSUTdxQ__KsTZemZ9yaTGpeCAMUc1RX_Swby9NOtxXwONFdKGPrjFcjVZhQmQoKe1eu2nceFWGLaPA8bpu-JYB7rh4ChJmExLRRWJzjB4686HjUsP_t?key=l4b_IFG3ufUXGX7WLcs4Dknq" width="1592" height="602" loading="lazy"></p>
<p>This diagram is a visual reference for how prompt chaining can be used to build a lightweight agentic system using just LLM calls and conditional logic – without any heavyweight frameworks.</p>
<p>Here’s a breakdown of what’s happening in the flow:</p>
<ol>
<li><strong>In → LLM Call</strong></li>
</ol>
<ul>
<li><p>Takes the initial input and runs the first LLM call.</p>
</li>
<li><p>Produces Output 1.</p>
</li>
</ul>
<ol start="2">
<li><strong>Gate</strong></li>
</ol>
<ul>
<li><p>Evaluates Output 1 to decide the next step.</p>
</li>
<li><p>Acts as a conditional checkpoint (for example, success/failure, intent validation, confidence threshold).</p>
</li>
</ul>
<ol start="3">
<li><strong>If Gate passes:</strong></li>
</ol>
<ul>
<li><p>Proceeds to LLM Call 2 with Output 1 as input.</p>
</li>
<li><p>LLM Call 2 produces Output 2.</p>
</li>
<li><p>Output 2 goes into LLM Call 3, which generates the final result.</p>
</li>
<li><p>Final output flows into the Out.</p>
</li>
</ul>
<ol start="4">
<li><strong>If Gate fails:</strong></li>
</ol>
<ul>
<li><p>The flow terminates early at Exit.</p>
</li>
<li><p>Skips further LLM calls, saving compute and avoiding invalid outputs.</p>
</li>
</ul>
<h2 id="heading-langbase-sdk">Langbase SDK</h2>
<p>The Langbase SDK makes it easy to build powerful AI agents using TypeScript. It gives you everything you need to work with any LLM, connect your own embedding models, manage document memory, and build AI agents that can reason and respond.</p>
<p>The SDK <a target="_blank" href="http://langbase.com">i</a>s designed to work with Node.js, Next.js, React, or any modern JavaScript stack. You can use it to upload documents, create semantic memory, and run AI workflows (called Pipes agents) with just a few lines of code.</p>
<p>Langbase is an API-first AI platform, and its TypeScript SDK smooths out the experience – making it easy to get started without dealing with infrastructure. Just drop in your API key, write your logic, and you're good to go.</p>
<p>Now that you know about Langbase SDK, let’s start building the prompt chaining agent.</p>
<h2 id="heading-building-a-prompt-chaining-agent-using-langbase-pipes">Building a Prompt Chaining Agent using Langbase Pipes</h2>
<p>Let’s walk through a real prompt chaining agentic system built using Langbase Pipe agents (serverless AI agents with unified APIs for every LLM). For this, we’ll be setting up a basic Node.js project.</p>
<p>We’ll be implementing a sequential product marketing content pipeline that transforms a raw product description into polished marketing copy through three stages (that is, the creation of three Pipe agents):</p>
<h3 id="heading-first-stage-summary-agent">First Stage (Summary Agent):</h3>
<ul>
<li><p>Takes a raw product description</p>
</li>
<li><p>Condenses it into two concise sentences</p>
</li>
<li><p>Has a quality gate that checks if the summary is detailed enough (at least 10 words)</p>
</li>
</ul>
<h3 id="heading-second-stage-features-agent">Second Stage (Features Agent):</h3>
<ul>
<li><p>Takes the summary from stage 1</p>
</li>
<li><p>Extracts and formats key product features as bullet points</p>
</li>
</ul>
<h3 id="heading-final-stage-marketing-copy-agent">Final Stage (Marketing Copy Agent):</h3>
<ul>
<li><p>Takes the bullet points from stage 2</p>
</li>
<li><p>Generates refined marketing copy for the product</p>
</li>
</ul>
<p>All stages will be using the OpenAI 4o-mini model through the Langbase SDK. The best part is that you can use different LLM models for each stage/Pipe agent creation as well.</p>
<p>What makes this interesting is its pipeline approach. Each stage builds upon the output of the previous stage, with a quality check after the summary stage to ensure the pipeline maintains high standards.</p>
<p>Let’s begin with the creation of this prompt chaining agentic system.</p>
<h3 id="heading-step-1-setup-your-project">Step 1: Setup Your Project</h3>
<p>I’ll be building a basic Node.js app in TypeScript that uses the Langbase SDK to create a scalable prompt chaining agentic system. It will work without any framework, following an AI primitive level approach.</p>
<p>To get started with that, create a new directory for your project and navigate to it:</p>
<pre><code class="lang-bash">mkdir agentic-architecture &amp;&amp; <span class="hljs-built_in">cd</span> agentic-architecture
</code></pre>
<p>Then initialize a Node.js project and create a TypeScript file by running this command in your terminal:</p>
<pre><code class="lang-bash">npm init -y &amp;&amp; touch prompt-chaining.ts
</code></pre>
<p>The <code>prompt-chaining.ts</code> file will contain code of all the agent creations in it.</p>
<p>After this, we will be using the Langbase SDK to create the agents and <code>dotenv</code> to manage environment variables. So, let's install these dependencies.</p>
<pre><code class="lang-bash">npm i langbase dotenv
</code></pre>
<h3 id="heading-step-2-get-langbase-api-key">Step 2: Get Langbase API Key</h3>
<p>Every request you send to Langbase needs an API key. You can generate API keys from the <a target="_blank" href="https://studio.langbase.com/">Langbase studio</a> by following these steps:</p>
<ol>
<li><p>Switch to your user or org account.</p>
</li>
<li><p>From the sidebar, click on the <code>Settings</code> menu.</p>
</li>
<li><p>In the developer settings section, click on the <code>Langbase API keys</code> link.</p>
</li>
<li><p>From here you can create a new API key or manage existing ones.</p>
</li>
</ol>
<p>For more details, you can visit the Langbase API keys documentation.</p>
<p>After generating the API key, create an <code>.env</code> file in the root of your project and add your Langbase API key in it:</p>
<pre><code class="lang-bash">LANGBASE_API_KEY=xxxxxxxxx
</code></pre>
<p>Replace xxxxxxxxx with your Langbase API key.</p>
<h3 id="heading-step-3-add-llm-api-keys">Step 3: Add LLM API keys</h3>
<p>Once you have the Langbase API key, you’ll be needing the LLM key as well to run the RAG agent. If you have set up LLM API keys in your profile, the AI memory and agent pipe will automatically use them. Otherwise navigate to the LLM API keys page and add keys for different providers like OpenAI, Anthropic, and so on.</p>
<p>Follow these steps to add the LLM keys:</p>
<ol>
<li><p>Add LLM API keys in your account using Langbase studio</p>
</li>
<li><p>Switch to your user or org account.</p>
</li>
<li><p>From the sidebar, click on the <code>Settings</code> menu.</p>
</li>
<li><p>In the developer settings section, click on the <code>LLM API keys</code> link.</p>
</li>
<li><p>From here you can add LLM API keys for different providers like OpenAI, TogetherAI, Anthropic, and so on.</p>
</li>
</ol>
<h3 id="heading-step-4-add-logic-in-prompt-chainingts-file">Step 4: Add logic in <code>prompt-chaining.ts</code> file</h3>
<p>In the <code>prompt-chaining.ts</code> file you created in Step 1, add the following code:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> dotenv <span class="hljs-keyword">from</span> <span class="hljs-string">'dotenv'</span>;
<span class="hljs-keyword">import</span> { Langbase } <span class="hljs-keyword">from</span> <span class="hljs-string">'langbase'</span>;


dotenv.config();


<span class="hljs-keyword">const</span> langbase = <span class="hljs-keyword">new</span> Langbase({
   apiKey: process.env.LANGBASE_API_KEY!
});


<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params">inputText: <span class="hljs-built_in">string</span></span>) </span>{
   <span class="hljs-comment">// Prompt chaining steps</span>
   <span class="hljs-keyword">const</span> steps = [
       {
           name: <span class="hljs-string">`summary-agent-<span class="hljs-subst">${<span class="hljs-built_in">Date</span>.now()}</span>`</span>,
           model: <span class="hljs-string">'openai:gpt-4o-mini'</span>,
           description:
               <span class="hljs-string">'summarize the product description into two concise sentences'</span>,
           prompt: <span class="hljs-string">`Please summarize the following product description into two concise
           sentences:\n`</span>
       },
       {
           name: <span class="hljs-string">`features-agent-<span class="hljs-subst">${<span class="hljs-built_in">Date</span>.now()}</span>`</span>,
           model: <span class="hljs-string">'openai:gpt-4o-mini'</span>,
           description: <span class="hljs-string">'extract key product features as bullet points'</span>,
           prompt: <span class="hljs-string">`Based on the following summary, list the key product features as
           bullet points:\n`</span>
       },
       {
           name: <span class="hljs-string">`marketing-copy-agent-<span class="hljs-subst">${<span class="hljs-built_in">Date</span>.now()}</span>`</span>,
           model: <span class="hljs-string">'openai:gpt-4o-mini'</span>,
           description:
               <span class="hljs-string">'generate a polished marketing copy using the bullet points'</span>,
           prompt: <span class="hljs-string">`Using the following bullet points of product features, generate a
           compelling and refined marketing copy for the product, be precise:\n`</span>
       }
   ];


   <span class="hljs-comment">//  Create the pipe agents</span>
   <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.all(
       steps.map(<span class="hljs-function"><span class="hljs-params">step</span> =&gt;</span>
           langbase.pipes.create({
               name: step.name,
               model: step.model,
               messages: [
                   {
                       role: <span class="hljs-string">'system'</span>,
                       content: <span class="hljs-string">`You are a helpful assistant that can <span class="hljs-subst">${step.description}</span>.`</span>
                   }
               ]
           })
       )
   );


   <span class="hljs-comment">// Initialize the data with the raw input.</span>
   <span class="hljs-keyword">let</span> data = inputText;


   <span class="hljs-keyword">try</span> {
       <span class="hljs-comment">// Process each step in the workflow sequentially.</span>
       <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> step <span class="hljs-keyword">of</span> steps) {
           <span class="hljs-comment">// Call the LLM for the current step.</span>
           <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> langbase.pipes.run({
               stream: <span class="hljs-literal">false</span>,
               name: step.name,
               messages: [{ role: <span class="hljs-string">'user'</span>, content: <span class="hljs-string">`<span class="hljs-subst">${step.prompt}</span> <span class="hljs-subst">${data}</span>`</span> }]
           });


           data = response.completion;


           <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Step: <span class="hljs-subst">${step.name}</span> \n\n Response: <span class="hljs-subst">${data}</span>`</span>);


           <span class="hljs-comment">// Gate on summary agent output to ensure it is not too brief.</span>
           <span class="hljs-comment">// If summary is less than 10 words, throw an error to stop the workflow.</span>
           <span class="hljs-keyword">if</span> (step.name === <span class="hljs-string">'summary-agent'</span> &amp;&amp; data.split(<span class="hljs-string">' '</span>).length &lt; <span class="hljs-number">10</span>) {
               <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(
                   <span class="hljs-string">'Gate triggered for summary agent. Summary is too brief. Exiting workflow.'</span>
               );
               <span class="hljs-keyword">return</span>;
           }
       }
   } <span class="hljs-keyword">catch</span> (error) {
       <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error in main workflow:'</span>, error);
   }


   <span class="hljs-comment">// The final refined marketing copy</span>
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Final Refined Product Marketing Copy:'</span>, data);
}


<span class="hljs-keyword">const</span> inputText = <span class="hljs-string">`Our new smartwatch is a versatile device featuring a high-resolution display,
long-lasting battery life,fitness tracking, and smartphone connectivity. It's designed for
everyday use and is water-resistant. With cutting-edge sensors and a sleek design, it's
perfect for tech-savvy individuals.`</span>;


main(inputText);
</code></pre>
<p>Here’s a breakdown of the above code:</p>
<p>Setup and initialization:</p>
<ul>
<li><p><code>dotenv</code> loads <code>env</code> variables from the <code>.env</code> file for secure API key access.</p>
</li>
<li><p>Langbase is imported from the SDK to interact with the API.</p>
</li>
<li><p>A Langbase client instance is created using your API key.</p>
</li>
</ul>
<p>Define the AI steps (prompt chain):</p>
<ul>
<li><p>Three AI agents (steps) are defined for a pipeline:</p>
<ol>
<li><p><strong>Summarization Agent</strong>: Summarizes the input product description into 2 sentences.</p>
</li>
<li><p><strong>Feature Extraction Agent</strong>: Extracts key features from the summary as bullet points.</p>
</li>
<li><p><strong>Marketing Copy Agent</strong>: Turns bullet points into polished marketing copy.</p>
</li>
</ol>
</li>
<li><p>Each agent uses <code>openai:gpt-4o-mini</code> as the LLM.</p>
</li>
</ul>
<p>Create Langbase Pipes (agents):</p>
<ul>
<li><p>Langbase pipes are created for each step using <code>langbase.pipes.create(...)</code>.</p>
</li>
<li><p>Each pipe has a unique name (timestamped) and a system message guiding its purpose.</p>
</li>
</ul>
<p>Run the workflow (sequential processing):</p>
<ul>
<li><p>Input text flows through each step one by one:</p>
<ul>
<li><p>The output of one step becomes the input for the next.</p>
</li>
<li><p>Pipes are run using <code>langbase.pipes.run(...)</code>.</p>
</li>
</ul>
</li>
<li><p>Intermediate outputs are logged after each step.</p>
</li>
</ul>
<p>Validation check (gatekeeping):</p>
<ul>
<li>If the summary output is too short (less than 10 words), the workflow stops with an error.</li>
</ul>
<p>Final Output:</p>
<ul>
<li>After all steps, the final result is a refined marketing copy printed to the console.</li>
</ul>
<p>For this article, we’re using a demo smartwatch product description to view the result in the <code>inputText</code> field.</p>
<h3 id="heading-step-5-run-the-file">Step 5: Run the file</h3>
<p>To run the <code>prompt-chaining.ts</code> file to view the results, you need to:</p>
<ul>
<li><p>Add TypeScript as a dependency</p>
</li>
<li><p>Add a script to run TypeScript files</p>
</li>
<li><p>Add a TypeScript configuration file</p>
</li>
</ul>
<p>For it lets first install <code>pnpm</code> by running this command in your terminal:</p>
<pre><code class="lang-bash">pnpm install
</code></pre>
<p>Then in your terminal again, run this command to add relevant dependencies and configuration files:</p>
<pre><code class="lang-bash">pnpm add -D typescript ts-node @types/node
</code></pre>
<p>After that, create a TypeScript configuration file <code>tsconfig.json</code>:</p>
<pre><code class="lang-bash">pnpm <span class="hljs-built_in">exec</span> tsc --init
</code></pre>
<p>And update the <code>package.json</code> to add the relevant script. This is what your <code>package.json</code> should look like after updating:</p>
<pre><code class="lang-json">{
 <span class="hljs-attr">"name"</span>: <span class="hljs-string">"agentic-architectures"</span>,
 <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
 <span class="hljs-attr">"main"</span>: <span class="hljs-string">"index.js"</span>,
 <span class="hljs-attr">"scripts"</span>: {
   <span class="hljs-attr">"test"</span>: <span class="hljs-string">"echo \"Error: no test specified\" &amp;&amp; exit 1"</span>,
   <span class="hljs-attr">"prompt-chaining"</span>: <span class="hljs-string">"ts-node prompt-chaining.ts"</span>
 },
 <span class="hljs-attr">"keywords"</span>: [],
 <span class="hljs-attr">"author"</span>: <span class="hljs-string">""</span>,
 <span class="hljs-attr">"license"</span>: <span class="hljs-string">"ISC"</span>,
 <span class="hljs-attr">"description"</span>: <span class="hljs-string">""</span>,
 <span class="hljs-attr">"dependencies"</span>: {
   <span class="hljs-attr">"dotenv"</span>: <span class="hljs-string">"^16.5.0"</span>,
   <span class="hljs-attr">"langbase"</span>: <span class="hljs-string">"^1.1.55"</span>
 },
 <span class="hljs-attr">"devDependencies"</span>: {
   <span class="hljs-attr">"@types/node"</span>: <span class="hljs-string">"^22.14.1"</span>,
   <span class="hljs-attr">"ts-node"</span>: <span class="hljs-string">"^10.9.2"</span>,
   <span class="hljs-attr">"typescript"</span>: <span class="hljs-string">"^5.8.3"</span>
 }
}
</code></pre>
<p>Now let’s run the project by pnpm run prompt-chaining</p>
<h2 id="heading-the-result">The Result</h2>
<p>After running the project, you’ll see the result of the example smartwatch product description in your console as follows:</p>
<pre><code class="lang-bash">Step: summarize-description
Response: This smartwatch combines fitness tracking and smartphone connectivity with a high-resolution display and long-lasting battery. Designed <span class="hljs-keyword">for</span> everyday use with a sleek, water-resistant build, it<span class="hljs-string">'s ideal for tech enthusiasts.

Step: extract-features
Response: Okay, here are the key product features extracted from the summary:

Fitness Tracking
Smartphone Connectivity
High-Resolution Display
Long-Lasting Battery
Sleek Design
Water-Resistant Build
Designed for Everyday Use
Step: refine-marketing-copy
Response: ## Elevate Your Everyday with Seamless Connectivity and Unrivaled Performance.

Experience the perfect fusion of style and functionality with our revolutionary device, designed to seamlessly integrate into your active lifestyle. Stay motivated and informed with comprehensive Fitness Tracking, while effortlessly staying connected via Smartphone Connectivity.

Immerse yourself in vibrant clarity with the stunning High-Resolution Display, and power through your day without interruption thanks to the Long-Lasting Battery. Encased in a Sleek Design, this device is as stylish as it is practical.

Built to withstand the rigors of daily life, the Water-Resistant Build ensures worry-free wear, rain or shine. Engineered for comfort and performance, this device is Designed for Everyday Use, empowering you to live your best life, effortlessly.</span>
</code></pre>
<p>This is how you can build a prompt chaining agentic system with AI primitives (no framework) using the Langbase SDK and Langbase agentic architectures.</p>
<p>Thank you for reading!</p>
<p>Connect with me by 🙌:</p>
<ul>
<li><p>Subscribing to my <a target="_blank" href="https://www.youtube.com/@AIwithMahamCodes">YouTube</a> Channel. If you are willing to learn about AI and agents.</p>
</li>
<li><p>Subscribing to my free newsletter <a target="_blank" href="https://mahamcodes.substack.com/">“The Agentic Engineer”</a> where I share all the latest AI and agents news/trends/jobs and much more.</p>
</li>
<li><p>Follow me on <a target="_blank" href="https://x.com/MahamDev">X (Twitter)</a>.</p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build RAG AI Agents with TypeScript ]]>
                </title>
                <description>
                    <![CDATA[ The most powerful AI systems don’t just generate – they also retrieve, reason, and respond with context. Retrieval-Augmented Generation (RAG) is how we get there. It combines the strengths of search and generation to build more accurate, reliable, an... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-rag-ai-agents-with-typescript/</link>
                <guid isPermaLink="false">67ffc2a75667d9e59ef9bc61</guid>
                
                    <category>
                        <![CDATA[ RAG  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ai agents ]]>
                    </category>
                
                    <category>
                        <![CDATA[ llm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Maham Codes ]]>
                </dc:creator>
                <pubDate>Wed, 16 Apr 2025 14:45:59 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1744814746615/72626297-def9-466a-8c1a-2cdb1b411300.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The most powerful AI systems don’t just generate – they also retrieve, reason, and respond with context. Retrieval-Augmented Generation (RAG) is how we get there. It combines the strengths of search and generation to build more accurate, reliable, and context-aware AI systems.</p>
<p>In this guide, you'll build a RAG-based AI agent in TypeScript using Langbase SDK. You'll plug in your own data as memory, use any embedding model, retrieve relevant context, and call an LLM to generate a precise response.</p>
<p>By the end of this tutorial, you'll have a working RAG system that:</p>
<ul>
<li><p>Stores and retrieves documents with semantic memory</p>
</li>
<li><p>Uses custom embeddings for vector search</p>
</li>
<li><p>Handles user queries with relevant context</p>
</li>
<li><p>Generates responses via OpenAI, Anthropic, or any LLM</p>
</li>
</ul>
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ul>
<li><p><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-agentic-rag">What is agentic RAG?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-langbase-sdk">Langbase SDK</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-1-setup-your-project">Step 1: Setup your project</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-2-get-langbase-api-key">Step 2: Get Langbase API Key</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-3-add-llm-api-keys">Step 3: Add LLM API keys</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-4-create-an-agentic-ai-memory">Step 4: Create an agentic AI memory</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-5-add-documents-to-ai-memory">Step 5: Add documents to AI memory</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-6-perform-rag-retrieval">Step 6: Perform RAG retrieval</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-7-create-support-pipe-agent">Step 7: Create support pipe agent</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-8-generate-rag-responses">Step 8: Generate RAG responses</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-result">The result</a></p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before we begin creating a RAG-based AI agent, you’ll need to have some tools ready to go.</p>
<p>In this tutorial, I’ll be using the following tech stack:</p>
<ul>
<li><p><a target="_blank" href="http://langbase.com/">Langbase</a> – the platform to build and deploy your serverless AI agents.</p>
</li>
<li><p><a target="_blank" href="https://langbase.com/docs/sdk">Langbase SDK</a> – a TypeScript AI SDK, designed to work with JavaScript, TypeScript, Node.js, Next.js, React, and the like.</p>
</li>
<li><p><a target="_blank" href="https://openai.com/">OpenAI</a> – to get the LLM key for the preferred model.</p>
</li>
</ul>
<p>You’ll also need to:</p>
<ul>
<li><p>Sign up on Langbase to get access to the API key.</p>
</li>
<li><p>Sign up on OpenAI to generate the LLM key for the model you want to use (for this demo, I’ll be using the <code>openai:text-embedding-3-large</code> model). You can generate the key <a target="_blank" href="https://platform.openai.com/api-keys">here</a>.</p>
</li>
</ul>
<h2 id="heading-what-is-agentic-rag">What is Agentic RAG?</h2>
<p>Retrieval augmented generation (RAG) is an architecture for optimizing the performance of an artificial intelligence (AI) model by connecting it with external knowledge bases. RAG helps large language models (LLMs) deliver more relevant responses at a higher quality.</p>
<p>When we use AI agents to facilitate RAG, it becomes <strong>Agentic RAG.</strong> Agentic RAG systems add AI agents to the RAG pipeline to increase adaptability and accuracy. Compared to traditional RAG systems, agentic RAG allows LLMs to conduct information retrieval from multiple sources and handle more complex workflows.</p>
<p>Here’s the tabular comparison of RAG vs Agentic RAG:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Feature</strong></td><td><strong>RAG</strong></td><td><strong>Agentic RAG</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Task Complexity</td><td>Simple query tasks – no complex decision-making</td><td>Handles complex, multi-step tasks using multiple tools and agents</td></tr>
<tr>
<td>Decision-Making</td><td>Limited – no autonomy</td><td>Agents decide what to retrieve, how to grade, reason, reflect, and generate</td></tr>
<tr>
<td>Multi-Step Reasoning</td><td>Single-step queries and responses only</td><td>Supports multi-step reasoning with retrieval, grading, filtering, and evaluation</td></tr>
<tr>
<td>Key Role</td><td>LLM + external data for answers</td><td>Adds intelligent agents for retrieval, generation, critique, and orchestration</td></tr>
<tr>
<td>Real-Time Data Retrieval</td><td>Not supported</td><td>Built for real-time retrieval and dynamic integration</td></tr>
<tr>
<td>Retrieval Integration</td><td>Static, pre-defined vector databases</td><td>Agents dynamically retrieve from diverse and flexible sources</td></tr>
<tr>
<td>Context Awareness</td><td>Static context – no runtime adaptability</td><td>High – agents adapt to queries, pull relevant context, and fetch live data if needed</td></tr>
</tbody>
</table>
</div><h2 id="heading-langbase-sdk">Langbase SDK</h2>
<p>The Langbase SDK makes it easy to build powerful AI tools using TypeScript. It gives you everything you need to work with any LLM, connect your own embedding models, manage document memory, and build AI agents that can reason and respond.</p>
<p>The SDK is designed to work with Node.js, Next.js, React, or any modern JavaScript stack. You can use it to upload documents, create semantic memory, and run AI workflows (called Pipe agents) with just a few lines of code.</p>
<p>Langbase is an API-first AI platform. Its TypeScript SDK smooths out the experience, making it easy to get started without dealing with infrastructure. Just drop in your API key, write your logic, and you're good to go.</p>
<p>Now that you know about Langbase SDK, let’s start building the RAG agent.</p>
<h2 id="heading-step-1-setup-your-project">Step 1: Setup Your Project</h2>
<p>We’ll be building a basic Node.js app in TypeScript that uses the Langbase SDK to create an agentic RAG system. For that, create a new directory for your project and navigate to it.</p>
<pre><code class="lang-bash">mkdir agentic-rag &amp;&amp; <span class="hljs-built_in">cd</span> agentic-rag
</code></pre>
<p>Then initialize a Node.js project and create different TypeScript files by running this command in your terminal:</p>
<pre><code class="lang-bash">npm init -y &amp;&amp; touch index.ts agents.ts create-memory.ts upload-docs.ts create-pipe.ts
</code></pre>
<p>Here’s a breakdown of what each file will do in the project:</p>
<ul>
<li><p><strong>index.ts:</strong> This is typically the entry point of a TypeScript project. It orchestrates agent creation, memory setup, and document upload.</p>
</li>
<li><p><strong>agents.ts:</strong> This file handles AI agent creation and configuration.</p>
</li>
<li><p><strong>create-memory.ts:</strong> This sets up Langbase Memory (RAG) for storing and retrieving context.</p>
</li>
<li><p><strong>upload-docs.ts:</strong> This file will upload documents to Memory so agents can access and use them.</p>
</li>
<li><p><strong>create-pipe.ts</strong>: This file sets up a <a target="_blank" href="https://langbase.com/docs/pipe/quickstart">Langbase Pipe agent</a> which is a serverless AI agent with unified APIs for every LLM.</p>
</li>
</ul>
<p>After this, we will be using the Langbase SDK to create RAG agents and <code>dotenv</code> to manage environment variables. So, let's install these dependencies.</p>
<pre><code class="lang-bash">npm i langbase dotenv
</code></pre>
<h2 id="heading-step-2-get-langbase-api-key">Step 2: Get Langbase API Key</h2>
<p>Every request you send to Langbase needs an API key. You can generate API keys from the <a target="_blank" href="https://studio.langbase.com/">Langbase studio</a> by following these steps:</p>
<ol>
<li><p>Switch to your user or org account.</p>
</li>
<li><p>From the sidebar, click on the <code>Settings</code> menu.</p>
</li>
<li><p>In the developer settings section, click on the <code>Langbase API keys</code> link.</p>
</li>
<li><p>From here you can create a new API key or manage existing ones.</p>
</li>
</ol>
<p>For more details, check out the Langbase API keys documentation.</p>
<p>After generating the API key, create an <code>.env</code> file in the root of your project and add your Langbase API key in it:</p>
<pre><code class="lang-bash">LANGBASE_API_KEY=xxxxxxxxx
</code></pre>
<p>Replace xxxxxxxxx with your Langbase API key.</p>
<h2 id="heading-step-3-add-llm-api-keys">Step 3: Add LLM API Keys</h2>
<p>Once you have the Langbase API key, you’ll need the LLM key as well to run the RAG agent. If you have set up LLM API keys in your profile, the AI memory and agent pipe will automatically use them. Otherwise, navigate to the LLM API keys page and add keys for different providers like OpenAI, Anthropic, and so on.</p>
<p>Follow these steps to add the LLM keys:</p>
<ol>
<li><p>Add LLM API keys in your account using Langbase studio</p>
</li>
<li><p>Switch to your user or org account.</p>
</li>
<li><p>From the sidebar, click on the <code>Settings</code> menu.</p>
</li>
<li><p>In the developer settings section, click on the <code>LLM API keys</code> link.</p>
</li>
<li><p>From here you can add LLM API keys for different providers like OpenAI, TogetherAI, Anthropic, and so on.</p>
</li>
</ol>
<h2 id="heading-step-4-create-an-agentic-ai-memory">Step 4: Create an Agentic AI Memory</h2>
<p>Let’s now use the Langbase SDK to create an AI memory (Langbase memory agent) where your agent can store and retrieve context.</p>
<p>Langbase serverless memory agents (long-term memory solution) are designed to acquire, process, retain, and retrieve information seamlessly. They dynamically attach private data to any LLM, enabling context-aware responses in real time and reducing hallucinations.</p>
<p>These agents combine vector storage, RAG, and internet access to create a powerful managed context search API. You can use them to build smarter, more capable AI applications.</p>
<p>In a RAG setup, memory – when connected directly to a Langbase Pipe Agent – becomes a memory agent. This pairing gives the LLM the ability to fetch relevant data and deliver precise, contextually accurate answers – addressing the limitations of LLMs when it comes to handling private data.</p>
<p>To create it, add the following code to <code>create-memory.ts</code> file you created in Step 1:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> <span class="hljs-string">'dotenv/config'</span>;
<span class="hljs-keyword">import</span> {Langbase} <span class="hljs-keyword">from</span> <span class="hljs-string">'langbase'</span>;

<span class="hljs-keyword">const</span> langbase = <span class="hljs-keyword">new</span> Langbase({
    apiKey: process.env.LANGBASE_API_KEY!,
});

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> memory = <span class="hljs-keyword">await</span> langbase.memories.create({
        name: <span class="hljs-string">'knowledge-base'</span>,
        description: <span class="hljs-string">'An AI memory for agentic memory workshop'</span>,
        embedding_model: <span class="hljs-string">'openai:text-embedding-3-large'</span>
    });

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'AI Memory:'</span>, memory);
}

main();
</code></pre>
<p>Here’s what’s happening in the above code:</p>
<ul>
<li><p>Import the <code>dotenv</code> package to load environment variables.</p>
</li>
<li><p>Import the <code>Langbase</code> class from the langbase package.</p>
</li>
<li><p>Create a new instance of the Langbase class with your API key.</p>
</li>
<li><p>Use the <code>memories.create</code> method to create a new AI memory.</p>
</li>
<li><p>Set the name and description of the memory.</p>
</li>
<li><p>Use the <code>openai:text-embedding-3-large</code> model for embedding.</p>
</li>
<li><p>Log the created memory to the console.</p>
</li>
</ul>
<p>After this, let's create the agentic memory by running the <code>create-memory.ts</code> file.</p>
<pre><code class="lang-bash">npx tsx create-memory.ts
</code></pre>
<p>This will create an AI memory and log the memory details to the console.</p>
<h2 id="heading-step-5-add-documents-to-ai-memory">Step 5: Add Documents to AI Memory</h2>
<p>Now that you’ve created an AI memory agent, the next step is to add documents in it. These documents will serve as the context your agent can reference during interactions.</p>
<p>First, create a docs directory in your project root, and add two sample text files:</p>
<ul>
<li><p><a target="_blank" href="https://langbase.com/docs/examples/agent-architectures">agent-architectures.txt</a></p>
</li>
<li><p><a target="_blank" href="http://langbase.com/docs">langbase-faq.txt</a></p>
</li>
</ul>
<p>Next, open the <code>upload-docs.ts</code> file created in Step 1 and paste in the following code:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> <span class="hljs-string">'dotenv/config'</span>;
<span class="hljs-keyword">import</span> { Langbase } <span class="hljs-keyword">from</span> <span class="hljs-string">'langbase'</span>;
<span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'fs/promises'</span>;
<span class="hljs-keyword">import</span> path <span class="hljs-keyword">from</span> <span class="hljs-string">'path'</span>;

<span class="hljs-keyword">const</span> langbase = <span class="hljs-keyword">new</span> Langbase({
    apiKey: process.env.LANGBASE_API_KEY!,
});

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> cwd = process.cwd();
    <span class="hljs-keyword">const</span> memoryName = <span class="hljs-string">'knowledge-base'</span>;

    <span class="hljs-comment">// Upload agent architecture document</span>
    <span class="hljs-keyword">const</span> agentArchitecture = <span class="hljs-keyword">await</span> readFile(path.join(cwd, <span class="hljs-string">'docs'</span>, <span class="hljs-string">'agent-architectures.txt'</span>));
    <span class="hljs-keyword">const</span> agentResult = <span class="hljs-keyword">await</span> langbase.memories.documents.upload({
        memoryName,
        contentType: <span class="hljs-string">'text/plain'</span>,
        documentName: <span class="hljs-string">'agent-architectures.txt'</span>,
        <span class="hljs-built_in">document</span>: agentArchitecture,
        meta: { category: <span class="hljs-string">'Examples'</span>, topic: <span class="hljs-string">'Agent architecture'</span> },
    });

    <span class="hljs-built_in">console</span>.log(agentResult.ok ? <span class="hljs-string">'✓ Agent doc uploaded'</span> : <span class="hljs-string">'✗ Agent doc failed'</span>);

    <span class="hljs-comment">// Upload FAQ document</span>
    <span class="hljs-keyword">const</span> langbaseFaq = <span class="hljs-keyword">await</span> readFile(path.join(cwd, <span class="hljs-string">'docs'</span>, <span class="hljs-string">'langbase-faq.txt'</span>));
    <span class="hljs-keyword">const</span> faqResult = <span class="hljs-keyword">await</span> langbase.memories.documents.upload({
        memoryName,
        contentType: <span class="hljs-string">'text/plain'</span>,
        documentName: <span class="hljs-string">'langbase-faq.txt'</span>,
        <span class="hljs-built_in">document</span>: langbaseFaq,
        meta: { category: <span class="hljs-string">'Support'</span>, topic: <span class="hljs-string">'Langbase FAQs'</span> },
    });

    <span class="hljs-built_in">console</span>.log(faqResult.ok ? <span class="hljs-string">'✓ FAQ doc uploaded'</span> : <span class="hljs-string">'✗ FAQ doc failed'</span>);
}

main();
</code></pre>
<p>Let’s break down what’s happening in this code:</p>
<ul>
<li><p><code>dotenv/config</code> is used to load environment variables from your .env file.</p>
</li>
<li><p>Langbase is imported from the SDK to interact with the API.</p>
</li>
<li><p><code>readFile</code> from the <code>fs/promises</code> module reads each document file asynchronously.</p>
</li>
<li><p><code>path.join()</code> ensures file paths work across different operating systems.</p>
</li>
<li><p>A Langbase client instance is created using your API key.</p>
</li>
<li><p><code>memories.documents.upload</code> is used to upload each <code>.txt</code> file to the AI memory.</p>
</li>
<li><p>Each upload includes metadata like <code>category</code> and <code>topic</code> to help organize the content.</p>
</li>
<li><p>Upload success or failure is logged to the console.</p>
</li>
</ul>
<p>This step ensures your AI agent will have actual content to pull from – FAQs, architecture docs, or anything else you upload into memory.</p>
<p>Then, run the <code>upload-docs.ts</code> file to upload the documents to the AI memory by this command in your terminal. This will upload the documents to the AI memory:</p>
<pre><code class="lang-bash">npx tsx upload-docs.ts
</code></pre>
<h2 id="heading-step-6-perform-rag-retrieval">Step 6: Perform RAG Retrieval</h2>
<p>In this step, we’ll perform RAG against a query using the documents we uploaded to AI memory.</p>
<p>Add the following code to your <code>agents.ts</code> file created in Step 1:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> <span class="hljs-string">'dotenv/config'</span>;
<span class="hljs-keyword">import</span> { Langbase } <span class="hljs-keyword">from</span> <span class="hljs-string">'langbase'</span>;

<span class="hljs-keyword">const</span> langbase = <span class="hljs-keyword">new</span> Langbase({
    apiKey: process.env.LANGBASE_API_KEY!,
});

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">runMemoryAgent</span>(<span class="hljs-params">query: <span class="hljs-built_in">string</span></span>) </span>{
    <span class="hljs-keyword">const</span> chunks = <span class="hljs-keyword">await</span> langbase.memories.retrieve({
        query,
        topK: <span class="hljs-number">4</span>,
        memory: [
            {
                name: <span class="hljs-string">'knowledge-base'</span>,
            },
        ],
    });

    <span class="hljs-keyword">return</span> chunks;
}
</code></pre>
<p>Let’s break down what this does:</p>
<ul>
<li><p>Import the <code>Langbase</code> class from the Langbase SDK.</p>
</li>
<li><p>Initialize the Langbase client using your API key from environment variables.</p>
</li>
<li><p>Define an async function <code>runMemoryAgent</code> that takes a query string as input.</p>
</li>
<li><p>Use <code>memories.retrieve</code> to query the memory for the most relevant chunks, retrieving the top 4 results (<code>topK: 4</code>) from the memory named "knowledge-base".</p>
</li>
<li><p>Return the retrieved memory chunks.</p>
</li>
</ul>
<p>Now let's add the following code to the <code>index.ts</code> file created in Step 1 to run the memory agent:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { runMemoryAgent } <span class="hljs-keyword">from</span> <span class="hljs-string">'./agents'</span>;

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> chunks = <span class="hljs-keyword">await</span> runMemoryAgent(<span class="hljs-string">'What is agent parallelization?'</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Memory chunk:'</span>, chunks);
}

main();
</code></pre>
<p>This code runs a Langbase memory query for “What is agent parallelization?” It uses <code>runMemoryAgent</code> to retrieve the top matching chunks from your AI memory and logs the results. It’s how you fetch relevant knowledge with RAG.</p>
<p>After this, run the <code>index.ts</code> file to perform RAG retrieval against the query by this command in terminal:</p>
<pre><code class="lang-bash">npx tsx index.ts
</code></pre>
<p>You will see the memory agent output as retrieved memory chunks in the console as follows:</p>
<pre><code class="lang-bash">[
  {
    text: <span class="hljs-string">'---\n'</span> +
      <span class="hljs-string">'\n'</span> +
      <span class="hljs-string">'## Agent Parallelization\n'</span> +
      <span class="hljs-string">'\n'</span> +
      <span class="hljs-string">'Parallelization runs multiple LLM tasks at the same time to improve speed or accuracy. It works by splitting a task into independent parts (sectioning) or generating multiple responses for comparison (voting).\n'</span> +
      <span class="hljs-string">'\n'</span> +
      <span class="hljs-string">'Voting is a parallelization method where multiple LLM calls generate different responses for the same task. The best result is selected based on agreement, predefined rules, or quality evaluation, improving accuracy and reliability.\n'</span> +
      <span class="hljs-string">'\n'</span> +
      <span class="hljs-string">"`This code implements an email analysis system that processes incoming emails through multiple parallel AI agents to determine if and how they should be handled. Here's the breakdown:"</span>,
    similarity: 0.7146744132041931,
    meta: {
      docName: <span class="hljs-string">'agent-architectures.txt'</span>,
      documentName: <span class="hljs-string">'agent-architectures.txt'</span>,
      category: <span class="hljs-string">'Examples'</span>,
      topic: <span class="hljs-string">'Agent architecture'</span>
    }
  },
  {
    text: <span class="hljs-string">'async function main(inputText: string) {\n'</span> +
      <span class="hljs-string">'\ttry {\n'</span> +
      <span class="hljs-string">'\t\t// Create pipes first\n'</span> +
      <span class="hljs-string">'\t\tawait createPipes();\n'</span> +
      <span class="hljs-string">'\n'</span> +
      <span class="hljs-string">'\t\t// Step A: Determine which agent to route to\n'</span> +
      <span class="hljs-string">'\t\tconst route = await routerAgent(inputText);\n'</span> +
      <span class="hljs-string">"\t\tconsole.log('Router decision:', route);\n"</span> +
      <span class="hljs-string">'\n'</span> +
      <span class="hljs-string">'\t\t// Step B: Call the appropriate agent\n'</span> +
      <span class="hljs-string">'\t\tconst agent = agentConfigs[route.agent];\n'</span> +
      <span class="hljs-string">'\n'</span> +
      <span class="hljs-string">'\t\tconst response = await langbase.pipes.run({\n'</span> +
      <span class="hljs-string">'\t\t\tstream: false,\n'</span> +
      <span class="hljs-string">'\t\t\tname: agent.name,\n'</span> +
      <span class="hljs-string">'\t\t\tmessages: [\n'</span> +
      <span class="hljs-string">"\t\t\t\t{ role: 'user', content: `<span class="hljs-variable">${agent.prompt}</span> <span class="hljs-variable">${inputText}</span>` }\n"</span> +
      <span class="hljs-string">'\t\t\t]\n'</span> +
      <span class="hljs-string">'\t\t});\n'</span> +
      <span class="hljs-string">'\n'</span> +
      <span class="hljs-string">'\t\t// Final output\n'</span> +
      <span class="hljs-string">'\t\tconsole.log(\n'</span> +
      <span class="hljs-string">'\t\t\t`Agent: ${agent.name} \\n\\n Response: ${response.completion}`\n'</span> +
      <span class="hljs-string">'\t\t);\n'</span> +
      <span class="hljs-string">'\t} catch (error) {\n'</span> +
      <span class="hljs-string">"\t\tconsole.error('Error in main workflow:', error);\n"</span> +
      <span class="hljs-string">'\t}\n'</span> +
      <span class="hljs-string">'}\n'</span> +
      <span class="hljs-string">'\n'</span> +
      <span class="hljs-string">'// Example usage:\n'</span> +
      <span class="hljs-string">"const inputText = 'Why days are shorter in winter?';\n"</span> +
      <span class="hljs-string">'\n'</span> +
      <span class="hljs-string">'main(inputText);\n'</span> +
      <span class="hljs-string">'```\n'</span> +
      <span class="hljs-string">'\n'</span> +
      <span class="hljs-string">'\n'</span> +
      <span class="hljs-string">'---\n'</span> +
      <span class="hljs-string">'\n'</span> +
      <span class="hljs-string">'## Agent Parallelization\n'</span> +
      <span class="hljs-string">'\n'</span> +
      <span class="hljs-string">'Parallelization runs multiple LLM tasks at the same time to improve speed or accuracy. It works by splitting a task into independent parts (sectioning) or generating multiple responses for comparison (voting).'</span>,
    similarity: 0.5911030173301697,
    meta: {
      docName: <span class="hljs-string">'agent-architectures.txt'</span>,
      documentName: <span class="hljs-string">'agent-architectures.txt'</span>,
      category: <span class="hljs-string">'Examples'</span>,
      topic: <span class="hljs-string">'Agent architecture'</span>
    }
  },
  {
    text: <span class="hljs-string">"`This code implements a sophisticated task orchestration system with dynamic subtask generation and parallel processing. Here's how it works:\n"</span> +
      <span class="hljs-string">'\n'</span> +
      <span class="hljs-string">'1. Orchestrator Agent (Planning Phase):\n'</span> +
      <span class="hljs-string">'   - Takes a complex task as input\n'</span> +
      <span class="hljs-string">'   - Analyzes the task and breaks it down into smaller, manageable subtasks\n'</span> +
      <span class="hljs-string">'   - Returns both an analysis and a list of subtasks in JSON format\n'</span> +
      <span class="hljs-string">'\n'</span> +
      <span class="hljs-string">'2. Worker Agents (Execution Phase):\n'</span> +
      <span class="hljs-string">'   - Multiple workers run in parallel using Promise.all()\n'</span> +
      <span class="hljs-string">'   - Each worker gets:\n'</span> +
      <span class="hljs-string">'     - The original task for context\n'</span> +
      <span class="hljs-string">'     - Their specific subtask to complete\n'</span> +
      <span class="hljs-string">'   - All workers use Gemini 2.0 Flash model\n'</span> +
      <span class="hljs-string">'\n'</span> +
      <span class="hljs-string">'3. Synthesizer Agent (Integration Phase):\n'</span> +
      <span class="hljs-string">'   - Takes all the worker outputs\n'</span> +
      <span class="hljs-string">'   - Combines them into a cohesive final result\n'</span> +
      <span class="hljs-string">'   - Ensures the pieces flow together naturally'</span>,
    similarity: 0.5393730401992798,
    meta: {
      docName: <span class="hljs-string">'agent-architectures.txt'</span>,
      documentName: <span class="hljs-string">'agent-architectures.txt'</span>,
      category: <span class="hljs-string">'Examples'</span>,
      topic: <span class="hljs-string">'Agent architecture'</span>
    }
  },
  {
    text: <span class="hljs-string">"`This code implements an email analysis system that processes incoming emails through multiple parallel AI agents to determine if and how they should be handled. Here's the breakdown:\n"</span> +
      <span class="hljs-string">'\n'</span> +
      <span class="hljs-string">'1. Three Specialized Agents running in parallel:\n'</span> +
      <span class="hljs-string">'   - Sentiment Analysis Agent: Determines if the email tone is positive, negative, or neutral\n'</span> +
      <span class="hljs-string">'   - Summary Agent: Creates a concise summary of the email content\n'</span> +
      <span class="hljs-string">'   - Decision Maker Agent: Takes the outputs from the other agents and decides:\n'</span> +
      <span class="hljs-string">'     - If the email needs a response\n'</span> +
      <span class="hljs-string">"     - Whether it's spam\n"</span> +
      <span class="hljs-string">'     - Priority level (low, medium, high, urgent)\n'</span> +
      <span class="hljs-string">'\n'</span> +
      <span class="hljs-string">'2. The workflow:\n'</span> +
      <span class="hljs-string">'   - Takes an email input\n'</span> +
      <span class="hljs-string">'   - Runs sentiment analysis and summary generation in parallel using Promise.all()\n'</span> +
      <span class="hljs-string">'   - Feeds those results to the decision maker agent\n'</span> +
      <span class="hljs-string">'   - Outputs a final decision object with response requirements\n'</span> +
      <span class="hljs-string">'\n'</span> +
      <span class="hljs-string">'3. All agents use Gemini 2.0 Flash model and are structured to return parsed JSON responses'</span>,
    similarity: 0.49115753173828125,
    meta: {
      docName: <span class="hljs-string">'agent-architectures.txt'</span>,
      documentName: <span class="hljs-string">'agent-architectures.txt'</span>,
      category: <span class="hljs-string">'Examples'</span>,
      topic: <span class="hljs-string">'Agent architecture'</span>
    }
  }
]
</code></pre>
<h2 id="heading-step-7-create-support-pipe-agent">Step 7: Create Support Pipe Agent</h2>
<p>In this step, we will create a support agent using the Langbase SDK. Go ahead and add the following code to the <code>create-pipe.ts</code> file created in Step 1:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> <span class="hljs-string">'dotenv/config'</span>;
<span class="hljs-keyword">import</span> { Langbase } <span class="hljs-keyword">from</span> <span class="hljs-string">'langbase'</span>;

<span class="hljs-keyword">const</span> langbase = <span class="hljs-keyword">new</span> Langbase({
    apiKey: process.env.LANGBASE_API_KEY!,
});

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> supportAgent = <span class="hljs-keyword">await</span> langbase.pipes.create({
        name: <span class="hljs-string">`ai-support-agent`</span>,
        description: <span class="hljs-string">`An AI agent to support users with their queries.`</span>,
        messages: [
            {
                role: <span class="hljs-string">`system`</span>,
                content: <span class="hljs-string">`You're a helpful AI assistant.
                You will assist users with their queries.
                Always ensure that you provide accurate and to the point information.`</span>,
            },
        ],
    });

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Support agent:'</span>, supportAgent);
}

main();
</code></pre>
<p>Let's go through the above code:</p>
<ul>
<li><p>Initialize the Langbase SDK with your API key.</p>
</li>
<li><p>Use the <code>pipes.create</code> method to create a new pipe agent.</p>
</li>
<li><p>Log the created pipe agent to the console.</p>
</li>
</ul>
<p>Now run the <code>create-pipe.ts</code> file to create the pipe agent by this command in your terminal:</p>
<pre><code class="lang-bash">npx tsx create-pipe.ts
</code></pre>
<p>This will create a support agent and log the agent details to the console.</p>
<h2 id="heading-step-8-generate-rag-responses">Step 8: Generate RAG Responses</h2>
<p>Up until now, we’ve created a Langbase memory agent, added documents in it, performed RAG retrieval against a query, and created a support agent using Langbase Pipe agent. The only thing left in creating this complete RAG agent is generating comprehensive responses using LLMs.</p>
<p>To do this, add the following code to the <code>agents.ts</code> file created in Step 1:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> <span class="hljs-string">'dotenv/config'</span>;
<span class="hljs-keyword">import</span> { Langbase, MemoryRetrieveResponse } <span class="hljs-keyword">from</span> <span class="hljs-string">'langbase'</span>;

<span class="hljs-keyword">const</span> langbase = <span class="hljs-keyword">new</span> Langbase({
    apiKey: process.env.LANGBASE_API_KEY!,
});

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">runAiSupportAgent</span>(<span class="hljs-params">{
    chunks,
    query,
}: {
    chunks: MemoryRetrieveResponse[];
    query: <span class="hljs-built_in">string</span>;
}</span>) </span>{
    <span class="hljs-keyword">const</span> systemPrompt = <span class="hljs-keyword">await</span> getSystemPrompt(chunks);

    <span class="hljs-keyword">const</span> { completion } = <span class="hljs-keyword">await</span> langbase.pipes.run({
        stream: <span class="hljs-literal">false</span>,
        name: <span class="hljs-string">'ai-support-agent'</span>,
        messages: [
            {
                role: <span class="hljs-string">'system'</span>,
                content: systemPrompt,
            },
            {
                role: <span class="hljs-string">'user'</span>,
                content: query,
            },
        ],
    });

    <span class="hljs-keyword">return</span> completion;
}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getSystemPrompt</span>(<span class="hljs-params">chunks: MemoryRetrieveResponse[]</span>) </span>{
    <span class="hljs-keyword">let</span> chunksText = <span class="hljs-string">''</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> chunks) {
        chunksText += chunk.text + <span class="hljs-string">'\n'</span>;
    }

    <span class="hljs-keyword">const</span> systemPrompt = <span class="hljs-string">`
    You're a helpful AI assistant.
    You will assist users with their queries.

    Always ensure that you provide accurate and to the point information.
    Below is some CONTEXT for you to answer the questions. ONLY answer from the CONTEXT. CONTEXT consists of multiple information chunks. Each chunk has a source mentioned at the end.

For each piece of response you provide, cite the source in brackets like so: [1].

At the end of the answer, always list each source with its corresponding number and provide the document name. like so [1] Filename.doc. If there is a URL, make it hyperlink on the name.

 If you don't know the answer, say so. Ask for more context if needed.
    <span class="hljs-subst">${chunksText}</span>`</span>;

    <span class="hljs-keyword">return</span> systemPrompt;
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">runMemoryAgent</span>(<span class="hljs-params">query: <span class="hljs-built_in">string</span></span>) </span>{
    <span class="hljs-keyword">const</span> chunks = <span class="hljs-keyword">await</span> langbase.memories.retrieve({
        query,
        topK: <span class="hljs-number">4</span>,
        memory: [
            {
                name: <span class="hljs-string">'knowledge-base'</span>,
            },
        ],
    });

    <span class="hljs-keyword">return</span> chunks;
}
</code></pre>
<p>The above code:</p>
<ul>
<li><p>Creates a function <code>runAiSupportAgent</code> that takes chunks and query as input.</p>
</li>
<li><p>Uses the <code>pipes.run</code> method to generate responses using the LLM.</p>
</li>
<li><p>Creates a function <code>getSystemPrompt</code> to generate a system prompt for the LLM.</p>
</li>
<li><p>Combines the retrieved chunks to create a system prompt.</p>
</li>
<li><p>Returns the generated completion.</p>
</li>
</ul>
<p>Now, let's run the support agent with AI memory chunks. Add the following code to the <code>index.ts</code> file:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { runMemoryAgent, runAiSupportAgent } <span class="hljs-keyword">from</span> <span class="hljs-string">'./agents'</span>;

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> query = <span class="hljs-string">'What is agent parallelization?'</span>;
    <span class="hljs-keyword">const</span> chunks = <span class="hljs-keyword">await</span> runMemoryAgent(query);

    <span class="hljs-keyword">const</span> completion = <span class="hljs-keyword">await</span> runAiSupportAgent({
        chunks,
        query,
    });

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Completion:'</span>, completion);
}

main();
</code></pre>
<p>This code runs two agents: one to retrieve memory chunks relevant to a query (<code>runMemoryAgent</code>), and another (<code>runAiSupportAgent</code>) to generate a final answer using those chunks.</p>
<p>Then, run the <code>index.ts</code> file to generate responses using the LLM.</p>
<pre><code class="lang-bash">npx tsx index.ts
</code></pre>
<h3 id="heading-the-result">The Result</h3>
<p>After running the support agent, you’ll see the following output generated in your console:</p>
<pre><code class="lang-bash">Completion: Agent parallelization is a process that runs multiple LLM (Language Model) tasks simultaneously to enhance speed or accuracy. This technique can be implemented <span class="hljs-keyword">in</span> two main ways:

1. **Sectioning**: A task is divided into independent parts that can be processed concurrently.
2. **Voting**: Multiple LLM calls generate different responses <span class="hljs-keyword">for</span> the same task, and the best result is selected based on agreement, predefined rules, or quality evaluation. This approach improves accuracy and reliability by comparing various outputs.

In practice, agent parallelization involves orchestrating multiple specialized agents to handle different aspects of a task, allowing <span class="hljs-keyword">for</span> efficient processing and improved outcomes.

If you need more detailed examples or further clarification, feel free to ask!
</code></pre>
<p>This is how you can build an agentic RAG system with TypeScript using the Langbase SDK.</p>
<p>Thank you for reading!</p>
<p>Connect with me by 🙌:</p>
<ul>
<li><p>Subscribing to my <a target="_blank" href="https://www.youtube.com/@AIwithMahamCodes">YouTube</a> Channel if you want to learn about AI and agents.</p>
</li>
<li><p>Subscribing to my free newsletter <a target="_blank" href="https://mahamcodes.substack.com/">The Agentic Engineer</a> where I share all the latest AI and agents news/trends/jobs and much more.</p>
</li>
<li><p>Follow me on <a target="_blank" href="https://x.com/MahamDev">X (Twitter)</a>.</p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Write Effective Prompts for AI Agents using Langbase ]]>
                </title>
                <description>
                    <![CDATA[ Prompt engineering isn’t just a skill these days – it gives you an important competitive edge in your development. In 2025, the difference between AI agents that work and those that don’t comes down to how well they’re prompted. Whether you’re a deve... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-write-effective-prompts-for-ai-agents-using-langbase/</link>
                <guid isPermaLink="false">67dae1dae49263fce2ef7dc3</guid>
                
                    <category>
                        <![CDATA[ llm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ AI ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ai agents ]]>
                    </category>
                
                    <category>
                        <![CDATA[ #PromptEngineering ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Maham Codes ]]>
                </dc:creator>
                <pubDate>Wed, 19 Mar 2025 15:25:14 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1742397395773/51f66f8f-56a4-418e-a59e-141de64be2b2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Prompt engineering isn’t just a skill these days – it gives you an important competitive edge in your development.</p>
<p>In 2025, the difference between AI agents that work and those that don’t comes down to how well they’re prompted. Whether you’re a developer, product manager, or just building with AI, getting really good at prompt engineering will make you significantly more effective.</p>
<p>Langbase lets you craft high-performance prompts and deploy serverless AI agents optimized for the latest models. In this article, we’ll break down tips and tricks to help you design effective prompts. We’ll also look at some advanced prompt engineering techniques for building serverless agents, and how to fine-tune LLM parameters to get the best results.</p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<p>To get the most out of this article, you’ll need:</p>
<ul>
<li><p>A Langbase account – <a target="_blank" href="http://langbase.com/signup">Sign up</a> if you haven’t already.</p>
</li>
<li><p>Basic knowledge of <a target="_blank" href="https://www.freecodecamp.org/news/how-to-start-building-projects-with-llms/">LLMs</a>, <a target="_blank" href="https://www.freecodecamp.org/news/how-ai-agents-can-supercharge-language-models-handbook/">AI agents</a>, and <a target="_blank" href="https://www.freecodecamp.org/news/learn-rag-fundamentals-and-advanced-techniques/">RAG (retrieval-augmented generation)</a>.</p>
</li>
</ul>
<h3 id="heading-heres-what-ill-cover"><strong>Here’s what I’ll cover:</strong></h3>
<ul>
<li><p><a class="post-section-overview" href="#heading-prompt-engineering-fundamentals">Prompt engineering fundamentals</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-tips-and-tricks-for-effective-prompt-design">Tips and tricks for effective prompt design</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-langbase-pipe-agent-prompts">Langbase pipe agent prompts</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-prompt-engineer-your-ai-agent">How to prompt engineer your AI agent</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-fine-tune-llm-models-response-parameters">Fine-tune LLM model’s response parameters</a></p>
</li>
</ul>
<p>Let’s get started!</p>
<h2 id="heading-prompt-engineering-fundamentals">Prompt Engineering Fundamentals</h2>
<p>A prompt tells the AI what to do—it sets the context, guides the response, and shapes the conversation. Prompt engineering is about designing prompts that make AI agents actually useful in real-world applications.</p>
<p>Here’s how to write good prompts:</p>
<h3 id="heading-1-define-your-goal-clearly">1. Define your goal clearly</h3>
<p>Before crafting a prompt, be clear about what you want to achieve—just like planning logic before writing code. Consider whether dynamic inputs are needed and how they’ll be handled. Define the ideal output format, whether JSON, XML, or plain text. Determine if the model requires additional context or if its training data is enough.</p>
<p>Set any constraints on response length, structure, or tone. Fine-tune LLM parameters if necessary to improve control. The more precise your goals, the better the results. And remember, effective prompt engineering is often a team effort.</p>
<p>Here’s an example prompt to help you out. If you're building a customer support bot, your goal should look like this:</p>
<p><em>"Generate concise, polite responses in plain text, pulling details from the company knowledge base."</em></p>
<ul>
<li><p>Define the output format (JSON, XML, plain text).</p>
<ul>
<li><em>Example: "Respond in JSON format with 'answer' and 'source' fields."</em></li>
</ul>
</li>
<li><p>Decide if extra context is needed.</p>
<ul>
<li><em>Example: "Use this document as reference: [URL]."</em></li>
</ul>
</li>
<li><p>Set constraints on length, tone, or structure.</p>
<ul>
<li><em>Example: "Limit response to 50 words, use a friendly tone."</em></li>
</ul>
</li>
</ul>
<h3 id="heading-2-experiment-relentlessly">2. Experiment relentlessly</h3>
<p>LLMs aren’t perfect, and neither is prompt engineering. Test everything. Try different formats, tweak parameters, and provide examples. AI models vary in capability—refining prompts through iteration is the only way to ensure reliable outputs.</p>
<p>Suppose your AI isn’t giving useful answers. You could:</p>
<ul>
<li><p><strong>Rephrase the prompt</strong>: Instead of <em>"Explain this topic,"</em> try <em>"Summarize this in one paragraph with key takeaways."</em></p>
</li>
<li><p><strong>Add constraints</strong>: <em>"Limit response to three bullet points."</em></p>
</li>
<li><p><strong>Give examples</strong>: <em>"For example, if asked about Python, reply like this: 'Python is a versatile language used for AI, web development, and automation.'”</em></p>
</li>
</ul>
<h3 id="heading-3-treat-llms-like-machines-not-humans">3. Treat LLMs like machines, not humans</h3>
<p>LLMs don’t think. They follow instructions—precisely. Ambiguity confuses them. Over-explaining can be just as bad as under-explaining. And remember: LLMs will generate an answer, even if it’s wrong. You have to manage this risk.</p>
<p>Here’s a comparison between over and under-explaining prompts:</p>
<p><strong>Over-explaining:</strong> <em>"Can you please, if possible, provide a very detailed yet concise explanation about how neural networks work, but not too technical, and try to be engaging, but also keep it short?"</em><br><strong>Better prompt:</strong> <em>"Explain neural networks in simple terms, under 100 words, with an analogy."</em></p>
<p><strong>Under-explaining:</strong> <em>"Tell me about neural networks."</em><br><strong>Better prompt:</strong> <em>"Describe neural networks in two sentences with an example."</em></p>
<h2 id="heading-tips-and-tricks-for-effective-prompt-design">Tips and Tricks for Effective Prompt Design</h2>
<p>Here are a few tips and tricks to help you effectively prompt engineer your AI and agents:</p>
<ul>
<li><p><strong>Be specific</strong> – Vague prompts lead to bad outputs. Define the format, tone, and level of detail you want. If needed, break complex tasks into smaller steps and chain your prompts.</p>
</li>
<li><p><strong>Control response length</strong> – If you need a concise response, specify the word or character limit. For example: <em>“Summarize this in 50 words.”</em></p>
</li>
<li><p><strong>Provide context</strong> – LLMs don’t know everything. If the model needs specific knowledge, include it in your prompt. For dynamic context, use a RAG-based approach to inject relevant information on demand.</p>
</li>
<li><p><strong>Use step-by-step reasoning</strong> – If a task requires logical reasoning, instruct the model explicitly: <em>“Think step by step before answering.”</em> This improves accuracy.</p>
</li>
<li><p><strong>Separate instructions from context</strong> – Long prompts can get messy. Start with clear instructions, then separate additional info.</p>
</li>
<li><p><strong>Tell it what to do, not what to avoid</strong> – Instead of saying, “Don’t explain the answer,” say, “Only output the final answer.” Positive instructions work better.</p>
</li>
<li><p><strong>Set constraints</strong> – Define limits on tone, length, or complexity. Example: <em>“Write in a professional tone, under 3 sentences.”</em></p>
</li>
<li><p><strong>Assign a role</strong> – LLMs perform better with a defined persona. Start with, “You are an expert in X,” for example, to guide the model’s behavior.</p>
</li>
<li><p><strong>Use examples</strong> – If precision matters, show the model what you expect. Techniques like few-shot and chain-of-thought (CoT) prompting help improve complex reasoning.</p>
</li>
</ul>
<h2 id="heading-langbase-pipe-agent-prompts">Langbase Pipe Agent Prompts</h2>
<p>AI agents aren’t just chatbots—they reason, plan, and take action based on user inputs. Unlike simple LLM queries, AI agents operate autonomously, making decisions and interacting with external tools to complete tasks.</p>
<p><a target="_blank" href="https://langbase.com/docs/pipe/quickstart"><strong>Langbase Pipe Agents</strong></a> are serverless AI agents with unified APIs for every LLM. They let developers define structured prompts to control agent behavior across different models. In this section, you'll learn how to structure prompts effectively by creating an AI agent Pipe to get reliable and useful responses.</p>
<h3 id="heading-the-three-key-prompts-in-langbase-pipe-agents">The three key prompts in Langbase Pipe agents</h3>
<p>To make AI agents work effectively, you need three types of prompts:</p>
<ol>
<li><p><strong>System prompt:</strong> Defines the LLM model's role, tone, and guidelines before processing user input.</p>
</li>
<li><p><strong>User prompt:</strong> The input given by the user to request a response from the model.</p>
</li>
<li><p><strong>AI assistant prompt:</strong> The model's generated response based on the user’s input.</p>
</li>
</ol>
<p>To learn how to use these three prompts with the UI using Langbase AI studio, you’ll find clear and concise instructions in this <a target="_blank" href="https://langbase.com/docs/features/prompt">guide</a>. It explains exactly where to go/what to click to write these prompts.</p>
<p>Let’s learn how to create an AI agent Pipe using the Langbase AI studio:</p>
<h3 id="heading-step-1-create-a-pipe-agent">Step 1: Create a Pipe agent</h3>
<p>After logging into your Langbase account, you can always go to <a target="_blank" href="http://pipe.new"><code>pipe.new</code></a> to create a new Pipe.</p>
<ol>
<li><p>Give your Pipe a name. Let’s call it <code>AI support agent</code>.</p>
</li>
<li><p>Click on the <code>[Create Pipe]</code> button. And just like that, you have created your first Pipe.</p>
</li>
</ol>
<p><img src="https://raw.githubusercontent.com/LangbaseInc/docs-images/refs/heads/main/guides/build-performant-rag/create-pipe-dark.jpg" alt="Creating a new Pipe" width="3456" height="1978" loading="lazy"></p>
<h3 id="heading-step-2-using-an-llm-model">Step 2: Using an LLM model</h3>
<p>If you have set up LLM API keys in your profile, the Pipe will automatically use them. If not, just hit the LLM API Keys button or head over to Settings to add Pipe-level LLM API keys.</p>
<p>Let's add an LLM provider API key now.</p>
<ol>
<li><p>Click on the LLM keys button. It will open a side panel.</p>
</li>
<li><p>Select Pipe level keys. Choose any LLM. For example, you can use <code>OpenAI</code> (for GPT) or any other 250+ <strong>supported models</strong> on Langbase.</p>
</li>
<li><p>Click on OpenAI <code>[ADD KEY]</code> button, add your LLM API key. Inside each key modal, you'll find a link <code>Get a new key from here</code> click it to create a new API key on any API provider's website.</p>
</li>
</ol>
<p><img src="https://raw.githubusercontent.com/LangbaseInc/docs-images/refs/heads/main/pipe/quickstart/updated/llm-keys-dark.jpg" alt="Add an LLM API Key" width="3456" height="1982" loading="lazy"></p>
<h3 id="heading-step-3-build-your-pipe-configure-llm-model">Step 3: Build your Pipe: Configure LLM model</h3>
<p>Let's start building our pipe. Go back to the <code>Pipe</code> tab and follow these steps:</p>
<ol>
<li><p>Click on the <code>gpt-4o-mini</code> button to select and configure the LLM model for your Pipe.</p>
</li>
<li><p>By default OpenAI <code>gpt-4o-mini</code> is selected. You can also pick any LLM model.</p>
</li>
<li><p>Choose one of the pre-configured <strong>presets</strong> for your model.</p>
</li>
<li><p>You can also modify any of the model params. Learn more with the icon, next to param name.</p>
</li>
</ol>
<p><img src="https://raw.githubusercontent.com/LangbaseInc/docs-images/refs/heads/main/pipe/quickstart/updated/model-dark.jpg" alt="Build your pipe: Configuiring the LLM model" width="3456" height="1982" loading="lazy"></p>
<h3 id="heading-step-4-build-your-pipe-configure-the-pipes-meta">Step 4: Build your Pipe: Configure the Pipe's Meta</h3>
<p>Use the Meta section to configure how your <code>AI support agent</code> Pipe should work. There are multiple ways you can configure it.</p>
<p>To start, you can set the output format of the Pipe to JSON. You can also turn on moderation mode to filter out inappropriate content as a requirement by OpenAI.</p>
<p>Then you can turn the streaming mode on and off, and turn off storing messages (input prompt and generated completion) for sensitive data like emails.</p>
<p><img src="https://raw.githubusercontent.com/LangbaseInc/docs-images/refs/heads/main/pipe/quickstart/updated/meta-dark.jpg" alt="Build your pipe: Configuiring the Pipe meta settings" width="3456" height="1982" loading="lazy"></p>
<h3 id="heading-step-5-design-a-prompt">Step 5: Design a Prompt</h3>
<p>Now that you have your LLM model and Pipe meta configured, it's time to design your prompt.</p>
<p><strong>Prompt: System Instructions</strong></p>
<p>Let's add a system instruction message to this agent. You can add this: <code>You're a helpful AI assistant. You will assist users with their queries about {{company}}. Always ensure that you provide accurate and to the point information.</code></p>
<p><img src="https://raw.githubusercontent.com/LangbaseInc/docs-images/refs/heads/main/pipe/quickstart/updated/system-prompt-dark.jpg" alt="Prompt design: System Instructions" width="3456" height="1982" loading="lazy"></p>
<p><strong>Prompt: User Message</strong></p>
<p>Now let's add a user message. Click on the <code>USER</code> button to add a new message. You can add this: <code>How to request payment API?</code>.</p>
<p><img src="https://raw.githubusercontent.com/LangbaseInc/docs-images/refs/heads/main/pipe/quickstart/updated/user-prompt-dark.jpg" alt="Prompt design: Adding a user message" width="3456" height="1982" loading="lazy"></p>
<p><strong>Prompt: Variables</strong></p>
<p>Any text written between double curly brackets <code>{{}}</code> becomes a variable. A variables section will display all your variable keys and values.</p>
<p>Since you added a variable <code>{{company}}</code>, you can see it appear in variables. Now you’re assessing the company variable value as <code>ACME</code>. This pipe will now replace <code>{{company}}</code> with its value in all messages.</p>
<p>✨ Variables allow you to use the same pipe with different data.</p>
<p><img src="https://raw.githubusercontent.com/LangbaseInc/docs-images/refs/heads/main/pipe/quickstart/updated/variables-dark.jpg" alt="Prompt design: Adding Variables" width="3456" height="1984" loading="lazy"></p>
<p><strong>Prompt as Code</strong></p>
<p>We're not writing code here, but if you were to write this prompt as code, it would look like this:</p>
<ol>
<li><p>Prompt is a <code>messages</code> array. Inside it are <code>message</code> objects.</p>
</li>
<li><p>Each <code>message</code> object typically consists of two properties:</p>
<ol>
<li><p><code>role</code> either "system", "user", or "assistant".</p>
</li>
<li><p><code>content</code> that you're sending or expecting to be generated from the AI LLM.</p>
</li>
</ol>
</li>
</ol>
<pre><code class="lang-bash">// Prompt example:
{
    messages: [
        { role: <span class="hljs-string">'system'</span>, content: <span class="hljs-string">'You are a helpful assistant.'</span> },
        { role: <span class="hljs-string">'user'</span>, content: <span class="hljs-string">'How to request payment API?'</span> },
        { role: <span class="hljs-string">'assistant'</span>, content: <span class="hljs-string">'Sure, here you go … …'</span> }
    ];
}
</code></pre>
<p>If you’re using the <strong>Langbase SDK</strong> to build serverless AI Pipe agents to define these three prompts, you need to send the prompt content in the <code>messages</code> object array as follows:</p>
<pre><code class="lang-bash">interface Message {
    role: <span class="hljs-string">'user'</span> | <span class="hljs-string">'assistant'</span> | <span class="hljs-string">'system'</span>| <span class="hljs-string">'tool'</span>;
    content: string | null;
    name?: string;
    tool_call_id?: string;
    tool_calls?: ToolCall[];
}
</code></pre>
<p>You can learn more about creating a pipe agent using the Langbase SDK <a target="_blank" href="https://langbase.com/docs/sdk/pipe/create">here.</a></p>
<p>Now that you know about creating a Pipe agent and its prompts, let's discuss a few effective techniques to prompt engineer your AI Pipe agents that’ll prove useful for a vast majority of LLMs.</p>
<h2 id="heading-how-to-prompt-engineer-your-ai-agent">How to Prompt Engineer Your AI Agent</h2>
<h3 id="heading-1-few-shot-training">1. Few-shot training</h3>
<p>Few-shot prompting improves an AI agent's ability to generate accurate responses by providing it with a few examples before asking it to perform a task. Instead of relying purely on pre-trained knowledge, the model learns from sample interactions, helping it generalize patterns and reduce errors.</p>
<p>For instance, in a customer support AI, showing examples of refund requests and troubleshooting responses allows the model to infer how to handle similar queries effectively.</p>
<pre><code class="lang-bash">You are a customer support AI. Use the examples below to understand how to respond.

Example 1:
Customer: <span class="hljs-string">"I want a refund for my order."</span>
AI: <span class="hljs-string">"Our refund policy allows returns within 30 days. Please provide your order number, and I'll assist you further."</span>

Example 2:
Customer: <span class="hljs-string">"My product isn't working. What should I do?"</span>
AI: <span class="hljs-string">"I'm sorry to hear that! Can you describe the issue? Meanwhile, you can check our troubleshooting guide [link]."</span>

Now, respond to the following query:
Customer: <span class="hljs-string">"I received the wrong item. What should I do?"</span>
</code></pre>
<h3 id="heading-2-memory-augmented-prompting-rag-based">2. Memory-augmented prompting (RAG-based)</h3>
<p>Memory-Augmented Prompting (RAG-Based) enhances AI responses by retrieving relevant external data instead of relying solely on pre-trained knowledge. This approach is particularly useful when dealing with dynamic or domain-specific information.</p>
<p>Using Langbase, you can create memory agents for this. Langbase memory agents are a managed context search API for developers. They’re a helpful long-term memory solution that can acquire, process, retain, and later retrieve information. Memory agents combine vector storage, RAG (Retrieval-Augmented Generation), and internet access to help you build powerful AI features and products.</p>
<p>By incorporating Langbase with a Retrieval Augmented Generation (RAG) system, Memory is used with a Pipe agent to retrieve relevant data for queries.</p>
<p>The process involves:</p>
<ul>
<li><p>Creating query embeddings.</p>
</li>
<li><p>Retrieving matching data from Memory.</p>
</li>
<li><p>Augmenting the query with this data of 3-20 chunks.</p>
</li>
<li><p>Using it to generate accurate, context-aware responses.</p>
</li>
</ul>
<h3 id="heading-rag-prompt">RAG prompt</h3>
<p>When a memory is attached to a Pipe agent, by default a RAG prompt appears which is fed to LLM to utilize the memory. Default prompt works fine in most cases, but you can customize the prompt based on your use case.</p>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcxZ-2ydsO9AoNFxGGLnLXalLgm6s4mr6TvJPGclnCGf9vIC1FM-nibFRUQLUfKLZMLq-HSUWF-gOkWY9JO5kdiVsCgW8ZCxS_Z5sL7bWVSVlKTq77qt8Q5d4rlqpooPlR4ARyAjQ?key=Q-k-bEK6x7APjPtDCPcYSPKJ" alt="RAG prompt" width="1600" height="908" loading="lazy"></p>
<p>You can learn how to build RAG by following this step-by-step <a target="_blank" href="https://langbase.com/docs/guides/rag">guide.</a></p>
<h3 id="heading-3-chain-of-thought-cot-prompting">3. Chain of Thought (CoT) prompting</h3>
<p>CoT prompting helps AI agents break down complex problems into logical steps before answering. Instead of jumping to conclusions, the model is guided to reason through the problem systematically.</p>
<p>This prompting technique is great when you need the "how" behind the answer. It is especially useful for tasks requiring multi-step reasoning, such as debugging code.</p>
<p>For example, a coding AI agent can analyze an issue with the following prompt:</p>
<pre><code class="lang-bash">Analyze the following error message and identify possible causes. Then, <span class="hljs-built_in">break</span> down the debugging steps to fix the issue.
</code></pre>
<p>This approach leads to more accurate and reliable responses by encouraging deeper reasoning rather than generating a hasty answer.</p>
<h3 id="heading-4-role-based-prompting">4. Role-based prompting</h3>
<p>Role-based prompting helps AI agents generate more precise and context-aware responses by assigning them a specific identity. Instead of providing generic answers, the model adopts the characteristics of a domain expert, leading to better accuracy and relevance.</p>
<p>For example, in a cybersecurity AI agent, defining its role as a security expert ensures its responses prioritize risk assessment and best practices. A sample prompt could be:</p>
<pre><code class="lang-bash">You are a cybersecurity expert. Identify vulnerabilities <span class="hljs-keyword">in</span> the given code and suggest fixes.
</code></pre>
<p>This approach narrows the LLM model’s focus, helping it analyze threats more effectively rather than offering broad, unstructured advice.</p>
<h3 id="heading-5-react-reasoning-acting-prompting">5. ReACT (Reasoning + Acting) prompting</h3>
<p>This enables AI agents to make decisions by alternating between logical reasoning and real-world actions. Instead of generating static responses, the model interacts dynamically with tools, APIs, or databases to fetch and process information.</p>
<p>For example, a personal assistant AI booking flights might use a prompt like:</p>
<pre><code class="lang-bash">Check flight availability <span class="hljs-keyword">for</span> [destination] on [date]. If no flights are found, suggest alternative dates.
</code></pre>
<p>This approach ensures the agent doesn’t hallucinate results—it retrieves real data, evaluates it, and adjusts its actions accordingly, making responses more reliable and grounded in actual outcomes. This technique integrates reasoning with real-time decision-making in agents. It’s perfect for dynamic, on-the-fly problem-solving.</p>
<h3 id="heading-6-safety-prompts">6. Safety prompts</h3>
<p>Langbase AI studio has a separate section that lets you define safety prompts inside a Pipe agent. For instance, do not answer questions outside of the given context.</p>
<p>One of its use cases can be to ensure the LLM does not provide any sensitive information in its response from the provided context.</p>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXc2pQ9a1xgRcow-Pit-Ay1O9W7G49DLx7jkFHlwtNLTCOu1PAUnO55IoBgW2dc0F1A6lo2FSTOSe_Lq020YcsNjBSrIhIBn4msooMh2nw0MMAYq6LHRaw0jSNMaMNjHoixcjIwDmg?key=Q-k-bEK6x7APjPtDCPcYSPKJ" alt="Safety prompts" width="1600" height="932" loading="lazy"></p>
<p>Learn how to define safety instructions for any LLM inside a pipe <a target="_blank" href="https://langbase.com/docs/features/safety">here.</a></p>
<h2 id="heading-how-to-fine-tune-the-llms-response-parameters">How to Fine-Tune the LLM’s Response Parameters</h2>
<p>Now that you know the techniques to design strong prompts for your Pipe agents, let's take this further by adjusting model parameters like temperature, maximum tokens, top_p, and others to refine how the model responds to user queries.</p>
<p>Here are the LLM parameters that you can tweak to build efficient Pipe agents:</p>
<ul>
<li><p><strong>Precise:</strong> Tuned for precise and accurate responses.</p>
</li>
<li><p><strong>Balanced:</strong> Strikes a balance between accuracy and creativity.</p>
</li>
<li><p><strong>Creative:</strong> Prioritizes creativity and diversity in the generated responses.</p>
</li>
<li><p><strong>Custom:</strong> Allows you to manually configure the response parameters.</p>
</li>
<li><p><strong>JSON_mode:</strong> Ensures the model will always output valid JSON.</p>
</li>
<li><p><strong>Temperature:</strong> Control how creative the LLM is with the outputs.</p>
</li>
<li><p><strong>Max_tokens:</strong> Specifies the maximum number of tokens that can be generated in the output.</p>
</li>
<li><p><strong>Frequency Penalty:</strong> Prevents the model from repeating a word that was too recently used/used too often.</p>
</li>
<li><p><strong>Presence Penalty:</strong> Prevents the model from repeating a word.</p>
</li>
<li><p><strong>Top_p:</strong> Generate tokens until the cumulative probability exceeds the chosen threshold.</p>
</li>
</ul>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXe2h29LWOzyHlHJ5fzPDIBpkJhHcsZYUXvtaBki-IYWEWrE0wrTGDFL-_VIcBsqqtjvb8OTr7_FHayhMlfdE5PXyJfFvqgSuSBPfh5QEU_AllCQg1MNsoYe-DZ-04g4zmxPE_PwyQ?key=Q-k-bEK6x7APjPtDCPcYSPKJ" alt="Fine-tune LLM model’s response parameters" width="1600" height="932" loading="lazy"></p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Building effective serverless AI agents becomes easier if you use these prompt engineering techniques. You can give it a try by creating your own Pipe agent by visiting <a target="_blank" href="http://pipe.new">pipe.new</a>.</p>
<p>Thank you for reading!</p>
<p>Connect with me by 🙌:</p>
<ul>
<li><p>Subscribing to my <a target="_blank" href="https://www.youtube.com/@AIwithMahamCodes">YouTube</a> Channel. If you are willing to learn about AI and agents.</p>
</li>
<li><p>Subscribing to my free newsletter <a target="_blank" href="https://mahamcodes.substack.com/">“The Agentic Engineer”</a> where I share all the latest AI and agents news/trends/jobs and much more.</p>
</li>
<li><p>Follow me on <a target="_blank" href="https://x.com/MahamDev">X (Twitter)</a>.</p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to build a Serverless AI Agent to Generate Cold emails for Your Dream Job ]]>
                </title>
                <description>
                    <![CDATA[ Cold emails can make a huge difference in your job search, but writing the perfect one takes time. You need to match your skills with the job description, find the right tone, and do it over and over again—it’s exhausting. This guide will walk you th... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/build-a-serverless-ai-agent-for-generating-cold-emails/</link>
                <guid isPermaLink="false">67b5df98970327b4e047537c</guid>
                
                    <category>
                        <![CDATA[ AI ]]>
                    </category>
                
                    <category>
                        <![CDATA[ llm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ai-agent ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Maham Codes ]]>
                </dc:creator>
                <pubDate>Wed, 19 Feb 2025 13:41:44 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1739971173263/869c0c1c-9b45-48af-a1d1-0982436b8630.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Cold emails can make a huge difference in your job search, but writing the perfect one takes time. You need to match your skills with the job description, find the right tone, and do it over and over again—it’s exhausting.</p>
<p>This guide will walk you through building a cold email generator agent using serverless memory agents by Langbase to automate this entire process. We’ll integrate the memory agent into a Node.js project, enabling it to read your résumé, analyze the job description, and generate a personalized, high-impact cold email in seconds.</p>
<h3 id="heading-heres-what-ill-cover">Here’s what I’ll cover:</h3>
<ol>
<li><p><a class="post-section-overview" href="#heading-large-language-models-llms-are-stateless-by-nature">Large language models (LLMs) are stateless by nature</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-memory-agents">What are Memory agents?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-reference-architecture">Reference Architecture</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-1-create-a-directory-and-initialize-npm">Step 1: Create a directory and initialize npm</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-2-create-a-serverless-pipe-agent">Step 2: Create a serverless Pipe agent</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-3-add-a-env-file">Step 3: Add a .env file</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-4-create-a-serverless-memory-agent">Step 4: Create a serverless memory agent</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-5-add-documents-to-the-memory-agent">Step 5: Add documents to the memory agent</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-6-generate-memory-embeddings">Step 6: Generate memory embeddings</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-understanding-memory-embeddings">Understanding memory embeddings</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-generate-embeddings">How to generate embeddings?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-step-7-integrate-memory-in-pipe-agent">Step 7: Integrate memory in Pipe agent</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-8-integrate-the-memory-agent-in-nodejs">Step 8: Integrate the memory agent in Node.js</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-9-start-the-baseai-server">Step 9: Start the BaseAI server</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-10-run-the-memory-agent">Step 10: Run the memory agent</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-result">The result</a></p>
</li>
</ol>
<h2 id="heading-large-language-models-llms-are-stateless-by-nature">Large Language Models (LLMs) Are Stateless by Nature</h2>
<p>LLMs (Large Language Models) are stateless because they don’t retain any memory of previous interactions or the context of past queries beyond the input they're given in a session. Each time an LLM processes a prompt, it operates on that specific prompt without any history from prior ones.</p>
<p>This stateless nature allows the model to treat each request as independent, which simplifies its architecture and training process. But this also means that without mechanisms like RAG (Retrieval-Augmented Generation) or memory (long-term), LLMs can't carry forward information from one interaction to the next.</p>
<p>To introduce continuity or context, developers can implement external systems to manage and inject context, but the model itself doesn't "remember" anything between requests.</p>
<h3 id="heading-how-do-we-solve-this">How do we solve this?</h3>
<p>By integrating <strong>Memory Agents</strong> by Langbase, we can give LLMs long-term memory—allowing them to store, retrieve, and use information dynamically, making them much more useful for real-world applications.</p>
<h2 id="heading-what-are-memory-agents">What Are Memory Agents?</h2>
<p><a target="_blank" href="https://langbase.com/docs/memory">Langbase serverless memory agents</a> (long-term memory solution) are designed to acquire, process, retain, and retrieve information seamlessly. They dynamically attach private data to any LLM, enabling context-aware responses in real time and reducing hallucinations.</p>
<p>These agents combine vector storage, Retrieval-Augmented Generation (RAG), and internet access to create a powerful managed context search API. Developers can use them to build smarter, more capable AI applications.</p>
<p>In a RAG setup, memory – when connected directly to a Langbase Pipe Agent – becomes a memory agent. This pairing gives the LLM the ability to fetch relevant data and deliver precise, contextually accurate answers—addressing the limitations of LLMs when it comes to handling private data.</p>
<p>Memory agents ensure secure local memory storage. Data used to create memory embeddings stays protected, processed within secure environments, and only sent externally if explicitly configured. Access is strictly controlled via API keys, ensuring sensitive information remains safe.</p>
<p>Note that pipe is a serverless AI agent. It has agentic memory and tools.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before we begin creating a cold email generator agent, you’ll need to have the following setup and tools ready to go.</p>
<p>In this tutorial, I’ll be using this tech stack:</p>
<ul>
<li><p><a target="_blank" href="http://baseai.dev/">BaseAI</a> — the web framework for building AI agents locally.</p>
</li>
<li><p><a target="_blank" href="http://langbase.com/">Langbase</a> — the platform to build and deploy your serverless AI agents.</p>
</li>
<li><p><a target="_blank" href="https://openai.com/">OpenAI</a> — to get the LLM key for the preferred model.</p>
</li>
</ul>
<p>You’ll also need to:</p>
<ul>
<li><p>Sign up on Langbase to get access to the API key.</p>
</li>
<li><p>Sign up on OpenAI to generate the LLM key for the model you want to use (for this demo, I’ll be using GPT-4o mini). You can generate the key <a target="_blank" href="https://platform.openai.com/api-keys">here</a>.</p>
</li>
</ul>
<h2 id="heading-reference-architecture">Reference Architecture</h2>
<p>Here’s a diagrammatic representation of the entire process of building a serverless AI agent to generate cold emails for job applications:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739900463621/e2b6753e-287f-4d69-b453-36d50f316fb8.png" alt="Reference architecture of memory agents working" class="image--center mx-auto" width="3142" height="1476" loading="lazy"></p>
<p>Let’s start building the agent!</p>
<h2 id="heading-step-1-create-a-directory-and-initialize-npm">Step 1: Create a Directory and Initialize npm</h2>
<p>To start creating a serverless AI agent that generates cold emails for a job opening, you need to create a directory in your local machine and install all the relevant dev dependencies in it. You can do this by navigating to it and running the following command in the terminal:</p>
<pre><code class="lang-bash">mkdir my-project
npm init -y
npm install dotenv
</code></pre>
<p>This command will create a package.json file in your project directory with default values. It will also install the <code>dotenv</code> package to read environment variables from the <code>.env</code> file.</p>
<h2 id="heading-step-2-create-a-serverless-pipe-agent">Step 2: Create a Serverless Pipe Agent</h2>
<p>Next, we’ll be creating a <a target="_blank" href="https://langbase.com/docs/pipe/quickstart">pipe agent</a>. Pipes are different from other agents, as they are serverless AI agents with agentic tools that can work with any language or framework. They are easily deployable, and with just one API they let you connect more than 250 LLMs to any data to build any developer API workflow.</p>
<p>To create your AI agent pipe, navigate to your project directory. Run the following command:</p>
<pre><code class="lang-bash">npx baseai@latest pipe
</code></pre>
<p>Upon running, you’ll see the following prompts:</p>
<pre><code class="lang-bash">BaseAI is not installed but required to run. Would you like to install it? Yes/No
Name of the pipe? email-generator-agent
Description of the pipe? Generates emails <span class="hljs-keyword">for</span> your dream job <span class="hljs-keyword">in</span> seconds
Status of the pipe? Public/Private
System prompt? You are a helpful AI assistant
</code></pre>
<p>Once you are done with the name, description, and status of the AI agent pipe, everything will be set up automatically for you. Your pipe will be created successfully at <code>/baseai/pipes/email-generator-agent.ts</code>.</p>
<h2 id="heading-step-3-add-a-env-file">Step 3: Add a .env File</h2>
<p>Create a <code>.env</code> file in the root directory of your project and add the OpenAI and Langbase API keys in it. You can access your Langbase API key from <a target="_blank" href="https://langbase.com/docs/api-reference/api-keys">here</a>.</p>
<h2 id="heading-step-4-create-a-serverless-memory-agent">Step 4: Create a Serverless Memory Agent</h2>
<p>Next, we’ll be creating a memory and then attaching it with the Pipe to make it a memory agent. To do this, run this command in your terminal:</p>
<pre><code class="lang-bash">npx baseai@latest memory
</code></pre>
<p>Upon running this command, you’ll see the following prompts:</p>
<pre><code class="lang-bash">Name of the memory? email-generator-memory
Description of the memory? Contains my resume
Do you want to create memory from the current project git repository? Yes/No
</code></pre>
<p>After this, everything will be set up automatically for you and you can access your memory created successfully at <code>/baseai/memory/email-generator-memory.ts</code>.</p>
<h2 id="heading-step-5-add-documents-to-the-memory-agent">Step 5: Add Documents to the Memory Agent</h2>
<p>Inside <code>/baseai/memory/email-generator-memory.ts</code> you’ll see another folder called documents. This is where you’ll store the files you want your AI agent to access. Let’s save your résumé as either a <code>.pdf</code> or <code>.txt</code> file. Then, I’ll convert it to a markdown file and place it in the <code>/baseai/memory/email-generator-memory/documents</code> directory.</p>
<p>This step ensures that the memory agent can process and retrieve information from your documents, making the AI agent capable of generating accurate cold emails based on the experiences and skills provided in the résumé attached.</p>
<h2 id="heading-step-6-generate-memory-embeddings">Step 6: Generate Memory Embeddings</h2>
<p>With your documents added to memory, the next step is generating memory embeddings. But before that, let me quickly explain what embeddings are and why they matter.</p>
<h3 id="heading-understanding-memory-embeddings">Understanding memory embeddings</h3>
<p>Memory embeddings are numerical representations of your documents that enable an AI to grasp context, relationships, and meaning within text. They act as a bridge, converting raw data into a structured format AI can process for semantic search and retrieval.</p>
<p>Without embeddings, AI agents wouldn’t effectively connect user queries with relevant content. Generating embeddings creates a searchable index, allowing the memory agent to deliver accurate, context-aware responses efficiently.</p>
<h3 id="heading-how-to-generate-embeddings">How to generate embeddings</h3>
<p>To generate embeddings for your documents, run the following command in your terminal:</p>
<pre><code class="lang-bash">npx baseai@latest embed -m email-generator-memory
</code></pre>
<p>Your memory is now ready to be connected with a Pipe (memory agent), enabling your AI agent to fetch precise, context-aware responses from your documents.</p>
<h2 id="heading-step-7-integrate-memory-in-pipe-agent">Step 7: Integrate Memory in Pipe Agent</h2>
<p>Next, you have to attach the memory you created to your Pipe agent to make it a memory agent. For that, go to <code>/baseai/pipes/email-generator-agent.ts</code>. This is what it will look like at the moment:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { PipeI } <span class="hljs-keyword">from</span> <span class="hljs-string">'@baseai/core'</span>;

<span class="hljs-keyword">const</span> pipePipeWithMemory = (): <span class="hljs-function"><span class="hljs-params">PipeI</span> =&gt;</span> ({
    apiKey: process.env.LANGBASE_API_KEY!, <span class="hljs-comment">// Replace with your API key https://langbase.com/docs/api-reference/api-keys</span>
    name: <span class="hljs-string">'email-generator-agent'</span>,
    description: <span class="hljs-string">'Generates emails for your dream job in seconds'</span>,
    status: <span class="hljs-string">'public'</span>,
    model: <span class="hljs-string">'openai:gpt-4o-mini'</span>,
    stream: <span class="hljs-literal">true</span>,
    json: <span class="hljs-literal">false</span>,
    store: <span class="hljs-literal">true</span>,
    moderate: <span class="hljs-literal">true</span>,
    top_p: <span class="hljs-number">1</span>,
    max_tokens: <span class="hljs-number">1000</span>,
    temperature: <span class="hljs-number">0.7</span>,
    presence_penalty: <span class="hljs-number">1</span>,
    frequency_penalty: <span class="hljs-number">1</span>,
    stop: [],
    tool_choice: <span class="hljs-string">'auto'</span>,
    parallel_tool_calls: <span class="hljs-literal">false</span>,
    messages: [
        { role: <span class="hljs-string">'system'</span>, content: You are a helpful AI assistant. }],
    variables: [],
    memory: [],
    tools: []
});

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> pipePipeWithMemory;
</code></pre>
<p>Now integrate the memory in the pipe by importing it at the top and calling it as a function in the <code>memory</code> array. Also, add the following in the messages content:</p>
<pre><code class="lang-bash">Based on the job description and my resume attached, write a compelling cold email tailored to the job, highlighting my most relevant skills, achievements, and experiences. Ensure the tone is professional yet approachable, and include a strong call to action <span class="hljs-keyword">for</span> a follow-up or interview.
</code></pre>
<p>This is what the code will look like after doing all of this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { PipeI } <span class="hljs-keyword">from</span> <span class="hljs-string">'@baseai/core'</span>;
<span class="hljs-keyword">import</span> emailGeneratorMemoryMemory <span class="hljs-keyword">from</span> <span class="hljs-string">'../memory/email-generator-memory'</span>;

<span class="hljs-keyword">const</span> pipeEmailGeneratorAgent = (): <span class="hljs-function"><span class="hljs-params">PipeI</span> =&gt;</span> ({
 <span class="hljs-comment">// Replace with your API key https://langbase.com/docs/api-reference/api-keys</span>
 apiKey: process.env.LANGBASE_API_KEY!,
 name: <span class="hljs-string">'email-generator-agent'</span>,
 description: <span class="hljs-string">'Generates emails for your dream job in seconds'</span>,
 status: <span class="hljs-string">'private'</span>,
 model: <span class="hljs-string">'openai:gpt-4o-mini'</span>,
 stream: <span class="hljs-literal">true</span>,
 json: <span class="hljs-literal">false</span>,
 store: <span class="hljs-literal">true</span>,
 moderate: <span class="hljs-literal">true</span>,
 top_p: <span class="hljs-number">1</span>,
 max_tokens: <span class="hljs-number">1000</span>,
 temperature: <span class="hljs-number">0.7</span>,
 presence_penalty: <span class="hljs-number">1</span>,
 frequency_penalty: <span class="hljs-number">1</span>,
 stop: [],
 tool_choice: <span class="hljs-string">'auto'</span>,
 parallel_tool_calls: <span class="hljs-literal">true</span>,
 messages: [{ role: <span class="hljs-string">'system'</span>, content: Based on the job description and my resume attached, write a compelling cold email tailored to the job, highlighting my most relevant skills, achievements, and experiences. Ensure the tone is professional yet approachable, and include a strong call to action <span class="hljs-keyword">for</span> a follow-up or interview. }],
 variables: [],
 memory: [emailGeneratorMemoryMemory()],
 tools: []
});

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> pipeEmailGeneratorAgent;
</code></pre>
<h2 id="heading-step-8-integrate-the-memory-agent-in-nodejs">Step 8: Integrate the Memory Agent in Node.js</h2>
<p>Now we’ll integrate the memory agent you created into the Node.js project to build an interactive command-line interface (CLI) for the document attached. This Node.js project will serve as the base for testing and interacting with the memory agent (in the beginning of the tutorial, we set up a Node.js project by initializing npm).</p>
<p>Now, create an index.ts file:</p>
<pre><code class="lang-bash">touch index.ts
</code></pre>
<p>In this TypeScript file, import the pipe agent you created. We will use the pipe primitive from <code>@baseai/core</code> to run the pipe.</p>
<p>Add the following code to the <code>index.ts</code> file:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> <span class="hljs-string">'dotenv/config'</span>;
<span class="hljs-keyword">import</span> { Pipe } <span class="hljs-keyword">from</span> <span class="hljs-string">'@baseai/core'</span>;
<span class="hljs-keyword">import</span> inquirer <span class="hljs-keyword">from</span> <span class="hljs-string">'inquirer'</span>;
<span class="hljs-keyword">import</span> ora <span class="hljs-keyword">from</span> <span class="hljs-string">'ora'</span>;
<span class="hljs-keyword">import</span> chalk <span class="hljs-keyword">from</span> <span class="hljs-string">'chalk'</span>;
<span class="hljs-keyword">import</span> pipeEmailGeneratorAgent <span class="hljs-keyword">from</span> <span class="hljs-string">'./baseai/pipes/email-generator-agent'</span>;

<span class="hljs-keyword">const</span> pipe = <span class="hljs-keyword">new</span> Pipe(pipeEmailGeneratorAgent());

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>) </span>{

   <span class="hljs-keyword">const</span> initialSpinner = ora(<span class="hljs-string">'Conversation with Memory agent...'</span>).start();
   <span class="hljs-keyword">try</span> {
       <span class="hljs-keyword">const</span> { completion: calculatorTool} = <span class="hljs-keyword">await</span> pipe.run({
           messages: [{ role: <span class="hljs-string">'user'</span>, content: <span class="hljs-string">'Hello'</span> }],
       });
       initialSpinner.stop();
       <span class="hljs-built_in">console</span>.log(chalk.cyan(<span class="hljs-string">'Report Generator Agent response...'</span>));
       <span class="hljs-built_in">console</span>.log(calculatorTool);
   } <span class="hljs-keyword">catch</span> (error) {
       initialSpinner.stop();
       <span class="hljs-built_in">console</span>.error(chalk.red(<span class="hljs-string">'Error processing initial request:'</span>), error);
   }

   <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {
       <span class="hljs-keyword">const</span> { userMsg } = <span class="hljs-keyword">await</span> inquirer.prompt([
           {
               <span class="hljs-keyword">type</span>: <span class="hljs-string">'input'</span>,
               name: <span class="hljs-string">'userMsg'</span>,
               message: chalk.blue(<span class="hljs-string">'Enter your query (or type "exit" to quit):'</span>),
           },
       ]);


       <span class="hljs-keyword">if</span> (userMsg.toLowerCase() === <span class="hljs-string">'exit'</span>) {
           <span class="hljs-built_in">console</span>.log(chalk.green(<span class="hljs-string">'Goodbye!'</span>));
           <span class="hljs-keyword">break</span>;
       }


       <span class="hljs-keyword">const</span> spinner = ora(<span class="hljs-string">'Processing your request...'</span>).start();


       <span class="hljs-keyword">try</span> {
           <span class="hljs-keyword">const</span> { completion: reportAgentResponse } = <span class="hljs-keyword">await</span> pipe.run({
               messages: [{ role: <span class="hljs-string">'user'</span>, content: userMsg }],
           });


           spinner.stop();
           <span class="hljs-built_in">console</span>.log(chalk.cyan(<span class="hljs-string">'Agent:'</span>));
           <span class="hljs-built_in">console</span>.log(reportAgentResponse);
       } <span class="hljs-keyword">catch</span> (error) {
           spinner.stop();
           <span class="hljs-built_in">console</span>.error(chalk.red(<span class="hljs-string">'Error processing your request:'</span>), error);
       }
   }
}

main();
</code></pre>
<p>This code creates an interactive CLI for chatting with an AI agent, using a pipe from the <code>@baseai/core</code> library to process user input. Here's what happens:</p>
<ul>
<li><p>It imports necessary libraries such as <code>dotenv</code> for environment configuration, <code>inquirer</code> for user input, <code>ora</code> for loading spinners, and <code>chalk</code> for colored output. Make sure you install these libraries first using this command in your terminal: <code>npm install ora inquirer</code>.</p>
</li>
<li><p>A pipe object is created from the BaseAI library using a predefined memory called <code>email-generator-agent</code>.</p>
</li>
</ul>
<p>In the <code>main()</code> function:</p>
<ul>
<li><p>A spinner starts while an initial conversation with the AI agent is initiated with the message 'Hello'.</p>
</li>
<li><p>The response from the AI is displayed.</p>
</li>
<li><p>A loop runs to continually ask the user for input and send queries to the AI agent.</p>
</li>
<li><p>The AI's responses are shown, and the process continues until the user types "exit”.</p>
</li>
</ul>
<h2 id="heading-step-9-start-the-baseai-server">Step 9: Start the BaseAI Server</h2>
<p>To run the memory agent locally, you need to start the BaseAI server first. Run the following command in your terminal:</p>
<pre><code class="lang-bash">npx baseai@latest dev
</code></pre>
<h2 id="heading-step-10-run-the-memory-agent">Step 10: Run the Memory Agent</h2>
<p>Run the <code>index.ts</code> file using the following command:</p>
<pre><code class="lang-bash">npx tsx index.ts
</code></pre>
<h2 id="heading-the-result">The Result</h2>
<p>In your terminal, you’ll be prompted to "Enter your query." For example, let’s paste a job description and ask to generate an email from our end showing interest. And it will give us the response with correct sources/citations as well.</p>
<p>With this setup, we’ve built a Cold Email Generator agent that uses the power of LLMs and Langbase memory agents to overcome LLMs' limitations, ensuring accurate responses without hallucinating on private data.</p>
<p>Here’s a demo of the end result:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/ns7UqX6Ycs8" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>Thank you for reading!</p>
<p>Connect with me by 🙌:</p>
<ul>
<li><p>Subscribing to my <a target="_blank" href="https://www.youtube.com/@AIwithMahamCodes">YouTube</a> Channel. If you are willing to learn about AI and agents.</p>
</li>
<li><p>Subscribing to my free newsletter <a target="_blank" href="https://mahamcodes.substack.com/">“The Agentic Engineer”</a> where I share all the latest AI and agents news/trends/jobs and much more.</p>
</li>
<li><p>Follow me on <a target="_blank" href="https://x.com/MahamDev">X (Twitter)</a>.</p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ LangChain Alternatives You Can Use to Build AI and Agentic Workflows ]]>
                </title>
                <description>
                    <![CDATA[ Building AI and agentic workflows is at the core of modern AI development in 2025. And LangChain has been the go-to framework for creating AI applications for a while now. But some developers are seeking alternatives that offer more flexibility, simp... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/langchain-alternatives-for-building-ai-and-agentic-workflows/</link>
                <guid isPermaLink="false">679bcc0fa60eb167ae249fba</guid>
                
                    <category>
                        <![CDATA[ AI ]]>
                    </category>
                
                    <category>
                        <![CDATA[ llm ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Maham Codes ]]>
                </dc:creator>
                <pubDate>Thu, 30 Jan 2025 18:59:27 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1738696551914/6800aa71-d6f2-472a-8982-35af81509813.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Building AI and agentic workflows is at the core of modern AI development in 2025. And LangChain has been the go-to framework for creating AI applications for a while now. But some developers are seeking alternatives that offer more flexibility, simplicity, and cost-effectiveness.</p>
<p>While LangChain has enabled rapid development of LLM-powered apps with tools for chaining, agents, and memory, its heavy abstraction, complex debugging, and difficulty with real-world use often make it more suited for prototyping than production-level applications.</p>
<p>In this article, we’ll explore some powerful LangChain alternatives you can try out that’ll help you build effective AI and agentic workflows. I’ll go through each one’s key features and best use cases so you can get a good idea of how it might help you.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-is-an-ai-and-agentic-workflow">What is an AI and Agentic Workflow?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-langbase">Langbase</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-llamaindex">LlamaIndex</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-ag2">AG2</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-braintrust">Braintrust</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-flowiseai">FlowiseAI</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrap-up">Wrap Up 🙌</a></p>
</li>
</ol>
<h2 id="heading-what-is-an-ai-and-agentic-workflow">What is an AI and Agentic Workflow?</h2>
<p>An <strong>AI workflow</strong> refers to a series of tasks executed by AI systems, typically following a predefined sequence. It handles tasks like data extraction, processing, and generating output based on clear instructions.</p>
<p>An <strong>agentic workflow</strong> goes a step further. It involves AI taking initiative, making decisions, and managing tasks autonomously. In agentic workflows, AI adapts its actions based on its environment or predefined goals, often without human intervention.</p>
<p>In short, an AI workflow becomes more "agentic" as it begins to think, decide, and act independently, acting like an intelligent agent. The more decisions AI can make on its own, the less it needs to be prompted by a human.</p>
<p>Now that it’s clear what an AI and agentic workflow is, let’s look at some other tools and frameworks that could serve as LangChain alternatives, each offering unique capabilities and approaches that you can use to build your AI and agentic workflows.</p>
<h2 id="heading-langbase">Langbase</h2>
<p><a target="_blank" href="http://langbase.com">Langbase</a> is a Serverless Composable AI Developer platform with multi-agent orchestration and advanced long-term memory. It’s designed for seamless AI development and deployment. Langbase provides support to over 100+ LLMs through one API ensuring a unified developer experience, with easy model switching and optimization.</p>
<p>💡 Multi-agent orchestration refers to coordinating multiple AI agents to work together on tasks. It involves controlling the flow of tasks, ensuring agents work in the right sequence, and coordinating their actions to maximize efficiency.</p>
<h3 id="heading-langbase-products">Langbase Products</h3>
<p>The platform offers the following products:</p>
<ol>
<li><p><strong>Pipe Agents:</strong> Pipe agents on Langbase are different from other agents. They are serverless AI agents with agentic tools that can work with any language or framework. Pipe agents are easily deployable, and with just one API they let you connect 100+ LLMs to any data to build any developer API workflow.</p>
</li>
<li><p><strong>Memory Agents:</strong> Langbase memory agents (long-term memory solution) are designed to acquire, process, retain, and retrieve information seamlessly. They dynamically attach private data to any LLM, enabling context-aware responses in real time and reducing hallucinations. Memory, when connected to a pipe agent, becomes a memory agent.</p>
</li>
<li><p><strong>BaseAI.dev:</strong> BaseAI is the open-source first web AI framework. With it you can start building local-first, agentic pipes, tools, and memory and deploy serverless with one command.</p>
</li>
<li><p><strong>AI Studio:</strong> Langbase AI Studio provides a playground to collaborate on AI agents, memory and tools. With it you can build, collaborate, test and deploy pipe and memory (RAG) agents.</p>
</li>
<li><p><strong>LangUI:</strong> LangUI is a free, open-source Tailwind library with ready-made components designed for AI and GPT projects.</p>
</li>
<li><p><strong>Langbase SDK:</strong> Langbase offers a TypeScript AI SDK that simplifies development. It helps you easily integrate LLMs, create memory agents, and chain them together into pipelines—all with minimal code. It supports JavaScript, TypeScript, Node.js, Next.js, React, and more, enabling faster development with a great developer experience.</p>
</li>
</ol>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcniBaqv7TmuUdmUqWejNJiulwjZDMf6Jg_Eh-AajXof7kfPVDKbiPXTQ3kgP-mXLA8cLZM87HYiL0_e6txSimQlcoPg90DCQ2lVYte1D_fzWiEGMsDP6IQMGiAO42a3-011owoHg?key=U363uJCJj9tPrezMPf7fa2Fc" alt="Source: Langbase" width="600" height="400" loading="lazy"></p>
<h3 id="heading-key-features">Key Features</h3>
<ul>
<li><p><strong>API-first platform</strong>: Simple APIs (Pipe and memory agent APIs) for easy integration with clear documentation and community support.</p>
<p>  💡 Use the Pipe API to manage the pipe agents in your Langbase account. It has create, update, list and run endpoints. The Langbase Memory API lets you manage memories and documents in your Langbase account programmatically.</p>
</li>
<li><p><strong>Serverless environment</strong>: Langbase operates in a fully serverless environment, removing the need for developers to manage infrastructure. This simplifies scaling and deployment, empowering developers of all skill levels—not just AI/ML experts—to build, scale, and deploy AI agents seamlessly.</p>
</li>
<li><p><strong>Composable infrastructure</strong>: Langbase is the <strong>first composable AI platform</strong>. It is built for flexibility and modularity. Developers can combine models into pipelines, each focused on a specific task. This makes development easier, shows the cost of each step, and lets you create highly personalized experiences. By choosing the best model for each task, Langbase helps you build efficient workflows that fit different needs.</p>
<p>  💡 Composable AI means combining different AI models like building blocks to create custom solutions. It’s simple, flexible, and adapts to your needs.</p>
</li>
<li><p><strong>Cost efficiency</strong>: Langbase offers significantly more value at a lower cost than LangChain, with overage costs just $2 per 1,000 runs compared to LangChain’s $5.</p>
</li>
</ul>
<h3 id="heading-use-cases">Use Cases</h3>
<p>Langbase is perfect for developers seeking cost-efficient solutions with seamless model switching through a single API. It’s well-suited for projects that require composable/modular AI infrastructure and advanced long-term memory features. It also excels in building autonomous workflows with multi-agent collaboration.</p>
<p>Here are a few specific applications that you can build using Langbase:</p>
<ul>
<li><p><strong>Customer Support Agent:</strong> Build customer support agents/apps that can handle complex, context-aware conversations across support tickets, emails, and chats, providing accurate, efficient resolutions. Check out the customer support agents <a target="_blank" href="https://langbase.com/docs/solutions/customer-support">here</a>.</p>
</li>
<li><p><strong>Coding Agent:</strong> Create multi-agentic apps that assist developers by generating code snippets, debugging, and reviewing code in real time, improving productivity in software development workflows. Here’s an example coding agent <a target="_blank" href="https://code-alchemist.langbase.dev/">demo</a>.</p>
</li>
</ul>
<h3 id="heading-getting-started-with-langbase">Getting Started with Langbase</h3>
<ul>
<li><p>To get started with Langbase signup for free <a target="_blank" href="https://langbase.com/signup">here</a>.</p>
</li>
<li><p>To create a pipe agent simply type pipe.new in the search bar.</p>
</li>
<li><p>To create a memory agent type rag.new in the search bar.</p>
</li>
</ul>
<h2 id="heading-llamaindex">LlamaIndex</h2>
<p><a target="_blank" href="https://www.llamaindex.ai/">LlamaIndex</a> is an open-source framework built for RAG applications and agent-based systems. It provides essential tools to ingest, structure, and connect private or domain-specific data to LLMs, enabling more accurate and reliable text generation.</p>
<p>With its support for building agents and integrating RAG pipelines as part of a broader toolset, LlamaIndex offers the flexibility to handle complex tasks.</p>
<h3 id="heading-key-features-1">Key Features</h3>
<ul>
<li><p><strong>Data loading</strong>: LlamaIndex makes data import seamless with support for 150+ sources, including APIs, PDFs, documents, and SQL databases. Using <strong>data connectors (LlamaHub)</strong>, developers can integrate diverse data into their LLM applications effortlessly. Examples include pulling real-time data from APIs, loading structured information from MySQL or PostgreSQL, and ingesting text from PDFs or reports.</p>
<p>  💡 Data Loaders are utilities that allow you to easily ingest data for search and retrieval by a large language model.</p>
</li>
<li><p><strong>Indexing</strong>: Indexing organizes and stores data for easy and fast retrieval, creating structures like vector or document indexes. With LlamaIndex, you can store and index data across multiple providers (for example, vector, document, graph, and SQL databases).</p>
</li>
<li><p><strong>Querying</strong>: Querying retrieves specific information from indexed data, enabling searches and advanced workflows like RAG pipelines for context-aware responses. For this, LlamaIndex lets you build advanced query workflows with retrieval, post-processing, and response synthesis for prompt chains and RAG pipelines.</p>
<p>  💡 A <strong>Query Pipeline</strong> in LlamaIndex is a simple way to design query workflows for different tasks like RAG and structured data extraction. It helps you define how queries interact with your data, making it easy to handle both basic and advanced workflows. Read about LlamaIndex Query Pipelines <a target="_blank" href="https://www.llamaindex.ai/blog/introducing-query-pipelines-025dc2bb0537">here</a>.</p>
</li>
<li><p><strong>Evaluations</strong>: Includes modules for evaluating retrieval and response quality, enhancing performance monitoring.</p>
</li>
</ul>
<h3 id="heading-use-cases-1">Use Cases</h3>
<p>LlamaIndex is preferred for seamless data indexing and quick retrieval, making it more suitable for production-ready RAG applications. On the other hand, LangChain provides more out-of-the-box components, making it easier to create diverse LLM architectures.</p>
<p>Here are a few specific RAG applications that you can build using LlamaIndex:</p>
<ul>
<li><p><strong>Financial Insights Assistant</strong>: Build a knowledge assistant for financial analysts to retrieve real-time insights from market data, earnings reports, and internal financial documents, enabling quicker decision-making and risk assessment.</p>
</li>
<li><p><strong>Manufacturing Advisor</strong>: Create an AI-powered assistant to streamline production workflows by accessing equipment manuals, maintenance logs, and supply chain data, improving operational efficiency and reducing downtime.</p>
</li>
</ul>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXeaMsX_VAc5eaX5XfO5fbZLa3Ak5yxQyKApHm1NcNR2iBtDovLuLBTXE2tUax73e9DZprnllnBdGva14hjGPPb1pzwiPn-TFa0Ckb0w6JbCeWQr8HAbWAq62sPdX8xfXCyFZ2UvYw?key=U363uJCJj9tPrezMPf7fa2Fc" alt="Source: LlamaIndex" width="600" height="400" loading="lazy"></p>
<h3 id="heading-getting-started-with-llamaindex">Getting Started with LlamaIndex</h3>
<p>You can get started with LlamaIndex in Python or TypeScript in just 5 lines of code.</p>
<ol>
<li><p>Set the <code>OPENAI_API_KEY</code> environment variable with your OpenAI API key.</p>
</li>
<li><p>Install the Python library: <code>pip install llama-index</code></p>
</li>
<li><p>Place your documents in a folder named <code>data</code>, then use this starter code to query them:</p>
</li>
</ol>
<pre><code class="lang-python">pythonCopyEditfrom llama_index.core <span class="hljs-keyword">import</span> VectorStoreIndex, SimpleDirectoryReader

documents = SimpleDirectoryReader(<span class="hljs-string">"data"</span>).load_data()
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine()
response = query_engine.query(<span class="hljs-string">"Your question here"</span>)
print(response)
</code></pre>
<p>For more details, check out their <a target="_blank" href="https://docs.llamaindex.ai/en/stable/#getting-started">documentation</a>.</p>
<h2 id="heading-ag2">AG2</h2>
<p><a target="_blank" href="https://ag2.ai/">AG2</a> (formerly AutoGen) is an open-source framework for building AI agents and enabling multi-agent collaboration. AG2 provides a framework for building autonomous workflows and agent collaboration, simplifying the creation of specialized agents that can work together seamlessly.</p>
<p>💡 <strong>Multi-agent collaboration</strong> refers to multiple agents working together toward a common goal, each performing tasks and sharing information as needed. The agents can be independent and specialized, but they collaborate to complete a task.</p>
<h3 id="heading-key-features-2">Key Features</h3>
<ul>
<li><p><strong>Agent collaboration</strong>: Supports multi-agent orchestration for seamless communication and task management.</p>
</li>
<li><p><strong>Flexible agent roles</strong>: Define agent behaviors, roles, and workflows with intuitive code. Assign specific roles to agents—such as data collector, analyzer, or decision-maker—and have them interact in conversations or work independently. For example, one agent might gather information, while another processes it and provides insights. These agent conversations can drive task completion, with each agent contributing based on its designated role, making workflows more dynamic and efficient.</p>
</li>
<li><p><strong>Human-in-the-loop support</strong>: AG2 enables seamless human involvement in the workflow by allowing for customizable input methods, such as manual overrides or feedback loops. It offers context-aware handoff, meaning the system can pass tasks to a human at the right moment, based on specific conditions or requirements. Additionally, interactive interfaces are provided, enabling humans to review, approve, or adjust agent actions in real-time, ensuring the system remains aligned with human judgment and oversight.</p>
</li>
<li><p><strong>Conversation patterns</strong>: Built-in patterns automate coordination tasks like message routing, state management, and dynamic speaker selection.</p>
</li>
</ul>
<h3 id="heading-use-cases-2">Use Cases</h3>
<p>AG2 stands out for its ability to handle complex agent interactions, making it a great choice for multi-agent workflows that require human collaboration.</p>
<p>Here are a few AI applications that you can build using AG2:</p>
<ul>
<li><p><strong>Content Creation and Review Pipelines:</strong> Build collaborative workflows where one agent generates written or visual content, another ensures compliance with guidelines, and a human reviewer provides creative inputs or final approval.</p>
</li>
<li><p><strong>Personalized Education Platforms:</strong> Create learning assistants where one agent curates educational content, another designs custom learning paths, and a third monitors student progress. Teachers or mentors can step in to provide personalized feedback or adjustments to the curriculum.</p>
</li>
</ul>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcuX2p7__EXrxmGP6pFHPKNtQDz6_d6vUU3PFpSy-viwSBIYpti3JCdCQzw3vUmrGOhnUG7Z9JqVd_PKgil3OI6KD5gnEe5yBDA4ImZ_5Lq-f16iIJ5RiaD6DEJuyneXT6TLw-oCQ?key=U363uJCJj9tPrezMPf7fa2Fc" alt="Source: AG2" width="600" height="400" loading="lazy"></p>
<h3 id="heading-getting-started-with-ag2">Getting Started with AG2</h3>
<p>AG2 requires <strong>Python version &gt;= 3.9, &lt; 3.14</strong>. It can be installed from pip:</p>
<pre><code class="lang-python">pip install ag2
</code></pre>
<p>For more details visit the <a target="_blank" href="https://docs.ag2.ai/docs/Getting-Started">documentation</a>.</p>
<h2 id="heading-braintrust">Braintrust</h2>
<p><a target="_blank" href="https://www.braintrust.dev/">Braintrust</a> is an end-to-end platform for evaluating, improving, and deploying large language models (LLMs) with tools for prompt engineering, data management, and continuous evaluation. Designed to make building AI applications more robust and iterative, Braintrust helps you prototype rapidly with different prompts and models, evaluate performance with built-in tools, and monitor real-world interactions in real time.</p>
<h3 id="heading-key-features-3">Key Features</h3>
<ul>
<li><p><strong>Iterative experimentation</strong>: Rapidly prototype and test prompts with different models in the integrated <a target="_blank" href="https://www.braintrust.dev/docs/guides/playground">playground</a>. You can experiment with real dataset inputs, compare responses across models (OpenAI, Anthropic, Mistral, Google, Meta, and more), and fine-tune performance in the playground.</p>
</li>
<li><p><strong>Performance insights</strong>: Evaluate model and prompt performance with built-in tools like the prompt playground, dataset imports, and scoring functions. You can test outputs against real-world data, compare models, and refine prompts iteratively. Use heuristics or LLM-based scoring to assess accuracy, track results, and improve performance over time within Braintrust's UI or SDK.</p>
</li>
<li><p><strong>Real-time monitoring</strong>: Track AI interactions with detailed logs, capturing inputs, outputs, and metadata for each request. Braintrust logs traces of AI calls, breaking them down into spans to pinpoint issues, monitor user behavior, and refine performance. Logs integrate seamlessly with evaluations, creating a feedback loop for continuous model improvement.</p>
</li>
<li><p><strong>Centralized data management</strong>: Braintrust integrates data from production, staging, and evaluations, allowing you to track changes, compare iterations, and refine models over time. Versioning ensures you can roll back, audit, and pin evaluations to specific dataset versions, supporting structured experimentation and human-in-the-loop reviews for continuous improvement.</p>
<p>  💡 Datasets allow you to collect data from production, staging, evaluations, and even manually, and then use that data to run evaluations and track improvements over time.</p>
</li>
</ul>
<h3 id="heading-use-cases-3"><strong>Use Cases</strong></h3>
<p>Braintrust is best suited for iterative model development and evaluation, especially for projects that demand robust testing and deployment pipelines. It stands out for building scalable LLM applications, offering data-driven insights that enable precise optimization and continuous improvement.</p>
<p>Here are a few apps you can build with Braintrust:</p>
<ul>
<li><p><strong>Evaluating a Chat Assistant:</strong> With Braintrust you can evaluate a chat assistant by ensuring conversational AI maintains context for accurate responses. It enables automated evaluations to assess response quality, manages datasets to refine test cases, and tracks performance for continuous improvement.</p>
</li>
<li><p><strong>AI Search Bar:</strong> Braintrust helps optimize AI-powered search by ensuring accuracy and context awareness. It logs queries to identify gaps, benchmarks search results for relevance, and compares model versions to track improvements.</p>
</li>
</ul>
<h3 id="heading-getting-started-with-braintrust">Getting Started with Braintrust</h3>
<ul>
<li><p>To get started <a target="_blank" href="https://www.braintrust.dev/signup">signup</a> on Braintrust.</p>
</li>
<li><p>Once you’re signed up, you’ll be asked to create an organization for free.</p>
</li>
<li><p>To run your first eval, you can either use the <a target="_blank" href="https://www.braintrust.dev/docs/start/eval-ui">UI</a> or the <a target="_blank" href="https://www.braintrust.dev/docs/start/eval-sdk">starter code</a> available. Install the Braintrust SDK using this command:</p>
<pre><code class="lang-bash">  npm install braintrust autoevals
</code></pre>
<p>  For more details visit the <a target="_blank" href="https://www.braintrust.dev/docs/start">documentation</a>.</p>
</li>
</ul>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcwXfdLQfJnKfYu0kNauwNFALM0fZfDPiuajC8DgcImgdUL-UmGpzhFQhRVUPj9LPLoJM_UWz7eAEU_yqwepSfgyIbFQTNIqxnABuueLNWke74CMewIe1nsp9FzO8p7WqYZbYMHpA?key=U363uJCJj9tPrezMPf7fa2Fc" alt="Source: Braintrust" width="600" height="400" loading="lazy"></p>
<h2 id="heading-flowiseai">FlowiseAI</h2>
<p><a target="_blank" href="https://flowiseai.com/">FlowiseAI</a> is an open source low-code tool for developers to build customized LLM orchestration flows &amp; AI agents. With its intuitive drag-and-drop interface, Flowise makes LLM technology accessible to a wider audience, including those with little to no coding experience.</p>
<h3 id="heading-key-features-4">Key Features</h3>
<ul>
<li><p><strong>Fast iteration</strong>: The low-code approach enables quick iterations, making it easy to move from testing to production in a fraction of the time.</p>
</li>
<li><p><strong>Chatflow and LLM orchestration</strong>: Seamlessly connect LLMs with memory, data loaders, caching, and moderation tools to manage how models process inputs, retrieve relevant data, and generate responses. This ensures controlled interactions between models, user inputs, and external data sources for optimal performance.</p>
</li>
<li><p><strong>100+ integrations</strong>: Easily connect with tools like Langchain and LlamaIndex to improve your workflows. These integrations help you link data sources, manage tasks, and add extra features, allowing you to build customized AI applications. Use them to automate work, improve model performance, or expand what your system can do based on your needs.</p>
</li>
<li><p><strong>Agents and assistants</strong>: Build autonomous agents that execute tasks using tools like multi-agents or sequential agents, enhancing your application’s capabilities. These agents can interact with external data sources and tools, enabling them to perform specialized tasks efficiently. For example, Flowise provides two approaches for creating agent-based systems: Multi-Agents, which work together in a specialized, collaborative way, and Sequential Agents, which process tasks in a structured, step-by-step manner. By integrating these systems, you can automate complex workflows and improve task execution within your app.</p>
</li>
<li><p><strong>Developer-friendly</strong>: Extend and integrate with your apps using APIs, SDKs, and embedded chat options, including React SDK and embedded widgets.</p>
</li>
</ul>
<h3 id="heading-use-cases-4">Use Cases</h3>
<p>Flowise is great for developers with little coding experience building LLM workflows and teams needing quick updates without losing functionality. It makes advanced AI workflows easy to use, even for non-experts.</p>
<p>It integrates with frameworks like LangChain and LlamaIndex, making it ideal for simplified AI development. But it may pose challenges for those new to LLMs, and code-first approaches might be better suited for highly specialized tasks.</p>
<p>Here are a few practical examples that you can build using Flowise:</p>
<ul>
<li><p><strong>Query Multiple Documents:</strong> With Flowise, you can build systems that query multiple documents by uploading them to Pinecone with metadata. Tool agents help the LLM select the appropriate document based on the question.</p>
</li>
<li><p><strong>Personal Assistants:</strong> Develop assistants who can handle tasks, schedule appointments, and provide reminders with Flowise.</p>
</li>
</ul>
<h3 id="heading-getting-started-with-flowiseai">Getting Started with FlowiseAI</h3>
<ul>
<li><p>To get started, install Flowise locally using NPM.</p>
<pre><code class="lang-bash">  npm install -g flowise
</code></pre>
<p>  💡 Prerequisite: ensure <a target="_blank" href="https://nodejs.org/en/download">NodeJS</a> is installed on machine. Node <code>v18.15.0</code> or <code>v20</code> and above is supported.</p>
</li>
<li><p>Start Flowise using this command and open <a target="_blank" href="http://localhost:3000">localhost:3000</a>:</p>
<pre><code class="lang-bash">  npx flowise start
</code></pre>
</li>
</ul>
<p>For more details check out these getting started <a target="_blank" href="https://docs.flowiseai.com/getting-started">steps</a>.</p>
<p><img src="https://docs.flowiseai.com/~gitbook/image?url=https%3A%2F%2F1820151947-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fy8ifwt9BYklr92KDdr48%252Fuploads%252Fgit-blob-b24c3b670833a97778c5374146e905d026e0b122%252Fmulti-docs-upload.png%3Falt%3Dmedia&amp;width=768&amp;dpr=4&amp;quality=100&amp;sign=1196a9d4&amp;sv=2" alt="Source: FlowiseAI" width="600" height="400" loading="lazy"></p>
<h2 id="heading-wrapping-up">Wrapping Up 🙌</h2>
<p>AI and agentic workflows are moving fast, and LangChain isn’t the only option anymore. Choosing the right tool comes down to your project’s needs—flexible agent orchestration, cutting costs, or seamless integration. As we push into 2025, these alternatives deserve your attention while building the future of AI.</p>
<p>Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Langbase Memory Agents to Make Any LLM a Conversational AI for Your Docs ]]>
                </title>
                <description>
                    <![CDATA[ It’s 2025, and Large Language Models (LLMs) still can’t access your private data. Ask them something personal, and they’ll either guess or give you the wrong answer. That’s the limitation—they’re trained on public information and don’t have access to... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-langbase-memory-agents/</link>
                <guid isPermaLink="false">678ac8f3892c4e60d8af0e95</guid>
                
                    <category>
                        <![CDATA[ llm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ai agents ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Maham Codes ]]>
                </dc:creator>
                <pubDate>Fri, 17 Jan 2025 21:17:39 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1737148633610/45e0af50-6026-4953-8e1a-953a7d5b6df6.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>It’s 2025, and Large Language Models (LLMs) still can’t access your private data. Ask them something personal, and they’ll either guess or give you the wrong answer. That’s the limitation—they’re trained on public information and don’t have access to your private context.</p>
<p>Memory agents solve this by securely linking your private data to any LLM in real time. In this tutorial, I’ll walk you through turning an LLM into a conversational AI that chats with your personal documents using Langbase memory agents.</p>
<h3 id="heading-heres-what-well-cover">Here’s what we’ll cover:</h3>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-are-memory-agents">What are Memory Agents?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-securing-your-data-with-memory-agents">Securing Your Data with Memory Agents</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-use-cases-for-memory-agents">Use Cases for Memory Agents</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-1-create-a-directory-and-initialize-npm">Step 1: Create a Directory and Initialize npm</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-2-create-a-pipe-agent">Step 2: Create a Pipe Agent</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-3-add-a-env-file">Step 3: Add a .env File</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-4-create-a-memory-agent">Step 4: Create a Memory Agent</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-5-add-documents-to-the-memory-agent">Step 5: Add Documents to the Memory Agent</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-6-generate-memory-embeddings">Step 6: Generate Memory Embeddings</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-are-memory-embeddings">What Are Memory Embeddings?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-do-you-need-memory-embeddings">Why Do You Need Memory Embeddings?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-generate-embeddings">How to Generate Embeddings</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-step-7-integrate-memory-in-pipe-agent">Step 7: Integrate Memory in Pipe Agent</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-8-integrate-the-memory-agent-in-nodejs">Step 8: Integrate the Memory Agent in Node.js</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-9-start-the-baseai-server">Step 9: Start the BaseAI Server</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-10-run-the-memory-agent">Step 10: Run the Memory Agent</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-result">The Result</a></p>
</li>
</ol>
<h2 id="heading-what-are-memory-agents">What are Memory Agents?</h2>
<p>Memory is what makes interactions meaningful. It’s how systems can remember what came before, a key aspect for building truly intelligent AI agents.</p>
<p>Here’s the thing: LLMs might seem human-like, but they don’t have memory built in. They’re <strong>stateless by  design</strong>. To make them useful for real-world tasks, you need to add memory. That’s where memory agents step in.</p>
<p><a target="_blank" href="https://langbase.com/docs/memory">Langbase memory agents</a> (long-term memory solution) are designed to <strong>acquire, process, retain, and retrieve</strong> information seamlessly. They dynamically attach private data to any LLM, enabling context-aware responses in real time and reducing hallucinations.</p>
<p>These agents combine vector storage, Retrieval-Augmented Generation (RAG), and internet access to create a powerful managed context search API. Developers can use them to build smarter, more capable AI applications.</p>
<p>In a RAG setup, memory – when connected directly to a <a target="_blank" href="https://langbase.com/docs/pipe">Langbase Pipe Agent</a> – becomes a <strong>memory agent</strong>. This pairing gives the LLM the ability to fetch relevant data and deliver precise, contextually accurate answers—addressing the limitations of LLMs when it comes to handling private data.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Pipe is a serverless AI agent. It has agentic memory and tools.</div>
</div>

<p>Here’s a diagrammatic representation of the entire process:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736776247313/6d66a33b-bf82-4a8e-96d7-1d8a6382b863.png" alt="Architectural diagram of memory agents workflow" class="image--center mx-auto" width="2004" height="1664" loading="lazy"></p>
<h2 id="heading-securing-your-data-with-memory-agents">Securing Your Data with Memory Agents</h2>
<p>Memory agents prioritize data security by keeping private information isolated and processed locally or within secure environments. The data used to create memory embeddings is not sent to external servers unless explicitly configured, ensuring sensitive information remains protected.</p>
<p>Also, access to the memory system is strictly controlled through API keys and permissions, preventing unauthorized access. This setup not only enhances AI capabilities but also maintains user trust by safeguarding their data.</p>
<h2 id="heading-use-cases-for-memory-agents">Use Cases for Memory Agents</h2>
<p>Here are some practical applications of these agents:</p>
<ul>
<li><p><strong>Customer Support:</strong> Deliver personalized, context-aware assistance by recalling interaction history.</p>
</li>
<li><p><strong>Document Search:</strong> Enable fast, semantic search in large datasets, manuals, or FAQs.</p>
</li>
<li><p><strong>Code Assistance:</strong> Provide project-specific documentation and debugging tips for developers.</p>
</li>
<li><p><strong>Knowledge Management:</strong> Centralize and retrieve internal information for teams efficiently.</p>
</li>
<li><p><strong>Education &amp; Training:</strong> Provide students or employees with customized training materials, track progress, and answer questions based on stored resources.</p>
</li>
<li><p><strong>Healthcare:</strong> Securely retrieve patient records or medical history for accurate support.</p>
</li>
<li><p><strong>Collaborative Workflows:</strong> Track project history and integrate with tools for team alignment.</p>
</li>
<li><p><strong>Legal Compliance:</strong> Reference guidelines to ensure accurate and regulation-compliant decisions.</p>
</li>
</ul>
<p>The many use cases enabled by memory agents are opening up new possibilities and changing what <strong>Artificial General Intelligence (AGI)</strong> can do.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before we begin creating a memory agent that chats with your documents, you’ll need to have the following setup and tools ready to go.</p>
<p>In this tutorial, I’ll be using the following tech stack:</p>
<ul>
<li><p><a target="_blank" href="http://baseai.dev">BaseAI</a> — the web framework for building AI agents locally.</p>
</li>
<li><p><a target="_blank" href="http://langbase.com">Langbase</a> — the platform to build and deploy your serverless AI agents.</p>
</li>
<li><p><a target="_blank" href="https://openai.com/">OpenAI</a> — to get the LLM key for the preferred model.</p>
</li>
</ul>
<p>You’ll also need to:</p>
<ul>
<li><p>Sign up on Langbase to get access to the API key.</p>
</li>
<li><p>Sign up on OpenAI to generate the LLM key for the model you want to use (for this demo, I’ll be using GPT-4o mini).</p>
</li>
</ul>
<p>Let’s get started!</p>
<h2 id="heading-step-1-create-a-directory-and-initialize-npm">Step 1: Create a Directory and Initialize npm</h2>
<p>To start creating a memory agent that chats with your documents, you need to create a directory in your local machine and install all the relevant dev dependencies in it. You can do this by navigating to it and running the following command in the terminal:</p>
<pre><code class="lang-bash">mkdir my-project
npm init -y
npm install dotenv
</code></pre>
<p>This command will create a <code>package.json</code> file in your project directory with default values. It will also install the <code>dotenv</code> package to read environment variables from the <code>.env</code> file.</p>
<h2 id="heading-step-2-create-a-pipe-agent">Step 2: Create a Pipe Agent</h2>
<p>Next, we’ll be creating a pipe agent. Pipes are different from other agents, as they are serverless AI agents with agentic tools that can work with any language or framework. They are easily deployable, and with just one API they let you connect 100+ LLMs to any data to build any developer API workflow.</p>
<p>To create your AI agent pipe, navigate to your project directory. Run the following command:</p>
<pre><code class="lang-bash">npx baseai@latest pipe
</code></pre>
<p>Upon running, you’ll see the following prompts:</p>
<pre><code class="lang-bash">BaseAI is not installed but required to run. Would you like to install it? Yes/No
Name of the pipe?  pipe-with-memory
Description of the pipe? Pipe attached to a memory
Status of the pipe? Public/Private
System prompt? You are a helpful AI assistant
</code></pre>
<p>Once you are done with the name, description, and status of the AI agent pipe, everything will be set up automatically for you. Your pipe will be created successfully at <code>/baseai/pipes/pipe-with-memory.ts</code>.</p>
<h2 id="heading-step-3-add-a-env-file">Step 3: Add a .env File</h2>
<p>Create a <code>.env</code> file in the root directory of your project and add the <a target="_blank" href="https://platform.openai.com/api-keys">OpenAI</a> and Langbase API key in it. You can access your Langbase API key from <a target="_blank" href="https://langbase.com/docs/api-reference/api-keys">here</a>.</p>
<h2 id="heading-step-4-create-a-memory-agent">Step 4: Create a Memory Agent</h2>
<p>Next, we’ll be creating a memory and then attaching it with the Pipe to make it a memory agent. To do this, run this command in your terminal:</p>
<pre><code class="lang-bash">npx baseai@latest memory
</code></pre>
<p>Upon running this command, you’ll see the following prompts:</p>
<pre><code class="lang-bash">Name of the memory?  chat-with-docs-agent
Description of the pipe? FAQs docs
Do you want to create memory from the current project git repository? Yes/No
</code></pre>
<p>After this, everything will be set up automatically for you and you can access your memory created successfully at <code>/baseai/memory/chat-with-docs-agent.ts</code>.</p>
<h2 id="heading-step-5-add-documents-to-the-memory-agent">Step 5: Add Documents to the Memory Agent</h2>
<p>Inside <code>/baseai/memory/chat-with-docs-agent.ts</code> you’ll see another folder called documents. This is where you’ll store the files you want your AI agent to access. For this demo, I’ll save the Pipe FAQs page as either a <code>.pdf</code> or <code>.txt</code> file. Then, I’ll convert it to a markdown file and place it in the <code>baseai/memory/chat-with-docs/documents</code> directory.</p>
<p>This step ensures the memory agent can <strong>process and retrieve</strong> information from your documents, making the AI agent capable of answering queries based on the content you provide.</p>
<h2 id="heading-step-6-generate-memory-embeddings">Step 6: Generate Memory Embeddings</h2>
<p>Now that you’ve added documents to the memory, the next step is to generate memory embeddings. But first, what exactly are embeddings, and why are they essential?</p>
<h3 id="heading-what-are-memory-embeddings">What Are Memory Embeddings?</h3>
<p>Embeddings are numerical representations of your documents that allow the AI to understand the context and relationships between words, phrases, and sentences. Think of embeddings as a way to translate your documents into a language the AI can process for semantic search and retrieval.</p>
<h3 id="heading-why-do-you-need-memory-embeddings">Why Do You Need Memory Embeddings?</h3>
<p>Without embeddings, the AI agent wouldn’t be able to match user queries with relevant content from your documents. By generating embeddings, you’re essentially creating a searchable index that enables accurate and efficient responses from the memory agent.</p>
<h3 id="heading-how-to-generate-embeddings">How to Generate Embeddings</h3>
<p>To generate embeddings for your documents, run the following command in your terminal:</p>
<pre><code class="lang-bash">npx baseai@latest embed -m chat-with-docs-agent
</code></pre>
<p>Your memory is now ready to be connected with a Pipe (memory agent), enabling your AI agent to fetch precise, context-aware responses from your documents.</p>
<h2 id="heading-step-7-integrate-memory-in-pipe-agent">Step 7: Integrate Memory in Pipe Agent</h2>
<p>Next, you have to attach the memory you created to your Pipe agent to make it a memory agent. For that, go to <code>/baseai/pipes/pipe-with-memory.ts</code>. This is what it will look like at the moment:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { PipeI } <span class="hljs-keyword">from</span> <span class="hljs-string">'@baseai/core'</span>;

<span class="hljs-keyword">const</span> pipePipeWithMemory = (): <span class="hljs-function"><span class="hljs-params">PipeI</span> =&gt;</span> ({
    apiKey: process.env.LANGBASE_API_KEY!, <span class="hljs-comment">// Replace with your API key https://langbase.com/docs/api-reference/api-keys</span>
    name: <span class="hljs-string">'pipe-with-memory'</span>,
    description: <span class="hljs-string">'Pipe attached to a memory'</span>,
    status: <span class="hljs-string">'public'</span>,
    model: <span class="hljs-string">'openai:gpt-4o-mini'</span>,
    stream: <span class="hljs-literal">true</span>,
    json: <span class="hljs-literal">false</span>,
    store: <span class="hljs-literal">true</span>,
    moderate: <span class="hljs-literal">true</span>,
    top_p: <span class="hljs-number">1</span>,
    max_tokens: <span class="hljs-number">1000</span>,
    temperature: <span class="hljs-number">0.7</span>,
    presence_penalty: <span class="hljs-number">1</span>,
    frequency_penalty: <span class="hljs-number">1</span>,
    stop: [],
    tool_choice: <span class="hljs-string">'auto'</span>,
    parallel_tool_calls: <span class="hljs-literal">false</span>,
    messages: [
        { role: <span class="hljs-string">'system'</span>, content: <span class="hljs-string">`You are a helpful AI assistant.`</span> }],
    variables: [],
    memory: [],
    tools: []
});

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> pipePipeWithMemory;
</code></pre>
<p>Now integrate the memory in the pipe by importing it at the top and calling it as a function in the <code>memory</code> array. This is what the code will look like after doing all of this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { PipeI } <span class="hljs-keyword">from</span> <span class="hljs-string">'@baseai/core'</span>;
<span class="hljs-keyword">import</span> chatWithDocsAgentMemory <span class="hljs-keyword">from</span> <span class="hljs-string">'../memory/chat-with-docs-agent'</span>;

<span class="hljs-keyword">const</span> pipePipeWithMemory = (): <span class="hljs-function"><span class="hljs-params">PipeI</span> =&gt;</span> ({
    apiKey: process.env.LANGBASE_API_KEY!, <span class="hljs-comment">// Replace with your API key https://langbase.com/docs/api-reference/api-keys</span>
    name: <span class="hljs-string">'pipe-with-memory'</span>,
    description: <span class="hljs-string">'Pipe attached to a memory'</span>,
    status: <span class="hljs-string">'public'</span>,
    model: <span class="hljs-string">'openai:gpt-4o-mini'</span>,
    stream: <span class="hljs-literal">true</span>,
    json: <span class="hljs-literal">false</span>,
    store: <span class="hljs-literal">true</span>,
    moderate: <span class="hljs-literal">true</span>,
    top_p: <span class="hljs-number">1</span>,
    max_tokens: <span class="hljs-number">1000</span>,
    temperature: <span class="hljs-number">0.7</span>,
    presence_penalty: <span class="hljs-number">1</span>,
    frequency_penalty: <span class="hljs-number">1</span>,
    stop: [],
    tool_choice: <span class="hljs-string">'auto'</span>,
    parallel_tool_calls: <span class="hljs-literal">false</span>,
    messages: [
        { role: <span class="hljs-string">'system'</span>, content: <span class="hljs-string">`You are a helpful AI assistant.`</span> }],
    variables: [],
    memory: [chatWithDocsAgentMemory()],
    tools: []
});

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> pipePipeWithMemory;
</code></pre>
<h2 id="heading-step-8-integrate-the-memory-agent-in-nodejs">Step 8: Integrate the Memory Agent in Node.js</h2>
<p>Now we’ll integrate the memory agent you created into the Node.js project to build an interactive command-line interface (CLI) for the document attached. This Node.js project will serve as the base for testing and interacting with the memory agent (in the beginning of the tutorial, we set up a Node.js project by initializing npm).</p>
<p>Now, create an <code>index.ts</code> file:</p>
<pre><code class="lang-bash">touch index.ts
</code></pre>
<p>In this TypeScript file, import the pipe agent you created. We will use the pipe primitive from <code>@baseai/core</code> to run the pipe.</p>
<p>Add the following code to the <code>index.ts</code> file:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> <span class="hljs-string">'dotenv/config'</span>;
<span class="hljs-keyword">import</span> { Pipe } <span class="hljs-keyword">from</span> <span class="hljs-string">'@baseai/core'</span>;
<span class="hljs-keyword">import</span> inquirer <span class="hljs-keyword">from</span> <span class="hljs-string">'inquirer'</span>;
<span class="hljs-keyword">import</span> ora <span class="hljs-keyword">from</span> <span class="hljs-string">'ora'</span>;
<span class="hljs-keyword">import</span> chalk <span class="hljs-keyword">from</span> <span class="hljs-string">'chalk'</span>;
<span class="hljs-keyword">import</span> pipePipeWithMemory <span class="hljs-keyword">from</span> <span class="hljs-string">'./baseai/pipes/pipe-with-memory'</span>;

<span class="hljs-keyword">const</span> pipe = <span class="hljs-keyword">new</span> Pipe(pipePipeWithMemory());

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>) </span>{

   <span class="hljs-keyword">const</span> initialSpinner = ora(<span class="hljs-string">'Conversation with Memory agent...'</span>).start();
   <span class="hljs-keyword">try</span> {
       <span class="hljs-keyword">const</span> { completion: calculatorTool} = <span class="hljs-keyword">await</span> pipe.run({
           messages: [{ role: <span class="hljs-string">'user'</span>, content: <span class="hljs-string">'Hello'</span> }],
       });
       initialSpinner.stop();
       <span class="hljs-built_in">console</span>.log(chalk.cyan(<span class="hljs-string">'Report Generator Agent response...'</span>));
       <span class="hljs-built_in">console</span>.log(calculatorTool);
   } <span class="hljs-keyword">catch</span> (error) {
       initialSpinner.stop();
       <span class="hljs-built_in">console</span>.error(chalk.red(<span class="hljs-string">'Error processing initial request:'</span>), error);
   }


   <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {
       <span class="hljs-keyword">const</span> { userMsg } = <span class="hljs-keyword">await</span> inquirer.prompt([
           {
               <span class="hljs-keyword">type</span>: <span class="hljs-string">'input'</span>,
               name: <span class="hljs-string">'userMsg'</span>,
               message: chalk.blue(<span class="hljs-string">'Enter your query (or type "exit" to quit):'</span>),
           },
       ]);


       <span class="hljs-keyword">if</span> (userMsg.toLowerCase() === <span class="hljs-string">'exit'</span>) {
           <span class="hljs-built_in">console</span>.log(chalk.green(<span class="hljs-string">'Goodbye!'</span>));
           <span class="hljs-keyword">break</span>;
       }


       <span class="hljs-keyword">const</span> spinner = ora(<span class="hljs-string">'Processing your request...'</span>).start();


       <span class="hljs-keyword">try</span> {
           <span class="hljs-keyword">const</span> { completion: reportAgentResponse } = <span class="hljs-keyword">await</span> pipe.run({
               messages: [{ role: <span class="hljs-string">'user'</span>, content: userMsg }],
           });


           spinner.stop();
           <span class="hljs-built_in">console</span>.log(chalk.cyan(<span class="hljs-string">'Agent:'</span>));
           <span class="hljs-built_in">console</span>.log(reportAgentResponse);
       } <span class="hljs-keyword">catch</span> (error) {
           spinner.stop();
           <span class="hljs-built_in">console</span>.error(chalk.red(<span class="hljs-string">'Error processing your request:'</span>), error);
       }
   }
}

main();
</code></pre>
<p>This code creates an interactive CLI for chatting with an AI agent, using a pipe from the <code>@baseai/core</code> library to process user input. Here's what happens:</p>
<ul>
<li><p>It imports necessary libraries such as <code>dotenv</code> for environment configuration, <code>inquirer</code> for user input, <code>ora</code> for loading spinners, and <code>chalk</code> for colored output. Make sure you install these libraries first using this command in your terminal: <code>npm install ora inquirer</code>.</p>
</li>
<li><p>A pipe object is created from the BaseAI library using a predefined memory called <code>pipe-with-memory</code>.</p>
</li>
</ul>
<p>In the <code>main()</code> function:</p>
<ul>
<li><p>A spinner starts while an initial conversation with the AI agent is initiated with the message 'Hello'.</p>
</li>
<li><p>The response from the AI is displayed.</p>
</li>
<li><p>A loop runs to continually ask the user for input and send queries to the AI agent.</p>
</li>
<li><p>The AI's responses are shown, and the process continues until the user types "exit”.</p>
</li>
</ul>
<h2 id="heading-step-9-start-the-baseai-server">Step 9: Start the BaseAI Server</h2>
<p>To run the memory agent locally, you need to start the BaseAI server first. Run the following command in your terminal:</p>
<pre><code class="lang-bash">npx baseai@latest dev
</code></pre>
<h2 id="heading-step-10-run-the-memory-agent">Step 10: Run the Memory Agent</h2>
<p>Run the index.ts file using the following command:</p>
<pre><code class="lang-bash">npx tsx index.ts
</code></pre>
<h2 id="heading-the-result">The Result</h2>
<p>In your terminal, you’ll be prompted to "Enter your query." For example, let’s ask: "What is a pipe on Langbase?" And it will give us the response with correct sources/citations as well.</p>
<p>With this setup, we’ve built a "Chat with Your Document" agent that uses the power of LLMs and Langbase memory agents to overcome LLMs' limitations, ensuring accurate responses without hallucinating on private data.</p>
<p>Here’s a demo of the end result:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/v2Iev-q3kuc" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>Thank you for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Make LLMs Better at Math Using AI Agents, MathJS, and BaseAI Tool Calls ]]>
                </title>
                <description>
                    <![CDATA[ Large Language Models (LLMs) like GPT often struggle to answer mathematical questions. In fact, if you ask a human a tough math question, like what is 185 cm in ft, they’ll struggle as well. They’d likely need a calculator to perform this conversion ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/make-llms-better-at-math-with-ai-agents/</link>
                <guid isPermaLink="false">6764337a5ad7698ab9779d34</guid>
                
                    <category>
                        <![CDATA[ llm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ AI ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ai agents ]]>
                    </category>
                
                    <category>
                        <![CDATA[ openai ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Maham Codes ]]>
                </dc:creator>
                <pubDate>Thu, 19 Dec 2024 14:53:46 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1734537732263/2ec966b6-d1d3-4d0f-ae37-982ef26ebc55.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Large Language Models (LLMs) like GPT often struggle to answer mathematical questions. In fact, if you ask a human a tough math question, like what is 185 cm in ft, they’ll struggle as well. They’d likely need a calculator to perform this conversion – and so do LLMs.</p>
<p>LLMs are built to handle natural language. While generally being good at generating words and stringing together language, when it comes to math, they often need help.</p>
<p>Unlike a calculator or math library, LLMs cannot sometimes reason or process symbolic logic. So, while they can manage basic arithmetic, especially if it's something familiar from their training data, they typically struggle with more complex problems, particularly word problems.</p>
<p>The main question is how to fix this LLM limitation?</p>
<p>No doubt, LLMs have evolved with the launch of reasoning models like GPT-o1 or Llama 3.3. But they still hallucinate, lack real-time data access, struggle with complex math, and produce non-deterministic outputs. Fortunately, we can solve this problem using AI agents.</p>
<h2 id="heading-what-is-an-ai-agent">What is an AI Agent?</h2>
<p>AI agents are autonomous software that use LLMs to perform tasks beyond simple text generation.</p>
<p>They make decisions and execute actions. AI agents rely on LLMs for language understanding but add capabilities like memory, real-time interaction, and decision-making.</p>
<h2 id="heading-how-ai-agents-solve-llm-limitations">How AI Agents Solve LLM Limitations</h2>
<p>Agents augment the capabilities of LLMs in the following ways:</p>
<ul>
<li><p><strong>Memory:</strong> AI agents help LLMs retain context from past interactions, improving long-term conversation coherence.</p>
</li>
<li><p><strong>Asynchronous processing:</strong> Agents handle multiple tasks at once, enhancing efficiency.</p>
</li>
<li><p><strong>Fact-checking:</strong> They connect to real-time data sources to verify information.</p>
</li>
<li><p><strong>Enhanced math:</strong> They integrate tools to handle complex calculations.</p>
</li>
<li><p><strong>Consistent output:</strong> Agents standardize LLM outputs for uniform formatting.</p>
</li>
</ul>
<p>To help address some of the math limitations LLMs experience, let’s create an AI agent that builds a calculator using MathJS and BaseAI tool calls.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>In this tutorial, I’ll be using the following tech stack:</p>
<ul>
<li><p><a target="_blank" href="https://mathjs.org/">MathJS</a> — an extensive math library for JavaScript and Node.js.</p>
</li>
<li><p><a target="_blank" href="https://baseai.dev">BaseAI</a> — the web framework for building AI agents locally.</p>
</li>
<li><p><a target="_blank" href="https://langbase.com">Langbase</a> — the platform to build and deploy your serverless AI agents.</p>
</li>
<li><p><a target="_blank" href="https://openai.com">OpenAI</a> — to get the LLM key for the preferred model.</p>
</li>
</ul>
<p>You’ll also need to:</p>
<ul>
<li><p>Sign up on Langbase to get access to the API key.</p>
</li>
<li><p>Sign up on OpenAI to generate the LLM key for the model you want to use (for this demo, I’ll be using GPT-4o mini).</p>
</li>
</ul>
<p>Let’s get started!</p>
<h2 id="heading-step-1-create-a-directory-and-initialize-npm">Step 1: Create a Directory and Initialize npm</h2>
<p>To start creating an AI agent, you need to create a directory in your local machine and install all the relevant dev dependancies in it. You can do this by navigating to it and running the following command in the terminal:</p>
<pre><code class="lang-bash">mkdir my-project

npm init -y

npm install dotenv mathjs
</code></pre>
<p>This command will create a <code>package.json</code> file in your project directory with default values. It will also install the <code>dotenv</code> package to read environment variables from the <code>.env</code> file, and <code>mathjs</code> to handle math operations.</p>
<h2 id="heading-step-2-create-an-ai-agent-pipe">Step 2: Create an AI Agent Pipe</h2>
<p>Next, we’ll be creating an AI agent pipe. Pipes are different from other agents, as they <strong>are serverless AI agents with agentic tools</strong> that can work with any language or framework. They are easily deployable, and with just one API they let you connect 100+ LLMs to any data to build any developer API workflow.</p>
<p>To create your AI agent pipe, navigate to your project directory. Run the following command:</p>
<pre><code class="lang-bash">npx baseai@latest pipe
</code></pre>
<p>Upon running that command, you’ll see the following prompts:</p>
<pre><code class="lang-bash">BaseAI is not installed but required to run. Would you like to install it? Yes/No

Name of the pipe? pipe-with-tool

Description of the pipe? An AI agent pipe that can call tools

Status of the pipe? Public/Private

System prompt? You are a helpful AI assistant
</code></pre>
<p>Once you are done with the name, description, and status of the AI agent pipe, everything will be set up automatically for you. Your pipe will be created successfully at <code>/baseai/pipes/pipe-with-tool.ts</code>.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Pipe is a serverless AI agent. It has agentic memory and tools.</div>
</div>

<h2 id="heading-step-3-add-a-env-file">Step 3: Add a .env File</h2>
<p>Create a <code>.env</code> file in the root directory of your project and add the <a target="_blank" href="https://platform.openai.com/api-keys">OpenAI</a> and Langbase API key in it. You can access your Langbase API key from <a target="_blank" href="https://langbase.com/docs/api-reference/api-keys">here</a>.</p>
<h2 id="heading-step-4-configure-the-ai-agent-pipe">Step 4: Configure the AI Agent Pipe</h2>
<p>In this step, we’ll configure the AI agent pipe created according to our needs.</p>
<p>Navigate to your project directory and open the AI agent pipe you created. You can add a system prompt to the pipe if you want. I’m sticking to <code>You are a helpful AI assistant that will work as a calculator.</code> This is what it will look like:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { PipeI } <span class="hljs-keyword">from</span> <span class="hljs-string">'@baseai/core'</span>;

<span class="hljs-keyword">const</span> pipePipeWithTool = (): <span class="hljs-function"><span class="hljs-params">PipeI</span> =&gt;</span> ({
   apiKey: process.env.LANGBASE_API_KEY!,
   name: <span class="hljs-string">'pipe-with-tool'</span>,
   description: <span class="hljs-string">'An AI agent pipe that can call tools'</span>,
   status: <span class="hljs-string">'private'</span>,
   model: <span class="hljs-string">'openai:gpt-4o-mini'</span>,
   stream: <span class="hljs-literal">true</span>,
   json: <span class="hljs-literal">false</span>,
   store: <span class="hljs-literal">true</span>,
   moderate: <span class="hljs-literal">true</span>,
   top_p: <span class="hljs-number">1</span>,
   max_tokens: <span class="hljs-number">1000</span>,
   temperature: <span class="hljs-number">0.7</span>,
   presence_penalty: <span class="hljs-number">1</span>,
   frequency_penalty: <span class="hljs-number">1</span>,
   stop: [],
   tool_choice: <span class="hljs-string">'auto'</span>,
   parallel_tool_calls: <span class="hljs-literal">true</span>,
   messages: [{ role: <span class="hljs-string">'system'</span>, content: <span class="hljs-string">`You are a helpful AI assistant that will work as a calculator.`</span> }],
   variables: [],
   memory: [],
   tools: []
});

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> pipePipeWithTool;
</code></pre>
<h2 id="heading-step-5-create-a-calculator-tool">Step 5: Create a Calculator Tool</h2>
<p>Tool calling lets an LLM use external tools, such as functions, APIs, or other resources, to get information or perform tasks beyond its built-in knowledge.</p>
<p>In this step, we'll create a <strong>Calculator Tool</strong> using BaseAI tools. This tool will handle all mathematical computations in your project, ensuring they are error-free and trustworthy. The tool is versatile and suitable for both simple calculations (e.g., <code>5+7</code>) and more advanced ones (e.g., <code>sin(pi/4) + log(10)</code>).</p>
<p>It will also be particularly helpful in reducing hallucinations, which it can do by offloading computations to an external tool This avoids incorrect or fabricated answers that LLMs might otherwise generate. It also reduces the likelihood of getting incorrect responses from the LLM by rechecking or gathering additional data to ensure accuracy.</p>
<p>By using BaseAI's smart tool-calling and memory features, we can reduce AI hallucinations by <strong>21%</strong> while improving the model's ability to self-correct its outputs.</p>
<p>These enhancements are useful when dealing with complex mathematical expressions or formula evaluations and should really improve the quality and accuracy of the LLM’s answers.</p>
<p>To create a calculator tool in your project that will be responsible for doing all the calculations without errors, run this command in your terminal:</p>
<pre><code class="lang-bash">npx baseai@latest tool
</code></pre>
<p>You’ll be asked to provide a name and description of the tool in your terminal. This is what I’m providing:</p>
<pre><code class="lang-bash">Name of the tool? Calculator

Description of the tool? Evaluate mathematical expressions
</code></pre>
<p>Your tool will be created at <code>/baseai/tools/calculator.ts</code>.</p>
<h2 id="heading-step-6-configure-the-calculator-tool">Step 6: Configure the Calculator Tool</h2>
<p>To configure the tool, navigate to your project directory and open the tool you created. You can find it at <code>/baseai/tools/calculator.ts</code>.</p>
<p>This is what the code will look like:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { ToolI } <span class="hljs-keyword">from</span> <span class="hljs-string">'@baseai/core'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculator</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-comment">// Add your tool logic here</span>
   <span class="hljs-comment">// This function will be called when the tool is executed</span>
}

<span class="hljs-keyword">const</span> toolCalculator = (): <span class="hljs-function"><span class="hljs-params">ToolI</span> =&gt;</span> ({
   run: calculator,
   <span class="hljs-keyword">type</span>: <span class="hljs-string">'function'</span> <span class="hljs-keyword">as</span> <span class="hljs-keyword">const</span>,
   <span class="hljs-function"><span class="hljs-keyword">function</span>: </span>{
       name: <span class="hljs-string">'toolCalculator'</span>,
       description: <span class="hljs-string">'Evaluate mathematical expressions'</span>,
       parameters: {}
   }
});

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> toolCalculator;
</code></pre>
<p>The <code>run</code> key in the <code>toolCalculator</code> object is the function that will be executed when the tool is called. You can write your logic to get the mathematical calculations for a given function.</p>
<p>Update the calculator tool’s description and code by adding parameters to the calculator function. The LLM will give values to these parameters when it calls the tool. And it’ll even import math from <code>mathjs</code>. This is the final code:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> math <span class="hljs-keyword">from</span> <span class="hljs-string">'mathjs'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculator</span>(<span class="hljs-params">{expression}: {expression: <span class="hljs-built_in">string</span>}</span>) </span>{
   <span class="hljs-keyword">return</span> math.evaluate(expression);
}

<span class="hljs-keyword">const</span> toolCalculator = <span class="hljs-function">() =&gt;</span> ({
   run: calculator,
   <span class="hljs-keyword">type</span>: <span class="hljs-string">'function'</span> <span class="hljs-keyword">as</span> <span class="hljs-keyword">const</span>,
   <span class="hljs-function"><span class="hljs-keyword">function</span>: </span>{
       name: <span class="hljs-string">'calculator'</span>,
       description:
           <span class="hljs-string">`A tool that can evaluate mathematical expressions. `</span> +
           <span class="hljs-string">`Example expressions: `</span> +
           <span class="hljs-string">`'5.6 * (5 + 10.5)', '7.86 cm to inch', 'cos(80 deg) ^ 4'.`</span>,
       parameters: {
           <span class="hljs-keyword">type</span>: <span class="hljs-string">'object'</span>,
           required: [<span class="hljs-string">'expression'</span>],
           properties: {
               expression: {
                   <span class="hljs-keyword">type</span>: <span class="hljs-string">'string'</span>,
                   description: <span class="hljs-string">'The mathematical expression to evaluate.'</span>,
               },
           },
       },
   },
});

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> toolCalculator;
</code></pre>
<h2 id="heading-step-7-integrate-the-tool-in-the-ai-agent-pipe">Step 7: Integrate the Tool in the AI Agent Pipe</h2>
<p>In this step, we’ll integrate the tool in the AI agent pipe we created. For that, open the pipe file present at <code>/baseai/pipes/pipe-with-tool.ts</code> and import the calculator tool at the top of the file. We will also call the calculator tool in the tools array of the pipe.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> {PipeI} <span class="hljs-keyword">from</span> <span class="hljs-string">'@baseai/core'</span>;
<span class="hljs-keyword">import</span> toolCalculator <span class="hljs-keyword">from</span> <span class="hljs-string">'../tools/calculator'</span>;

<span class="hljs-keyword">const</span> pipeWithTools = (): <span class="hljs-function"><span class="hljs-params">PipeI</span> =&gt;</span> ({
   apiKey: process.env.LANGBASE_API_KEY!,
   name: <span class="hljs-string">'pipe-with-tool'</span>,
   description: <span class="hljs-string">'An AI agent pipe that can call tools'</span>,
   status: <span class="hljs-string">'public'</span>,
   model: <span class="hljs-string">'openai:gpt-4o-mini'</span>,
   stream: <span class="hljs-literal">false</span>,
   json: <span class="hljs-literal">false</span>,
   store: <span class="hljs-literal">true</span>,
   moderate: <span class="hljs-literal">true</span>,
   top_p: <span class="hljs-number">1</span>,
   max_tokens: <span class="hljs-number">1000</span>,
   temperature: <span class="hljs-number">0.7</span>,
   presence_penalty: <span class="hljs-number">1</span>,
   frequency_penalty: <span class="hljs-number">1</span>,
   stop: [],
   tool_choice: <span class="hljs-string">'auto'</span>,
   parallel_tool_calls: <span class="hljs-literal">true</span>,
   messages: [{role: <span class="hljs-string">'system'</span>, content: <span class="hljs-string">`You are a helpful AI assistant that will work as a calculator.`</span>}],
   variables: [],
   memory: [],
   tools: [ toolCalculator()],
});

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> pipeWithTools;
</code></pre>
<h2 id="heading-step-8-integrate-ai-agent-pipe-in-nodejs">Step 8: Integrate AI Agent Pipe in Node.js</h2>
<p>Now we’ll integrate the AI agent pipe you created into the Node.js project to build an interactive command-line interface (CLI) for the calculator tool. This Node.js project will serve as the base for testing and interacting with the AI agent pipe (in the beginning of the tutorial, we set up a Node.js project by initializing npm).</p>
<p>Now, create an <code>index.ts</code> file:</p>
<pre><code class="lang-bash">touch index.ts
</code></pre>
<p>In this TypeScript file, import the AI agent pipe you created. We will use the pipe primitive from <code>@baseai/core</code> to run the pipe.</p>
<p>Add the following code to the <code>index.ts</code> file:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> <span class="hljs-string">'dotenv/config'</span>;
<span class="hljs-keyword">import</span> { Pipe } <span class="hljs-keyword">from</span> <span class="hljs-string">'@baseai/core'</span>;
<span class="hljs-keyword">import</span> inquirer <span class="hljs-keyword">from</span> <span class="hljs-string">'inquirer'</span>;
<span class="hljs-keyword">import</span> ora <span class="hljs-keyword">from</span> <span class="hljs-string">'ora'</span>;
<span class="hljs-keyword">import</span> chalk <span class="hljs-keyword">from</span> <span class="hljs-string">'chalk'</span>;
<span class="hljs-keyword">import</span> pipePipeWithTool <span class="hljs-keyword">from</span> <span class="hljs-string">'./baseai/pipes/pipe-with-tool'</span>;

<span class="hljs-keyword">const</span> pipe = <span class="hljs-keyword">new</span> Pipe(pipePipeWithTool());

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>) </span>{

   <span class="hljs-keyword">const</span> initialSpinner = ora(<span class="hljs-string">'Conversation with Math agent...'</span>).start();
   <span class="hljs-keyword">try</span> {
       <span class="hljs-keyword">const</span> { completion: calculatorTool} = <span class="hljs-keyword">await</span> pipe.run({
           messages: [{ role: <span class="hljs-string">'user'</span>, content: <span class="hljs-string">'Hello'</span> }],
       });
       initialSpinner.stop();
       <span class="hljs-built_in">console</span>.log(chalk.cyan(<span class="hljs-string">'Report Generator Agent response...'</span>));
       <span class="hljs-built_in">console</span>.log(calculatorTool);
   } <span class="hljs-keyword">catch</span> (error) {
       initialSpinner.stop();
       <span class="hljs-built_in">console</span>.error(chalk.red(<span class="hljs-string">'Error processing initial request:'</span>), error);
   }

   <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {
       <span class="hljs-keyword">const</span> { userMsg } = <span class="hljs-keyword">await</span> inquirer.prompt([
           {
               <span class="hljs-keyword">type</span>: <span class="hljs-string">'input'</span>,
               name: <span class="hljs-string">'userMsg'</span>,
               message: chalk.blue(<span class="hljs-string">'Enter your query (or type "exit" to quit):'</span>),
           },
       ]);

       <span class="hljs-keyword">if</span> (userMsg.toLowerCase() === <span class="hljs-string">'exit'</span>) {
           <span class="hljs-built_in">console</span>.log(chalk.green(<span class="hljs-string">'Goodbye!'</span>));
           <span class="hljs-keyword">break</span>;
       }

       <span class="hljs-keyword">const</span> spinner = ora(<span class="hljs-string">'Processing your request...'</span>).start();

       <span class="hljs-keyword">try</span> {
           <span class="hljs-keyword">const</span> { completion: reportAgentResponse } = <span class="hljs-keyword">await</span> pipe.run({
               messages: [{ role: <span class="hljs-string">'user'</span>, content: userMsg }],
           });

           spinner.stop();
           <span class="hljs-built_in">console</span>.log(chalk.cyan(<span class="hljs-string">'Agent:'</span>));
           <span class="hljs-built_in">console</span>.log(reportAgentResponse);
       } <span class="hljs-keyword">catch</span> (error) {
           spinner.stop();
           <span class="hljs-built_in">console</span>.error(chalk.red(<span class="hljs-string">'Error processing your request:'</span>), error);
       }
   }
}

main();
</code></pre>
<p>This code creates an interactive CLI for chatting with an AI agent, using a pipe from the <code>@baseai/core</code> library to process user input. Here's what happens:</p>
<ul>
<li><p>It imports necessary libraries such as <code>dotenv</code> for environment configuration, <code>inquirer</code> for user input, <code>ora</code> for loading spinners, and <code>chalk</code> for colored output. Make sure you install these libraries first using this command in your terminal <code>npm install ora inquirer</code>.</p>
</li>
<li><p>A pipe object is created from the BaseAI library using a predefined tool called <code>pipe-with-tool</code>.</p>
</li>
</ul>
<p>In the <code>main()</code> function:</p>
<ul>
<li><p>A spinner starts while an initial conversation with the AI agent is initiated with the message 'Hello'.</p>
</li>
<li><p>The response from the AI is displayed.</p>
</li>
<li><p>A loop runs to continually ask the user for input and send queries to the AI agent.</p>
</li>
<li><p>The AI's responses are shown, and the process continues until the user types "exit”.</p>
</li>
</ul>
<h2 id="heading-step-9-start-the-baseai-server">Step 9: Start the BaseAI Server</h2>
<p>To run the AI agent pipe locally, you need to start the BaseAI server. Run the following command in your terminal:</p>
<pre><code class="lang-bash">npx baseai@latest dev
</code></pre>
<h2 id="heading-step-10-run-the-ai-agent-pipe">Step 10: Run the AI Agent Pipe</h2>
<p>Run the <code>index.ts</code> file using the following command:</p>
<pre><code class="lang-bash">npx tsx index.ts
</code></pre>
<h2 id="heading-result">Result</h2>
<p>In your terminal, you’ll be prompted to <strong>"Enter your query."</strong> For example, let’s ask: <strong>"What is 120 cm in feet?"</strong> LLMs usually hallucinate when converting to feet. But because of the self-healing tool calling of the BaseAI framework, the tool detects and corrects its own errors.</p>
<p>With this setup, we’ve successfully built an AI agent that uses <strong>MathJS</strong> and <strong>BaseAI tool calls</strong> to eliminate the mathematical limitations of LLMs.</p>
<p>Here’s a demo of the end result:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/bBukL1Vte0g" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>As Large Language Models (LLMs) often struggle with mathematical reasoning due to their focus on language, leading to frequent errors in calculations, especially with complex math problems.</p>
<p>AI agents extend LLM capabilities by integrating tool calls. They handle real-time data, ensure more consistent outputs, and reduce hallucination.</p>
<p>By incorporating MathJS and tool calls via the BaseAI framework, developers can create custom serverless AI agents called pipes that serve as reliable calculators and address LLMs' inherent limitations.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
