<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[llm-exe - Medium]]></title>
        <description><![CDATA[A series of practical examples and patterns showing how to build LLM features with llm-exe: structured, testable, and composable. Covers prompts, parsing, validation, control flow, and more. - Medium]]></description>
        <link>https://medium.com/llm-exe?source=rss----3653156bcad7---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>llm-exe - Medium</title>
            <link>https://medium.com/llm-exe?source=rss----3653156bcad7---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 21:01:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/llm-exe" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building AI Agents Before Function Calling Existed: The Pattern That Powers Everything]]></title>
            <link>https://medium.com/llm-exe/building-ai-agents-before-function-calling-existed-the-pattern-that-powers-everything-602a2f1b1685?source=rss----3653156bcad7---4</link>
            <guid isPermaLink="false">https://medium.com/p/602a2f1b1685</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[llm-function-calling]]></category>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[llm-applications]]></category>
            <dc:creator><![CDATA[llm-exe]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 16:47:20 GMT</pubDate>
            <atom:updated>2026-04-12T16:47:21.275Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EMIovrLqBmSG6Y8hN0ENuw.png" /></figure><h3><strong>Function Calling Is Just Structured Prompting</strong></h3><p>OpenAI announced function calling in June 2023. It was genuinely useful — a clean API for letting LLMs use tools.</p><p>But here’s the thing: llm-exe had “callable executors” doing the exact same thing since May, 2023. Two weeks earlier.</p><p>Why? Because we realized something important: Any LLM that can output JSON can use tools. Function calling isn’t magic. It’s a pattern.</p><p>And once you understand the pattern, you can implement it with any model.</p><p><em>(No joke! Check the </em><a href="https://github.com/gregreindel/llm-exe/commit/cdb94d53991d7f1aedb7c3966dc2799209aca28b"><em>commit history</em></a><em>. We were doing tools before tools were cool.)</em></p><h3><strong>The Pattern Behind the Curtain</strong></h3><p>Here’s what actually happens when you use function calling:</p><pre>// What you think happens:<br>const response = await openai.chat.completions.create({<br>  model: &quot;gpt-4&quot;,<br>  messages: [{ role: &quot;user&quot;, content: &quot;What&#39;s the weather?&quot; }],<br>  functions: [{ name: &quot;get_weather&quot;, parameters: {...} }]<br>});<br><br>// What ACTUALLY happens (simplified):<br>const response = await openai.chat.completions.create({<br>  model: &quot;gpt-4&quot;,<br>  messages: [<br>    {<br>      role: &quot;system&quot;,<br>      content: `You have access to these functions:<br>      - get_weather: Get weather for a location<br><br>      To use a function, respond with:<br>      {&quot;function&quot;: &quot;get_weather&quot;, &quot;arguments&quot;: {&quot;location&quot;: &quot;San Francisco&quot;}}`<br>    },<br>    { role: &quot;user&quot;, content: &quot;What&#39;s the weather?&quot; }<br>  ]<br>});</pre><p>The model providers are essentially:</p><ol><li>Injecting your functions into a hidden prompt</li><li>Parsing the model’s structured output</li><li>Handling edge cases and errors for you</li></ol><p>To be fair, they’ve also fine-tuned models to be better at this specific format, and they handle a lot of complexity under the hood. But the core pattern? It’s simpler than you might think.</p><h3><strong>Build Your Own “Function Calling” in 5 Minutes</strong></h3><p>Let me show you how to build a tool-using agent that works with ANY model:</p><pre>import {<br>  useLlm,<br>  createLlmExecutor,<br>  createChatPrompt,<br>  createParser,<br>} from &quot;llm-exe&quot;;<br><br>// Step 1: Define your tools<br>const tools = [<br>  {<br>    name: &quot;calculate&quot;,<br>    description: &quot;Perform mathematical calculations&quot;,<br>    handler: (input: string) =&gt; {<br>      return { result: eval(input) }; // Don&#39;t do this in prod!<br>    },<br>  },<br>  {<br>    name: &quot;search&quot;,<br>    description: &quot;Search for information&quot;,<br>    handler: async (query: string) =&gt; {<br>      // Your actual search implementation<br>      return { result: `Results for: ${query}` };<br>    },<br>  },<br>];<br><br>// Step 2: Create a prompt that describes the tools<br>const toolPrompt = createChatPrompt&lt;{ question: string; tools: any[] }&gt;(`<br>You have access to these tools:<br>{{#each tools}}<br>- {{name}}: {{description}}<br>{{/each}}<br><br>To use a tool, respond with this JSON format:<br>{<br>  &quot;thought&quot;: &quot;Why I need this tool&quot;,<br>  &quot;action&quot;: &quot;tool_name&quot;,<br>  &quot;input&quot;: &quot;tool input&quot;<br>}<br><br>Question: {{question}}<br>`);<br><br>// Step 3: Parse the response<br>const toolParser = createParser(&quot;json&quot;, {<br>  schema: {<br>    type: &quot;object&quot;,<br>    properties: {<br>      thought: { type: &quot;string&quot; },<br>      action: { type: &quot;string&quot; },<br>      input: { type: &quot;string&quot; },<br>    },<br>  },<br>});<br><br>// Step 4: Create the executor<br>const agent = createLlmExecutor({<br>  llm: useLlm(&quot;openai.gpt-3.5-turbo&quot;), // Works with ANY model!<br>  prompt: toolPrompt,<br>  parser: toolParser,<br>});<br><br>// Step 5: Use it!<br>async function runAgent(question: string) {<br>  // Get the model&#39;s choice<br>  const choice = await agent({ question, tools });<br><br>  // Execute the chosen tool<br>  const tool = tools.find((t) =&gt; t.name === choice.action);<br>  const result = await tool.handler(choice.input);<br><br>  // Continue the conversation with the result<br>  console.log(`Thought: ${choice.thought}`);<br>  console.log(`Used tool: ${choice.action}`);<br>  console.log(`Result: ${result.result}`);<br>}<br><br>await runAgent(&quot;What&#39;s 123 * 456?&quot;);<br>// Output:<br>// Thought: I need to calculate this multiplication<br>// Used tool: calculate<br>// Result: 56088</pre><h3><strong>The Trade-offs: When DIY Makes Sense</strong></h3><p>Look, native function calling is great when it works. It’s optimized, clean, and handles errors well. But implementing it yourself gives you some unique advantages:</p><p><strong>1. Works with ANY Model</strong></p><pre>// Same code works with:<br>useLlm(&quot;openai.gpt-3.5-turbo&quot;); // ✅<br>useLlm(&quot;anthropic.claude-instant&quot;); // ✅<br>useLlm(&quot;ollama.llama2&quot;); // ✅<br>useLlm(&quot;some-random-model&quot;); // ✅</pre><p><strong>2. Add Custom Fields</strong></p><pre>// Want confidence scores? Just add them:<br>const parser = createParser(&quot;json&quot;, {<br>  schema: {<br>    properties: {<br>      thought: { type: &quot;string&quot; },<br>      action: { type: &quot;string&quot; },<br>      input: { type: &quot;string&quot; },<br>      confidence: { type: &quot;number&quot; }, // 👈 Your addition!<br>      reasoning_steps: { type: &quot;array&quot; }, // 👈 Why not?<br>    },<br>  },<br>});</pre><p><strong>3. Debug Everything</strong></p><pre>// See EXACTLY what the model sees:<br>console.log(prompt); // No hidden system prompts<br>console.log(response); // Raw model output<br>console.log(parsed); // Your structured data</pre><p><strong>4. Custom Routing Logic</strong></p><pre>// Route based on confidence, user permissions, cost, whatever:<br>if (choice.confidence &lt; 0.8) {<br>  return askUserForConfirmation(choice);<br>}<br><br>if (choice.action === &quot;delete_database&quot; &amp;&amp; !user.isAdmin) {<br>  return &quot;Nice try&quot;;<br>}</pre><h3><strong>Real World: This Actually Works</strong></h3><p>Here’s a reasoning agent that thinks step-by-step, uses tools, and works with GPT-3.5:</p><pre>const reasoningAgent = createLlmExecutor({<br>  llm: useLlm(&quot;openai.gpt-3.5-turbo&quot;),<br>  prompt: createChatPrompt(`<br>    Solve this step by step. For each step:<br>    1. Think about what you need<br>    2. Choose a tool<br>    3. Use it<br>    4. Analyze the result<br>    5. Decide if you need more info<br>    <br>    Available tools:<br>    - search: Find information<br>    - calculate: Do math<br>    - analyze: Analyze data<br>    - final_answer: Give final answer<br>    <br>    Respond with:<br>    {<br>      &quot;thought&quot;: &quot;your reasoning&quot;,<br>      &quot;action&quot;: &quot;tool_name&quot;, <br>      &quot;input&quot;: &quot;tool_input&quot;<br>    }<br>    <br>    Question: {{question}}<br>  `),<br>  parser: createParser(&quot;json&quot;, {<br>    schema: {<br>      type: &quot;object&quot;,<br>      properties: {<br>        thought: { type: &quot;string&quot; },<br>        action: { type: &quot;string&quot; },<br>        input: { type: &quot;string&quot; },<br>      },<br>    },<br>  }),<br>});<br><br>// This gives you a ReAct-style agent that works with ANY model!</pre><h3>Unveiling the Pattern</h3><p>Function calling isn’t a model capability. It’s a pattern:</p><ol><li><strong>Describe</strong> available tools in your prompt</li><li><strong>Parse</strong> structured output</li><li><strong>Execute</strong> the chosen tool</li><li><strong>Repeat</strong> with results</li></ol><p>Once you see this, you realize:</p><ul><li>You don’t need to wait for providers to add features</li><li>You can build agents that work with ANY model</li><li>You have MORE control than native function calling</li><li>It’s just prompts and parsers all the way down</li></ul><h4><strong>Are there trade-offs?</strong></h4><p>Sure. Native function calling is more polished, they’ve handled edge cases, malformed JSON, and fine-tuned the models. But here’s the crucial point: those are implementation details, not fundamental limitations.</p><p>With llm-exe, you gain:</p><ul><li><strong>Transparency</strong>: See exactly what’s happening</li><li><strong>Flexibility</strong>: Add any field, any logic, any model</li><li><strong>Control</strong>: Your code, your rules, your debugging</li><li><strong>Understanding</strong>: Know the pattern, not just the API</li></ul><p><strong>Try It Yourself: </strong><a href="https://www.npmjs.com/package/llm-exe">npm install llm-exe</a></p><p>Then build your own agent. Add tools that call your actual APIs. Add confidence scores to prevent hallucinations. Build agents that explain their reasoning. Make it work with that local model you’re running.</p><p>You’re not limited by what OpenAI or Anthropic decided to expose in their APIs. You have the same power they do.</p><p>Because at the end of the day, it’s all just prompt engineering.</p><p>Want to see more patterns like this? Check out llm-exe on <a href="https://github.com/gregreindel/llm-exe">GitHub</a> or read the docs <a href="https://llm-exe.com/">here</a>. It’s a TypeScript package that provides simplified components to help you implement and manage the fundamental patterns of AI agent development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=602a2f1b1685" width="1" height="1" alt=""><hr><p><a href="https://medium.com/llm-exe/building-ai-agents-before-function-calling-existed-the-pattern-that-powers-everything-602a2f1b1685">Building AI Agents Before Function Calling Existed: The Pattern That Powers Everything</a> was originally published in <a href="https://medium.com/llm-exe">llm-exe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[llm-exe LLM: Keep Your Code Clean While Switching Models]]></title>
            <link>https://medium.com/llm-exe/llm-exe-intro-llm-2f5f35e60caf?source=rss----3653156bcad7---4</link>
            <guid isPermaLink="false">https://medium.com/p/2f5f35e60caf</guid>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[llm-exe]]></category>
            <category><![CDATA[ai-development]]></category>
            <category><![CDATA[llm-development]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[llm-exe]]></dc:creator>
            <pubDate>Thu, 15 May 2025 02:40:20 GMT</pubDate>
            <atom:updated>2025-05-15T03:14:42.341Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Logo for llm-exe — a TypeScript utility for executing language models, with the text “LLM”." src="https://cdn-images-1.medium.com/max/1024/1*SA6XDJ-0GgM4QGugyONRCg.png" /></figure><p><em>This article is part of a multi-part series on </em><a href="https://llm-exe.com/"><strong><em>llm-exe</em></strong></a><em> — a lightweight toolkit for building composable, reliable functions on top of large language models. Each post dives into a different part of the system: prompts, parsers, executors, and how we use them together.</em></p><p><em>In this one, we’ll be exploring </em><strong><em>prompt</em></strong><em>, what it does, and how to use it effectively inside your own LLM workflows.</em></p><p>If you’ve ever integrated multiple LLM APIs in a TypeScript project, you know the pain: each provider has its own SDK or HTTP quirks, inconsistent naming, and unique edge cases. Who wants to bundle the OpenAI, Anthropic, and other SDKs into one codebase? The llm module from the llm-exe library solves this with a minimal, provider-agnostic interface for calling LLMs — clean, consistent, and built for composability.</p><p>In previous articles, we covered how llm-exe helps you create robust prompt templates and parse model outputs with type safety. Now, we focus on the piece that actually calls the model. The goal: one function to call any model you need. No more copy-pasting slightly different fetch calls or remembering which parameter name a given API expects — llm-exe standardizes it for you.</p><h3>Key Features of the llm Module</h3><ul><li><strong>One API for Every Provider</strong>: Call dozens of models with the same code. The llm module offers a consistent API across providers like OpenAI, Anthropic (Claude), Google (Gemini), Amazon (Bedrock), xAI (Grok), Ollama, DeepSeek, and more. You don’t have to rewrite logic when switching providers — just change one configuration line and you’re good to go.</li><li><strong>Built-In Reliability:</strong> Network hiccups and model overloads happen. The llm calls include <strong>automatic retries and timeouts out of the box</strong>. No need to hand-roll retry loops or worry about hanging requests.</li><li><strong>Composable with Prompts and Parsers:</strong> The design cleanly separates prompt templating, parsing, and the model call. You can use llm by itself for quick tasks, or compose it with prompt and parser modules for more structured workflows. This means you can test each piece independently and swap components easily – a prompt format change doesn’t affect your model-calling code. And if you bundle them into an <strong>executor</strong>, you get end-to-end type safety for inputs and outputs.</li><li><strong>Function Calling and Tools Support:</strong> Need the model to call functions (OpenAI’s plug-ins/tools) or orchestrate multi-step workflows? llm has hooks to support <strong>function calling and tool use</strong> when combined with extended executors. In practice, that means you can define functions the model is allowed to invoke, and llm-exe will handle the extra JSON back-and-forth for you.</li><li><strong>Minimal and Test-Friendly:</strong> Perhaps the best part is what llm <strong>doesn’t</strong> do – there’s no heavy framework or magic. It’s a thin, readable layer that <strong>just handles the model call</strong>, making it easy to reason about and trust. This also makes it <strong>easy to test</strong>. You can swap in a mock LLM to simulate responses. The clean separation means your unit tests don’t have to hit real APIs – you can verify logic in isolation.</li></ul><p>Let’s dive into how you actually use llm in code and how it fits into the larger llm-exe picture.</p><h3>One Unified Interface for Many Models</h3><p>Using the llm module is straightforward. First, you import the useLlm factory from the library. This function creates an LLM client object for a given provider/model. For example, here’s how you might call OpenAI’s GPT-4o-mini model:</p><pre>import { useLlm } from &quot;llm-exe&quot;;</pre><pre>const llm = useLlm(&quot;openai.gpt-4o-mini&quot;);<br>const response = await llm.call(&quot;Hello, world!&quot;);<br>const text = response.getResultText();<br>console.log(text);</pre><p>In the above snippet, we created an llm instance pointing to the &quot;openai.gpt-4o-mini&quot; model and then called it with a simple string prompt. The <strong>same code</strong> would work if we wanted to call, say, Anthropic’s Claude or another provider – we’d just change the model identifier string. No other code changes are required because the rest of the API is uniform.</p><p>Under the hood, useLlm(&quot;openai.gpt-4o-mini&quot;) knows how to reach OpenAI’s API, send the prompt, handle the API key (which you configure via environment or options), and retrieve the result. If we swap that to useLlm(&quot;google.gemini-2.0-flash&quot;) or useLlm(&quot;xai.grok-2&quot;), the call method and response handling remain exactly the same – only the endpoint and payload format change internally. This plug-and-play multi-provider support means you can <strong>prototype on one provider and later switch</strong> to another with minimal fuss. Your business logic doesn’t need a refactor for each LLM service.</p><h3>Provider-Agnostic Model IDs</h3><p>The string you pass to useLlm encapsulates both the provider and the model name, separated by a dot. For instance:</p><ul><li>&quot;openai.gpt-4o-mini&quot; – OpenAI GPT-4o-mini model.</li><li>&quot;anthropic.claude-3-7-sonnet&quot; – Anthropic Claude 3.7.</li><li>&quot;google.gemini-1.5-pro&quot; – Google’s Gemini 1.5 pro model.</li><li>&quot;xai.grok-2&quot; – xAI’s Grok model version 2.</li><li>&quot;ollama.deepseek-r1&quot; – a model served via Ollama (a local model like DeepSeek, Llama, etc).</li></ul><p>The library comes with <strong>shorthand identifiers</strong> for many popular models and versions. But you can also specify a more generic interface plus a model name. For example, you could use the Bedrock (AWS) Anthropic model via:</p><pre>const llm = useLlm(&quot;amazon:anthropic.chat.v1&quot;, { model: &quot;claude-2&quot; });</pre><p>Here, the part before the colon specifies the host/provider (Amazon Bedrock) and the base interface (chat.v1), and then we pass the actual model id (claude-3-sonnet-20240229-v1:0) in the options. This mechanism lets you call providers that host third-party models. Similarly, you have shorthands like &quot;openai.chat.v1&quot;, &quot;anthropic.chat.v1&quot;, &quot;ollama.chat.v1&quot;, etc., which you can configure with any model that provider supports. The key idea is that <strong>any model, from any provider, can be invoked through the same unified interface</strong>. It’s just a matter of choosing the provider and model string.</p><h3>Consistent API with Retries, Timeouts, and Control</h3><p>The llm object returned by useLlm provides a <strong>consistent set of methods</strong> regardless of which model you’re using. The primary method is llm.call(prompt, options?), which sends your prompt (could be a string or a structured chat prompt) to the model and returns a response. The response is a uniform object that abstracts away provider-specific response formats. For example, response.getResultText() will give you the main text content of the model’s answer, no matter if it came from OpenAI’s choices[0].message.content or Anthropic’s completion field. This consistency frees you from writing provider-specific parsing logic.</p><p>Beyond the basics, the module has <strong>resilience features built in</strong>. By default, calls will <strong>automatically retry</strong> on certain failures or timeouts. If a model API is temporarily overloaded or a network glitch occurs, llm-exe can retry the request so your application doesn’t have to handle that logic each time. You can configure how many retries or set a <strong>timeout</strong> to avoid waiting too long for a response. These features mean your code is more robust by default – you get production-friendly behavior without extra work.</p><h3>Standalone Usage vs. Executors with Prompts/Parsers</h3><p>You can use the llm module <strong>on its own</strong> or as part of a higher-level workflow. Using it on its own is great for quick tasks or scripts: you pass in a raw prompt string (or already formatted message array) and get back text. This is essentially a thin wrapper around HTTP calls. It&#39;s convenient, but theres not much structure around it.</p><p>However, llm-exe really shines when you <strong>compose </strong><strong>llm with the </strong><strong>prompt and </strong><strong>parser modules</strong>. In this series, we’ve discussed how prompt helps build prompts with variables, and how parser can convert model output into structured data or validated forms. The llm module cleanly plugs into that architecture. The separation means each lightweight piece can be developed and tested independently. For example, you can unit test that your prompt template produces the correct text given some inputs (ensuring you didn’t forget a variable), without invoking any model. Likewise, you can test your parser logic by feeding it sample outputs. The llm module can be swapped out or mocked in tests without affecting prompt or parser tests, reinforcing this modular design.</p><p>When you’re ready to wire them together, you typically use an <strong>executor</strong>. An executor is essentially a function that ties a prompt + llm + parser into one unit. You provide the llm instance, the prompt template, and the parser, and then call something like createLlmExecutor({ llm, prompt, parser }).execute(inputValues).</p><p>This will:</p><ul><li>format the prompt with inputValues,</li><li>call the model via llm,</li><li>run the parser on the model’s raw output,</li></ul><p>…finally returning a nice structured result.</p><h3>Function Calling and Advanced Hooks</h3><p>Modern LLMs like GPT-4o can do more than return text — they can <strong>call functions or tools</strong> when given the right parameters. The llm module supports these advanced scenarios as well. If you’re using OpenAI’s function calling, you can provide function definitions and let the model decide to invoke them. The llm-exe ecosystem can coordinate this: it will return structured data indicating the function call, and (if you use an executor pattern) you can handle it or even chain to another executor (since llm-exe lets LLMs call other executors too). Essentially, llm isn’t limited to plain text completion; it can facilitate interactive flows where the AI can request actions.</p><p>Similarly, for agent-like behaviors (tool use in answer generation), you might combine llm with custom logic that intercepts certain outputs. In extended executors, you can implement a loop where the model’s output triggers some tool, and then you feed the result back in. The unified interface makes this easier because you don’t have to juggle multiple SDKs – one interface can talk to any model that supports the needed capability.</p><h3>Simple, Composable, and Testable by Design</h3><p>The philosophy behind llm (and llm-exe in general) is to keep things <strong>simple and composable</strong>. The module focuses narrowly on the task of calling an LLM API and getting a result. It’s not generating prompts for you, it’s not attempting to manage complex dialogues on its own, and it’s not dictating how you structure your application. This minimalism makes the code <strong>easy to understand and trust</strong> – if something goes wrong, you can dig into the call logic without wading through a framework’s worth of abstraction.</p><p>This design also makes llm very <strong>testable</strong>. Because the side effects (HTTP calls) are isolated behind the useLlm interface, you can swap in a dummy implementation in your tests. In fact, llm-exe provides a special &quot;openai.mock&quot; provider for exactly this purpose. You can use useLlm(&quot;openai.mock&quot;) to get an LLM that doesn’t call an external service at all. Instead, you can configure it to return predetermined responses, simulate delays, or trigger errors to see how your code handles them. This means your CI tests don’t need actual API keys or internet access to verify your LLM-driven logic.</p><h3>Wrap Up</h3><p>The llm module in llm-exe provides TypeScript developers with a <strong>unified, pragmatic interface to call large language models</strong>. It abstracts away the differences between providers while exposing the controls and hooks you need for real-world applications. We’ve seen how it can call OpenAI, Anthropic, Google, Amazon, xAI, Ollama, or custom models with equal ease, handle retries and timeouts for you, and plug neatly into a larger framework of prompt templates and parsers. It does all this with a minimal footprint and an emphasis on clarity and testability.</p><p>This post is one piece of a series on building with llm-exe. The rest of the series walks through the other core modules, each one designed to work independently but built to fit together.</p><ul><li><a href="https://medium.com/llm-exe/llm-exe-intro-llm-executor-52bb95c76c84"><strong>Executors</strong></a>: Bind model + prompt + parser into a well-typed function.</li><li><a href="https://medium.com/llm-exe/llm-exe-intro-prompt-3d9d40dc923d"><strong>Prompts</strong></a>: Create structured, reusable templates that adapt to your data.</li><li><a href="https://medium.com/llm-exe/llm-exe-intro-parser-aed787f81082"><strong>Parsers</strong></a>: Convert messy LLM output into clean, typed responses.</li><li><strong>LLM</strong>: Choose and configure the models that power it all.</li></ul><p>Want to skip ahead? <a href="https://llm-exe.com/">Read the docs</a>, npm install llm-exe, and <a href="https://github.com/gregreindel/llm-exe">⭐ star the GitHub</a> if you&#39;re into it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f5f35e60caf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/llm-exe/llm-exe-intro-llm-2f5f35e60caf">llm-exe LLM: Keep Your Code Clean While Switching Models</a> was originally published in <a href="https://medium.com/llm-exe">llm-exe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[llm-exe Parser: Parse, Validate, and Structure AI Responses]]></title>
            <link>https://medium.com/llm-exe/llm-exe-intro-parser-aed787f81082?source=rss----3653156bcad7---4</link>
            <guid isPermaLink="false">https://medium.com/p/aed787f81082</guid>
            <category><![CDATA[ai-development]]></category>
            <category><![CDATA[structured-llm-output]]></category>
            <category><![CDATA[llm-exe]]></category>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[llm-exe]]></dc:creator>
            <pubDate>Thu, 15 May 2025 02:40:00 GMT</pubDate>
            <atom:updated>2025-05-15T03:15:21.765Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Logo for llm-exe — a TypeScript utility for executing language models, with the text “Parser”." src="https://cdn-images-1.medium.com/max/1024/1*pNb4XxrqiA2U11o4GmnVZw.png" /></figure><p><em>This article is part of a multi-part series on </em><a href="https://llm-exe.com/"><strong><em>llm-exe</em></strong></a><em> — a lightweight TypeScript toolkit for building composable, reliable functions on top of LLM’s. Each post dives into a different part of the system: prompts, parsers, executors, and how we use them together.</em></p><p><em>In this one, we’ll be exploring </em><strong><em>parser</em></strong><em>, what it does, and how to use it effectively inside your own LLM workflows.</em></p><p>LLMs are great at producing human-like text, but raw text alone isn’t enough for robust applications. llm-exe addresses this by making LLM-powered apps modular, typed, and testable. It divides the workflow into distinct components: prompt templates for structured inputs, LLM executors for model calls, and <strong>parsers</strong> for interpreting outputs, ensuring each aspect is handled independently.</p><p>This article explores the <strong>parser</strong> module, a crucial element that transforms the LLM’s raw string outputs into the structured, typed data your TypeScript application requires.</p><h3><strong>Why LLM Outputs Need Parsing</strong></h3><p>When you call an LLM, the response you get is ultimately just a string of text. You might <em>ask</em> the model to return a number or a JSON object, but the fact is the model’s reply will still be a string that your program must interpret. Backends typically require well-defined data types like arrays, objects, booleans, etc. — not free-form text. This is where the parser module comes in. <strong>Parsers transform raw LLM output into predictable, usable values</strong>, converting the model’s string into structured data that fit your needs. For example, a parser can split a newline-delimited list into an array, parse a JSON-formatted string into a JavaScript object, or even map a textual choice into a specific enum value. In short, parsers align the LLM’s output with your application’s data model, so you’re not left writing brittle string-handling code for every llm interaction.</p><h3><strong>Benefits of </strong><em>llm-exe</em><strong> Parsers</strong></h3><h4><strong>Separation of Concerns</strong></h4><p>A major advantage of using llm-exe parsers is the <strong>clean separation of concerns</strong>. A parser in llm-exe is a self-contained function whose <em>single responsibility</em> is to take a string input and output it as structured data. This means your output parsing logic is completely decoupled from prompt construction and LLM invocation. Such separation makes your code easier to reason about and debug — you can tweak or replace the parsing logic without touching prompt templates or LLM calls. It also makes parsers straightforward to <strong>unit test</strong>: given an example input string, you can verify the parser returns the expected structured result with no need to actually call an LLM. This single-focus design “encourages single responsibility per component” and is easier to test, reason about, and debug.</p><h4>Type Safety</h4><p>Parsers also bring end-to-end type safety to your LLM workflow. In llm-exe, the parser defines the expected output shape, and when you attach it to an LLM executor, it effectively determines the return type of your LLM-powered function. The parser module makes the traditionally unpredictable LLM outputs <strong>safe and predictable</strong> by enforcing a structure. In other words, there’s no guesswork or manual type casting needed — the TypeScript compiler <em>knows</em> the type of data your executor will return, whether it’s a string, a <em>MyData</em> object, or an array of numbers.</p><h4><strong>Extensible</strong> and Customizable</h4><p>llm-exe parsers are designed to be flexible. You can use built-in options like JSON, lists, and code blocks for common formats — or define your own parser when you need custom behavior or domain-specific validation. Either way, your parser plugs directly into the executor and the type system, so everything stays type-safe and consistent. Adding logic for validation or data transformation is just a matter of updating your parser function, allowing you to cleanly enforce app-specific rules before any LLM output reaches your core logic.</p><h3><strong>Built-in Parsers</strong></h3><p>llm-exe comes with a suite of <strong>included parsers</strong> to handle many common patterns out-of-the-box. These built-ins let you quickly impose structure on an LLM’s reply by simply specifying the parser name when building your executor. For example:</p><ul><li><strong><em>json:</em></strong> Parses a string containing JSON into a JavaScript object or array. This is invaluable when you instruct the model to output JSON. The <em>json</em> parser will safely parse the text and even accept minor formatting variations. You can optionally provide a JSON Schema to further validate/enforce the structure and supply default values for missing fields. (The parser is smart enough to handle JSON enclosed in markdown code fences or escaped within a string literal as well.) Using this parser means your LLM function can return a fully-typed object, with the parser guaranteeing the runtime structure matches your TypeScript interface or schema.</li><li><strong><em>listToArray:</em></strong> Converts a newline-separated list of items into an array of strings. This is useful if the LLM responds with bullet points or numbered steps each on separate lines. Internally it simply splits on line breaks and does some minor cleanup, but by using a provided parser you avoid writing that parsing logic yourself and you get type safety (the result is inferred as <em>string[] </em>in TypeScript).</li><li><strong><em>markdownCodeBlock</em></strong> — Extracts a snippet of code from a markdown-formatted response. If the LLM’s answer includes a fenced code block (for example, triple backticks with a language), this parser will pull out the code content and the language label. The output becomes an object like <em>{ code: “…”, language: “typescript” }</em>. This is extremely handy for code-generation prompts — you can ask for an answer in a markdown code block and have the parser neatly give you the code and its language as structured data. There’s also a related parser `markdownCodeBlocks` which will return an array of <em>{code, language}</em> objects if multiple code blocks are present.</li><li><strong><em>stringExtract</em></strong> — Ensures the output is one of a specific set of strings you expect. You provide an <em>enum</em> array of acceptable answers (for example, <em>[“yes”,”no”]</em> or <em>[“red”,”green”,”blue”]</em>), and the parser will look for one of those substrings in the LLM’s response. If it finds a match, it returns <em>exactly</em> that enum string (in normalized form), guaranteeing the result is one of the allowed values. This is great for yes/no/maybe style prompts or any multiple-choice answers — it gives you predictable output (the matching option) and filters out anything extra the model might say. Essentially, <em>stringExtract</em> acts like a validator that the model followed instructions, before your code uses the value.</li></ul><p>There are other included parsers as well, such as <em>listToJson</em> for converting lists of Name: Value pairs into a single JSON object, or <em>replaceTemplateString</em> which uses Handlebars templates to parse out values. You can refer to the <a href="https://llm-exe.com/parser/included-parsers.html">llm-exe documentation</a> for the full list.</p><p>Using a built-in parser is simple. You create it by name and attach it to your executor. Let’s walk through a quick example with <strong><em>listToArray</em></strong> to see it in action:</p><pre>import { createParser, createLlmExecutor, createPrompt, useLlm } from &quot;llm-exe&quot;;<br><br>// Suppose we want an LLM-powered function that lists test cases for a given code snippet.<br>const llm = useLlm(&quot;openai.gpt-4&quot;); // choose an LLM provider/model<br>const prompt = createPrompt(<br>  `You are a testing expert. Given the code below, <br>reply with an unordered list important test cases:`<br>).addUserMessage(&quot;{{code}}&quot;); // we&#39;ll fill in a &#39;code&#39; variable with the code snippet<br><br>const parser = createParser(&quot;listToArray&quot;); // use the built-in listToArray parser<br><br>// Combine into an executor function:<br>export const listTestCases = createLlmExecutor({<br>  llm,<br>  prompt,<br>  parser,<br>});<br><br>// Now, when we execute our function with a code snippet input:<br>const result = await listTestCases.execute({ code: sampleCodeString });<br><br>// result will be a string[] (array of test case descriptions)</pre><p>In this example, we didn’t have to manually process the LLM’s output. We know <em>listToArray</em> will take whatever the model returns (say, a bullet list of test case ideas) and give us back a clean JavaScript array of strings. The <em>result</em> variable is automatically typed as <em>string[]</em> by the compiler, thanks to the parser’s type definition. This way, our application logic can immediately work with an array of test case descriptions, rather than a single big string that we’d have to split or regex ourselves.</p><h3><strong>Creating Custom Parsers</strong></h3><p>Built-in parsers cover a lot, but inevitably you’ll encounter a situation where the output format is unique or you want to do some custom post-processing. The good news is <strong>llm-exe lets you define your own parser functions easily</strong>. A custom parser is essentially just a function that takes the raw string (and its also passed the execution context) and returns whatever structured data you want. Under the hood, <em>llm-exe</em> provides a helper to wrap your function into a Parser object.</p><p>To create a custom parser, you’ll use the <em>createCustomParser</em> factory. It accepts a name (for debugging/introspection) and your parsing function. The function signature is typically <em>(input: string, values: Record&lt;string, any&gt;) =&gt; OutputType</em>. The <em>input</em> is the raw LLM response string, and <em>values</em> are the original input values passed to the executor (in case your parsing needs to know something about the prompt inputs; often you won’t need this). You then implement whatever logic is needed to transform the string into <em>OutputType</em>. You can throw an error or return a default if <em>something</em> isn’t what you expect.</p><p><strong>Example:</strong> Imagine we have an LLM that is instructed to return a year as text and we want to parse it into a number. We can write a custom parser to ensure we get a numeric type:</p><pre>import { createCustomParser } from &quot;llm-exe&quot;;<br><br>function parseYear(input: string): number | null {<br>  const match = input.match(/\b(19|20)\d{2}\b/); // matches years 1900–2099<br>  if (match) {<br>    return parseInt(match[0], 10);<br>  }<br><br>  // fallback: try to parse the whole input if it&#39;s just a number<br>  const fallback = parseInt(input.trim(), 10);<br>  if (!isNaN(fallback) &amp;&amp; fallback &gt;= 1000 &amp;&amp; fallback &lt;= 2100) {<br>    return fallback;<br>  }<br><br>  return null;<br>}<br><br>// Custom parser: extract a year or return null<br>export const YearParser = createCustomParser&lt;number | null&gt;(<br>  &quot;YearParser&quot;,<br>  (input, _context) =&gt; parseYear(input)<br>);</pre><p>Here, <em>YearParser</em> is our new parser. It will attempt to convert the LLM’s output string to a JavaScript <em>number</em> (e.g. turning ”2025\n” into <em>2025</em>). The parser logic also guards against minor common issues like if the LLM responds with “the year is 2025”. If we cant extract a valid year, we return null — which means if the model gave an unexpected answer, and you’ll know the output didn’t meet the contract. We specified the generic <em>&lt;number&gt;</em> when calling <em>createCustomParser</em> to make the expected return type explicit, but often you don’t even need to — TypeScript can infer it from the function’s return type if the function is well-typed. As long as you define your parser function with proper types, <em>llm-exe</em> will flow those types through, so the rest of your code “knows” what type to expect from the LLM executor.</p><p>Using a custom parser is just like using a built-in. You can call <em>myCustomParser.parse(llmOutput)</em> directly if you want, but more commonly you pass the parser into an executor. For example:</p><pre>const myExecutor = createLlmExecutor({<br>  llm: useLlm(&quot;openai.gpt-4o-mini&quot;),<br>  prompt: createPrompt(&quot;What year was the moon landing?&quot;),<br>  parser: YearParser,<br>});<br><br>const answer = await myExecutor.execute({});<br>// answer is a number (e.g., 1969) <br>// because YearParser ensures the output is parsed to a number</pre><p>By plugging in YearParser, our myExecutor function becomes more resilient. If the model responds with a plain year like “1969”, the parser converts it directly to a number. If the answer is embedded in a sentence — like “It happened in 1969.” — the parser extracts the year. This flexibility helps absorb natural language noise without losing type safety. If the model returns something unusable (e.g. “sometime long ago”), the parser returns null, allowing us to detect and handle the failure explicitly. The executor’s output remains predictable: it’s always a number or null, and downstream code can rely on that.</p><p>Writing custom parsers gives you full control over output handling. You can strip unwanted text, handle subtle formatting inconsistencies, <strong>or even</strong> <strong>combine multiple pieces of the LLM output into one structured return</strong>. In more advanced scenarios, you might use a custom parser to post-process a JSON output (perhaps filtering or enhancing the parsed data) or to implement domain-specific parsing logic (for instance, parsing a chat conversation and extracting a particular field). The llm-exe approach lets you encapsulate all that in a dedicated parser function, keeping your main logic clean. And because the parser is a pure function, it’s easy to test it with sample outputs in isolation. This means you can simulate various model responses (including edge cases) and verify your parser handles them, without having to actually call the model during tests — a big win for reliability.</p><h4><strong>Parsers and Executors: Ensuring Type-Safe LLM Functions</strong></h4><p>It’s worth underscoring how parsers integrate with <em>llm-exe</em> executors to deliver type safety. In llm-exe, an “LLM function” (often created via <em>createLlmExecutor</em>) is defined by three things: an LLM backend, a prompt template, and a parser for the output. Once you have these, llm-exe can wire them together into a function that you call with some input and which returns a result. The <strong>parser’s type essentially becomes the function’s return type</strong>. For example, if you use a parser that outputs <em>string[]</em>, the executor function will be typed to return a <em>Promise&lt;string[]&gt;</em>. If you use a parser that outputs <em>{ passed: boolean, results: Item[] }</em>, your function’s return type will be <em>Promise&lt;{ passed: boolean; results: Item[] }&gt; </em>— and you’ll get full autocomplete and compile-time checks on that structure throughout your code.</p><p>This design turns what is normally a runtime concern (parsing a model’s text response) into a compile-time contract. It’s the parser that dictates, “I will produce data of type T,” and the rest of the system honors that. When you combine a prompt, an LLM, and a parser into an executor, llm-exe “shapes” the executor’s output type based on the parser. You can think of it like defining a regular function’s return type — except here the implementation of that function happens to involve an AI model call. The parser gives you confidence that <em>if</em> the model’s output can be parsed, it <strong>will conform to the structure you expect</strong>. And if it can’t be parsed, you’ll know (via errors or validations) rather than silently getting unpredictable data. This is especially important in production scenarios: your code can proceed assuming a certain response shape, because the parser module has enforced that shape.</p><h3><strong>Conclusion</strong></h3><p>The parser module in llm-exe is all about turning the unstructured into the structured. By isolating output parsing into its own module, llm-exe gives developers a powerful toolkit to handle LLM responses in a <strong>flexible</strong>, <strong>type-safe</strong>, and <strong>maintainable</strong> way. You get a library of ready-made parsers for common tasks and the ability to craft your own for novel ones, all while enjoying TypeScript’s compile-time guarantees on the shape of your data. Parsers define the return type of your LLM functions, enable full static type inference, and encourage a clear separation of concerns in your codebase. The result is LLM-driven components that are as reliable and testable as any other function in your application.</p><p>In the broader scope of the llm-exe framework, the parser module works in concert with other parts (like the prompt module that structures inputs, and the executor that orchestrates the call) to create a <strong>modular</strong> pipeline. Each piece — prompt, LLM, parser — can be developed and tested independently, then plugged together. This modularity means you can upgrade or change one part (say, swap out a model or tweak a format) without breaking the others.</p><p>llm-exe’s parser module takes the guesswork and fragility out of handling AI outputs. It empowers you to <strong>treat LLM responses as just another data source</strong> — one that can be trusted, validated, and cleanly integrated into your system.</p><p>This post is one piece of a series on building with llm-exe. The rest of the series walks through the other core modules, each one designed to work independently but built to fit together.</p><ul><li><a href="https://medium.com/llm-exe/llm-exe-intro-llm-executor-52bb95c76c84"><strong>Executors</strong></a>: Bind model + prompt + parser into a well-typed function.</li><li><a href="https://medium.com/llm-exe/llm-exe-intro-prompt-3d9d40dc923d"><strong>Prompts</strong></a>: Create structured, reusable templates that adapt to your data.</li><li><strong>Parsers</strong>: Convert messy LLM output into clean, typed responses.</li><li><a href="https://medium.com/llm-exe/llm-exe-intro-llm-2f5f35e60caf"><strong>LLM</strong></a>: Choose and configure the models that power it all.</li></ul><p>Want to skip ahead? <a href="https://llm-exe.com/">Read the docs</a>, npm install llm-exe, and <a href="https://github.com/gregreindel/llm-exe">⭐ star the GitHub</a> if you&#39;re into it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aed787f81082" width="1" height="1" alt=""><hr><p><a href="https://medium.com/llm-exe/llm-exe-intro-parser-aed787f81082">llm-exe Parser: Parse, Validate, and Structure AI Responses</a> was originally published in <a href="https://medium.com/llm-exe">llm-exe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[llm-exe Executor: Prompt, Parse, and Execute with Type Safety]]></title>
            <link>https://medium.com/llm-exe/llm-exe-intro-llm-executor-52bb95c76c84?source=rss----3653156bcad7---4</link>
            <guid isPermaLink="false">https://medium.com/p/52bb95c76c84</guid>
            <category><![CDATA[llm-exe]]></category>
            <category><![CDATA[ai-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[structured-llm-output]]></category>
            <dc:creator><![CDATA[llm-exe]]></dc:creator>
            <pubDate>Thu, 15 May 2025 02:37:46 GMT</pubDate>
            <atom:updated>2025-05-15T03:13:47.797Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fvXtGrwMmVgDm9cZEN4FbA.png" /></figure><p><em>This article is part of a multi-part series on </em><a href="https://llm-exe.com/"><strong><em>llm-exe</em></strong></a><em> — a lightweight TypeScript toolkit for building composable, reliable functions on top of large language models. Each post dives into a different part of the system: prompts, parsers, executors, and how we use them together.</em></p><p><em>In this one, we’ll be exploring </em><strong><em>llm-executor</em></strong><em>, what it does, and how to use it effectively inside your own LLM workflows.</em></p><p>Working with LLMs in real applications means more than just sending a prompt and getting a response. You’re formatting strings by hand, dealing with multiple SDKs, parsing unpredictable output, validating structures, casting types, and handling failures. It’s repetitive, fragile, and difficult to test or maintain.</p><p>The <strong>LLM Executor</strong> in llm-exe changes that. It wraps a prompt, a model, and a parser into a single, callable TypeScript function — fully typed, easy to reason about, and ready for production. You pass in a typed input object and get back a structured result. No brittle glue code. No guesswork.</p><p>Each part — the prompt template, the model call, the output parser — stays isolated and swappable. You can change one without rewriting the others. Executors can be composed into pipelines. They support hooks for logging, retries, and custom logic. And everything is type-checked end-to-end, so you catch issues early.</p><p>In this article, we’ll explore what the executor does, how it works, and how it can make your AI code as clean and reliable as any other part of your stack.</p><h4><strong>What Is an LLM Executor?</strong></h4><p>The LLM Executor is a high-level <strong>abstraction that connects your prompt, the LLM, and an output parser in one place</strong>; giving you back a callable, typed function. Each Executor encapsulates a single LLM interaction, fully defined by its inputs and outputs. You define:</p><p><strong>Prompt:</strong> a text or chat prompt template (with support for Handlebars {{variables}}) describing the task or question.</p><p><strong>LLM:</strong> the model or API to use (OpenAI, Anthropic, etc. via a unified interface).</p><p><strong>Parser:</strong> to interpret and validate the LLM’s text output into a typed result (could be plain text, JSON, lists, or custom logic).</p><p>With these, the executor generates a <strong>well-typed function</strong> that runs the prompt with your input, calls the LLM (handling details like retries or streaming under the hood), then parses the result into a <strong>structured, typed output</strong>. In simpler terms, an LLM Executor turns a prompt + model into a <strong>callable function</strong> — you pass in a typed input object and get back a typed result, without any manual string manipulation or type guessing.</p><h4><strong>Why Use the LLM Executor?</strong></h4><p>Using an LLM directly often involves lots of boilerplate: formatting prompts, calling different SDKs, and writing code to parse model responses. The LLM Executor eliminates that boilerplate.</p><p><strong>Turns LLM Calls into Real Functions:</strong> Invoke an AI as if it were a normal function. <em>Pass in one input object, get back a typed result</em> — no tricky code or manual formatting in between. For example, provide a JSON or form object as input, and receive a clean JavaScript object as output.</p><p><strong>Type-Safe from Start to Finish:</strong> All inputs and outputs are fully <strong>typed</strong> and inferred from your prompt and parser definitions. This means no <em>any</em> types, no casting, and no guessing if the model returned what you expected. If your prompt expects a field <em>name: string</em>, the executor won’t even run unless you pass a proper <em>{ name: “…” }</em>. And if your parser is expecting a list of strings, the output will be exactly a <em>string[]</em> — catch errors early and avoid runtime surprises.</p><p><strong>Isolated, Swappable Components:</strong> The prompt template, LLM provider, and parser are kept decoupled under the executor. You can tweak or swap any one of them (try a different prompt wording, switch from GPT-4 to another model, or change the output format) <em>*without rewriting code*</em>. This modularity makes iteration and experimentation much easier.</p><p><strong>Extensible with Hooks:</strong> The executor supports hooks for logging and customization. You can attach <em>onSuccess</em>, <em>onError</em>, or <em>onComplete</em> handlers to tap into execution events — perfect for adding telemetry, caching, or custom side effects around LLM calls, all without cluttering your core logic.</p><p><strong>Composable and Reusable:</strong> Since each executor is just a function, you can <strong>compose multiple LLM calls into pipelines</strong> easily. One executor’s output can feed into another’s input, or you can call LLM executors from within other functions. This encourages small, focused LLM-powered units of logic that are easy to test and maintain.</p><p><strong>Built-In and Custom Parsers:</strong> The executor works with a variety of parsers — use out-of-the-box ones for common formats (plaintext, JSON, lists, etc.) or plug in a <strong>custom parser</strong> to handle domain-specific output. Either way, the output type is validated and <strong>fully inferred</strong> by TypeScript, so you know exactly what you’re getting.</p><p><strong>Multi-Provider Support:</strong> Under the hood, `llm-exe` lets you call LLMs from different providers (OpenAI, Anthropic, Google, etc.) through one interface. The executor doesn’t care which provider you use — you can swap out the `llm` backend with one line of code and everything else stays the same.</p><p>In short, the LLM Executor <strong>bundles prompt, model, and parser into one well-defined, type-safe function</strong>. This dramatically reduces unnecessary code, prevents a whole class of bugs, and makes your AI integration feel like a natural part of your codebase.</p><h4><strong>Example 1: A Friendly Introduction</strong></h4><p>Let’s see the LLM Executor in action with a simple example. Suppose we want an AI function that introduces itself to a user by name. We’ll create an executor that greets the user and identifies the model or company it’s representing, based on an input name. With `llm-exe`, we can do this in just a few lines:</p><pre>import {<br>  useLlm,<br>  createChatPrompt,<br>  createParser,<br>  createLlmExecutor,<br>} from &quot;llm-exe&quot;;<br><br>async function doIntroduction&lt;I extends { name: string }&gt;(input: I) {<br>  // 1. Define the prompt template with a placeholder for the name<br>  const instruction = `Hello LLM! I&#39;m {{ name }}. <br>I’m doing a test, so greet me back by name and identify <br>yourself by company or model name.`;<br><br>  const prompt = createChatPrompt&lt;I&gt;(instruction);<br><br>  // 2. Select the LLM to use (OpenAI GPT-4 in this case)<br>  const llm = useLlm(&quot;openai.gpt-4o-mini&quot;);<br><br>  // 3. Choose a parser for the output (plain string here)<br>  const parser = createParser(&quot;string&quot;);<br><br>  // 4. Create the LLM executor that ties it all together<br>  const executor = createLlmExecutor({ llm, prompt, parser });<br><br>  // 5. Execute the LLM call with the input data and return the result<br>  return executor.execute(input);<br>}<br><br>  // Usage:<br>  const result = await doIntroduction({ name: &quot;Alice&quot; });<br>  console.log(result);</pre><p>Let’s break down what’s happening here:</p><ul><li><strong>Prompt with Template:</strong> We wrote an instruction string that uses {{ name }} as a placeholder. By passing that string into createChatPrompt&lt;I&gt;, we get a prompt object that knows it requires a { name: string } input. This is <strong>statically checked</strong> – if we forget to supply name later, TypeScript will complain.</li><li><strong>LLM Selection:</strong> useLlm(&quot;openai.gpt-4o-mini&quot;) picks a model. We could swap &quot;openai.gpt-4o-mini&quot; with &quot;anthropic.claude-instant&quot; or any supported provider/model, and our function logic wouldn’t need to change.</li><li><strong>Parser:</strong> We use a simple &quot;string&quot; parser which means &quot;just return the raw text response as a string.&quot; If we expected a more complex output (say JSON), we could use createParser(&quot;json&quot;) to automatically validate and parse JSON output, or define a custom parser function. The <strong>parser defines the return type</strong> – here it’s string, so doIntroduction will return a Promise&lt;string&gt;.</li><li><strong>Executor Creation:</strong> createLlmExecutor({ llm, prompt, parser }) glues the prompt, LLM, and parser together into an <strong>executor object</strong>. This object has an async .execute() method that takes the input (in our case an object with name) and handles the whole sequence: injecting name into the prompt template, calling the model, and then running the parser on the result. Because we created the prompt with type I extends { name: string } and the parser as &quot;string&quot;, the executor’s TypeScript definition becomes (input: { name: string }) =&gt; Promise&lt;string&gt;. In other words, <strong>a type-safe function from </strong><strong>{ name: string } to </strong><strong>string</strong>.</li><li><strong>Execution:</strong> Finally, calling executor.execute({ name: &quot;Alice&quot; }) sends our prompt to the LLM and returns the parsed result. No manual HTTP calls or JSON parsing on our part – just a clean function call. For example, the AI might reply with: <em>&quot;Hello Alice! This is GPT-4 at OpenAI, pleased to meet you.&quot;</em>, and that string is exactly what result will contain.</li></ul><p>Notice how <strong>concise</strong> this is compared to the traditional approach. We didn’t have to assemble a prompt string with string concatenation or manually parse the AI’s response. The separation of concerns is clear: the prompt handles text, the LLM call is abstracted by useLlm, and the parser guarantees we get the right type out. The executor ties them together so we can simply call doIntroduction() like any other async function. <strong>No type casting, no guesswork.</strong></p><h3>Example 2: Structured Output with a List Parser</h3><p>For a second example, let’s build an AI function that returns a list of items. Say we want to ask the model: <em>“What are your top N favorite colors?”</em> and get back an array of color names. We’ll use a parser that turns a Markdown list into a JavaScript array for easy consumption in our code.</p><pre>async function getFavoriteColors&lt;I extends { count: number }&gt;(input: I) {<br>  const instruction = `Reply with an unordered list of your top {{count}} favorite colors.`;<br>  const executor = createLlmExecutor({<br>    llm: useLlm(&quot;openai.gpt-4o-mini&quot;),<br>    prompt: createChatPrompt&lt;I&gt;(instruction),<br>    parser: createParser(&quot;listToArray&quot;),<br>  });<br>  return executor.execute(input);<br>}<br><br>// Usage:<br>const colors = await getFavoriteColors({ count: 3 });<br>console.log(colors);</pre><p>Here, the prompt uses {{count}} to ask for a variable number of favorite colors, and we chose the &quot;listToArray&quot; parser – a built-in parser that will convert a markdown bullet list into a JavaScript array of strings. Thanks to that parser, the return type of getFavoriteColors is inferred as Promise&lt;string[]&gt;. In code, colors might come out as, for example:</p><pre>[&quot;Blue&quot;, &quot;Green&quot;, &quot;Red&quot;];</pre><figure><img alt="TypeScript function call to getFavoriteColors({ count: 3 }), with type hint showing it accepts an object with count: number and returns a Promise&lt;string[]&gt;." src="https://cdn-images-1.medium.com/max/822/1*j12jyklDmJBgNUGsm35_MA.jpeg" /><figcaption>The prompt and parser types infer the input and output types, respectively</figcaption></figure><p>Each step remains type-safe. If the model returns something that doesn’t fit the expected list format, the parser would throw an error or reject the promise, alerting you to the mismatch. In development, this is invaluable: it’s easier to catch prompt or output format issues early, and you can adjust either the prompt or parser accordingly.</p><figure><img alt="TypeScript error: argument { count: [3] } is invalid — number[] is not assignable to expected type count: number." src="https://cdn-images-1.medium.com/max/1024/1*jJS057U6CKlB0H1AmZIYqQ.jpeg" /><figcaption>The input is well-typed based on the prompt — this typing extends to the executor</figcaption></figure><p>This example also showcases how easy it is to <strong>switch output formats</strong>. If we wanted the colors in a single comma-separated string instead, we could use a different parser (or no parser, and just get a raw string). If we wanted a more structured object, we could prompt the LLM to output JSON and use the JSON parser. The executor makes these changes trivial — you adjust one line and your function’s output type updates automatically.</p><h3>Hooks, Logging, and Extensibility</h3><p>In a real application, you often need more than just a raw function call — you might want to log the prompt and response, handle errors centrally, or measure execution time. The LLM Executor provides <strong>hooks</strong> and an event emitter interface to support these scenarios:</p><ul><li><strong>Hooks on Creation:</strong> You can pass a second argument to createLlmExecutor with hook callbacks. For example:</li></ul><pre>const hooks = {<br>  onComplete: (res, metadata) =&gt; {<br>    console.log(&quot;LLM call completed&quot;, metadata);<br>  },<br>  onSuccess: (res) =&gt; {<br>    /* handle success */<br>  },<br>  onError: (err) =&gt; {<br>    /* handle error */<br>  },<br>};<br>const executor = createLlmExecutor({ llm, prompt, parser }, hooks);</pre><p>These hooks (onComplete, onSuccess, onError) will be invoked at appropriate times during execution, allowing you to plug in logging, analytics, or custom behaviors whenever the executor runs. For instance, you could record model usage or modify the raw output before parsing.</p><ul><li><strong>Event Emitters:</strong> The executor instance is also an event emitter. You can attach listeners with executor.on(&quot;onComplete&quot;, ...) or one-time listeners with executor.once(...). This gives another way to decouple side-effect logic from the core execution. It’s especially handy if you want to monitor or decorate the executor’s behavior from outside (for example, in a testing framework or a higher-level orchestration layer).</li></ul><p>These extensibility points mean you’re not boxed into a black box call — you have <strong>full visibility and control</strong> if you need it. Yet, if you don’t need any custom handling, you can simply ignore hooks and treat the executor like a pure function. This design lets you start simple and add complexity only as required, keeping your codebase clean.</p><h3>Composing and Testing LLM Functions</h3><p>Because each LLM Executor is essentially a self-contained function, you can <strong>compose them together</strong> to build more complex workflows. For example, you might have one executor that extracts some info from text, and another that uses that info in a follow-up question. Composing them is as simple as calling one inside the other or in sequence, just like you would with normal functions. The ability to easily chain AI calls (or even have an AI function call another AI function) opens up powerful patterns, all while each step remains clear and testable.</p><p><strong>Testing</strong> LLM-powered code is notoriously tricky, but the structure that llm-exe encourages makes it easier. Since the prompt logic and parsing logic are separated, you can unit test your prompt formatting functions or parser functions in isolation. You can even mock the LLM call by substituting a dummy llm instance (for example, one that returns a canned response) and then test the executor’s behavior deterministically. And thanks to TypeScript, if you ever change the prompt template or output format, the compiler will nudge you to update your types accordingly. This all translates to fewer bugs in production.</p><h3>Recap: Strongly-Typed, Minimal Overhead</h3><p>The LLM Executor transforms the way you integrate AI into your TypeScript applications:</p><ul><li><strong>Prompt in, typed output out.</strong> Define what you want (prompt + desired output structure) and let the executor handle the rest. Your AI calls become few-liners instead of sprawling logic.</li><li><strong>Strongly-typed contracts:</strong> The inputs and outputs of your AI functions are enforced by the compiler. This <strong>prevents mismatch errors</strong> and documentation drift, and it gives you auto-complete hints on the input object.</li><li><strong>Modular design:</strong> Prompt, model, and parser logic stay isolated and reusable. You can maintain each piece separately or swap out components with minimal impact.</li><li><strong>Better reliability and testing:</strong> With built-in validation (through parsers) and hook points for monitoring, you gain confidence in your AI interactions. It’s straightforward to test each part or simulate calls, leading to more reliable applications.</li><li><strong>Scalability and composability:</strong> Build complex behaviors by composing simple LLM-powered functions. As your project grows, this approach scales far better than giant monolithic prompts or deeply nested if/then parsing code.</li></ul><p>In essence, the LLM Executor lets you <strong>treat AI calls as first-class functions in your codebase</strong>, bringing the benefits of clean code and type safety to the world of LLMs.</p><p><strong>Try it out</strong>: Refactor one of your existing LLM-powered-functions to use an LLM Executor, or start a new project with a fresh approach. Once you see the reduction in boilerplate and the improvement in clarity, you might not want to go back. By harnessing the LLM Executor, you can build smarter applications <strong>faster, with fewer bugs</strong>, and have confidence that your AI calls are as dependable as any other function in your code.</p><p>This post is one piece of a series on building with llm-exe. The rest of the series walks through the other core modules, each one designed to work independently but built to fit together.</p><ul><li><strong>Executors</strong>: Bind model + prompt + parser into a well-typed function.</li><li><a href="https://medium.com/llm-exe/llm-exe-intro-prompt-3d9d40dc923d"><strong>Prompts</strong></a>: Create structured, reusable templates that adapt to your data.</li><li><a href="https://medium.com/llm-exe/llm-exe-intro-parser-aed787f81082"><strong>Parsers</strong></a>: Convert messy LLM output into clean, typed responses.</li><li><a href="https://medium.com/llm-exe/llm-exe-intro-llm-2f5f35e60caf"><strong>LLM</strong></a>: Choose and configure the models that power it all.</li></ul><p>Want to skip ahead? <a href="https://llm-exe.com/">Read the docs</a>, npm install llm-exe, and <a href="https://github.com/gregreindel/llm-exe">⭐ star the GitHub</a> if you&#39;re into it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52bb95c76c84" width="1" height="1" alt=""><hr><p><a href="https://medium.com/llm-exe/llm-exe-intro-llm-executor-52bb95c76c84">llm-exe Executor: Prompt, Parse, and Execute with Type Safety</a> was originally published in <a href="https://medium.com/llm-exe">llm-exe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[llm-exe Prompt: Create Typed, Modular Prompt Templates in TypeScript]]></title>
            <link>https://medium.com/llm-exe/llm-exe-intro-prompt-3d9d40dc923d?source=rss----3653156bcad7---4</link>
            <guid isPermaLink="false">https://medium.com/p/3d9d40dc923d</guid>
            <category><![CDATA[llm-prompt-engineering]]></category>
            <category><![CDATA[ai-development]]></category>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[llm-exe]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[llm-exe]]></dc:creator>
            <pubDate>Thu, 15 May 2025 02:29:41 GMT</pubDate>
            <atom:updated>2026-05-19T23:58:40.331Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Logo for llm-exe — a TypeScript utility for executing language models, with the text “Prompt”." src="https://cdn-images-1.medium.com/max/1024/1*dS2JYhFHRzopDo5x-qPT5Q.png" /></figure><p><em>This article is part of a multi-part series on </em><a href="https://llm-exe.com/"><strong><em>llm-exe</em></strong></a><em> — a lightweight TypeScript toolkit for building composable, reliable functions on top of large language models. Each post dives into a different part of the system: prompts, parsers, executors, and how we use them together.</em></p><p><em>In this one, we’ll be exploring </em><strong><em>prompt</em></strong><em>, what it does, and how to use it effectively inside your own LLM workflows.</em></p><p>Prompt design is at the heart of most LLM-powered features, but hardcoding prompts as string literals can make your code fragile and hard to maintain. One missing variable or subtle formatting bug can break things in unpredictable ways. llm-exe is a TypeScript toolkit that helps you <strong>write better prompts —</strong> <strong>ones that are reusable, type-safe, and easy to plug into multi-turn conversations</strong>. In this article, we’ll walk through the llm-exe prompt module: why it exists, how it works, and how features like conditionals, loops, and partials help keep your AI logic clean and reliable. By the end, you’ll see how separating prompt logic from business logic can lead to simpler, more maintainable applications.</p><h3><strong>Why Use the prompt Module?</strong></h3><p>Crafting prompts with plain strings or template literals often results in <strong>messy, error-prone code.</strong> Common problems include:</p><ul><li><strong>Mixing logic with prompt text:</strong> With raw strings, you might dynamically construct prompts in code, intertwining business logic with prompt wording. This makes both harder to read and test. The llm-exe prompt treats prompts as pure templates, keeping presentation separate from code, so you can manage and even store prompts independently. In other words, you define the prompt structure once, and fill in data later, keeping your business logic out of string construction and allowing prompts to be tested in isolation.</li><li><strong>No input validation or type safety:</strong> Standard string templates don’t tell you if you’ve forgotten to supply a variable or if a value is of the wrong type — you’ll only find out when the LLM produces a weird response (or none at all). In llm-exe, prompts can be <strong>strongly typed</strong>. You declare what variables a prompt expects, and the TypeScript compiler <em>and</em> runtime will catch mistakes early. You get autocompletion for prompt inputs and errors if required data is missing, which is impossible with raw strings or basic JS templates.</li><li><strong>Repetitive prompt text and logic:</strong> Without a good templating system, you’ll end up duplicating chunks of prompts across your app (for example, the same instructions or formatting hints in multiple places). The prompt module makes prompts <strong>composable and DRY</strong>. It allows <em>partials</em> (reusable template snippets) and helpers so you can factor out common pieces like disclaimers or example formatting. You can also use conditionals and loops directly in your prompt template to handle variations, instead of writing complex string-building code for each case. This means no more copy-pasting large prompt strings — you adapt to different inputs with zero duplication.</li><li><strong>Managing multi-turn conversations manually:</strong> Language model interactions often involve a dialogue (system instructions, user queries, assistant replies, etc.). Handling this with raw strings is cumbersome. You have to manually label roles or concatenate a conversation history. The llm-exe prompt module is <em>purpose-built for multi-role chat</em>. It natively distinguishes between system, user, and assistant messages and makes it easy to build a prompt that includes the full dialogue history. This ensures the model sees the complete context (instructions + previous messages) so it can reason accurately, without you stitching strings together ad-hoc.</li></ul><p>By addressing these issues, the prompt module enables clearer prompt design and more robust LLM applications. Next, let’s look at how you actually use it.</p><h3><strong>Core API: Building Multi-Role Prompts</strong></h3><p>The <em>prompt</em> module provides a simple, fluent API to construct a chat prompt message-by-message. At the heart is the <em>createChatPrompt</em> function, which initializes a new prompt. You can optionally give it an initial system instruction string (this will become the first message with role “system”). Then, use methods like <em>addUserMessage</em>, <em>addSystemMessage</em>, and <em>addAssistantMessage</em> to append messages of various roles. Each call adds a structured message (with a role and content) to the prompt’s internal list.</p><p>For example, here’s how we can build a prompt with a system instruction, a user question, and even a hypothetical assistant reply from prior context:</p><pre>import { createChatPrompt } from &quot;llm-exe&quot;;<br><br>const prompt = createChatPrompt(&quot;You are a helpful assistant.&quot;);<br>prompt.addUserMessage(&quot;Hello there!&quot;);<br>prompt.addAssistantMessage(&quot;Hi! How can I help you today?&quot;);<br><br>console.log(prompt.messages);</pre><p>The <em>prompt.messages</em> array now contains three messages with their roles, ready to be sent to an LLM:</p><pre>[<br>  { &quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful assistant.&quot; },<br>  { &quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Hello there!&quot; },<br>  { &quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: &quot;Hi! How can I help you today?&quot; }<br>]</pre><p>As shown above, you don’t have to manually tag or format the conversation, each message and role is tracked for you. This internal structure aligns with how most chat models expect input.</p><p>The API methods for building prompts are straightforward:</p><ul><li><strong>addUserMessage(content: string)</strong></li><li><strong>addAssistantMessage(content: string)</strong></li><li><strong>addSystemMessage(content: string)</strong></li><li><strong>addToPrompt(content: string, role: string)</strong></li><li><strong>addFromHistory(messages: Array&lt;{ role: string, content: string }&gt; )</strong></li></ul><p>These can be called in any order and even chained for convenience.</p><p>In addition to adding messages, the prompt object provides a crucial method to finalize your prompt:</p><ul><li><strong>format(data: Record&lt;string, any&gt;): string</strong></li></ul><h3><strong>Type Safety and Input Validation</strong></h3><p>One of the standout features of llm-exe’s prompt module is its embrace of <strong>TypeScript’s type safety</strong> to catch errors early. When creating a prompt, you can parametrize it with a type that represents the expected input variables for that prompt. For example, if your prompt template uses a variable <em>{{name}}</em>, you can specify that the prompt expects an object with a <em>name: string</em> property:</p><pre>const prompt = createChatPrompt&lt;{ name: string }&gt;(&quot;User&#39;s name is: {{ name }}&quot;);<br>// ... add messages, etc. ...<br>prompt.format({ name: &quot;Alice&quot; }); // OK, provides the required variable<br>prompt.format({}); // ❌ Type error: property &#39;name&#39; is missing</pre><p>In the snippet above, the second <em>format</em> call will be flagged by TypeScript because we didn’t provide the required <em>name</em>. This is incredibly powerful — it turns what would have been a runtime error (or a badly formatted prompt) into a compile-time error that you can fix before running your code. You also get IDE autocompletion on the keys of the <em>data</em> object you pass to <em>format()</em>, since the prompt knows its expected structure.</p><figure><img alt="TypeScript error message showing a type mismatch: an empty object {} is not assignable to a parameter of type { name: string } in a call to prompt.format({})." src="https://cdn-images-1.medium.com/max/1024/1*mIqjASBaBw3BSK7pQouepA.png" /><figcaption>The format call is flagged by TypeScript because we didn’t provide the required <em>name</em></figcaption></figure><p>This level of validation and type-checking is <strong>impossible with raw string prompts or basic template literals</strong>. In dynamic languages or untyped templates, forgetting a variable or misnaming a placeholder would only show up when the model generates an unexpected answer (or crashes). With llm-exe, by contrast, you’re alerted immediately.</p><h3><strong>Advanced Templating with Handlebars: Conditionals, Loops, and Partials</strong></h3><p>Under the hood, llm-exe uses <strong>Handlebars</strong> as its templating engine for prompts. This is a deliberate choice that brings a lot of power: you can include not just variables in your prompt, but also logic like conditionals and loops directly within the prompt text. The result is that your prompt definitions can handle complex scenarios <em>declaratively</em>, without resorting to imperative string building in code.</p><p><strong>Using variables</strong> is straightforward: any <em>{{variable}}</em> in the prompt will be replaced by the corresponding value from the object you pass to<em> format()</em>. You can even access object properties (e.g. <em>{{user.name}}</em>) and iterate or conditionally render based on data.</p><p>For example, suppose you’re writing a prompt for a travel agent chatbot that can handle different request types (car rental vs hotel booking) and wants to personalize based on the user’s past rentals. You could define a prompt template like this:</p><pre>// Define a partial for the car rental questionnaire<br>const carTemplate = `The user ({{userName}}) wants to rent a car.<br>Ask the user:<br>- The year, make, and model of the car they&#39;d like to rent.<br>- Whether they&#39;d prefer something similar to a past rental or something new.<br><br>Be polite and helpful. <br>{{#if pastRentals.length}}<br>Since the user has rented cars before, mention their past rentals:<br>{{#each pastRentals}}<br>- {{this.year}} {{this.make}} {{this.model}}<br>{{/each}}<br>Use that context to guide your question.<br>{{else}}<br>This is the user&#39;s first rental, so no prior rental history is available.<br>{{/if}}`;<br><br>// Register the partial (reusable template chunk) with llm-exe:<br>utils.registerPartials([{ name: &quot;CarTemplate&quot;, template: carTemplate }]);<br><br>// Create a prompt with conditional logic to include the appropriate partial<br>const prompt = createChatPrompt(`<br>  You are a travel agent for ABC Rentals.<br>  {{#eq request &quot;car&quot;}}{{&gt; CarTemplate }}{{/eq}}<br>  {{#eq request &quot;hotel&quot;}}Ask the user about their hotel preferences...{{/eq}}<br>`);</pre><p>Let’s zoom in on what’s happening here:</p><ul><li>We defined a <strong>partial</strong> named CarTemplate containing the detailed instructions for a car rental scenario. It uses <em>#if</em> and <em>#each</em> Handlebars blocks to tailor the prompt based on whether <em>pastRentals</em> data exists. This partial is essentially a sub-prompt that can be inserted into larger prompts. We registered it via <em>utils.registerPartials(…) </em>so that the prompt engine knows about it.</li><li>Our main prompt (passed to <em>createChatPrompt</em>) is a high-level template that uses a custom helper <em>#eq </em>(an equality check helper provided by llm-exe) to decide which block to include. If <em>request</em> == “car”, it includes the CarTemplate partial, and if <em>request</em> == “hotel”, it uses an inline text for the hotel case (for brevity in this example).</li><li>Notice how <strong>clean and declarative</strong> this prompt template is. We can read it almost like a DSL: “You are a travel agent… if the request is car, insert the car template, if it’s hotel, do something else.” All the looping over `pastRentals` and checking if the array is non-empty is handled <em>inside the template</em>, not in our TypeScript code. This keeps our business logic separate — we didn’t have to write any looping or branching in code to assemble the string; it’s all in the template.</li></ul><p>When we later call <em>prompt.format()</em> with a data object containing <em>{ request: “car”, userName: “Greg”, pastRentals: […] },</em> the Handlebars engine will produce a fully rendered prompt string. It will automatically run the <em>#if</em>/<em>#each</em> logic to include the list of past rentals if present, or the alternate text if not. This <strong>ability to handle conditions and lists within the prompt</strong> is extremely powerful and goes far beyond basic template string capabilities. It allows your prompt to adapt to the input data flexibly, without creating a tangle of string concatenation code.</p><p><strong>Partials</strong> in particular promote reuse and maintainability. If you have common sub-prompts (like a standard set of instructions, or a format example, or in our case a car rental questionnaire), you can define them once and drop them into any prompt with a single <em>{{&gt; PartialName}}</em> include. This keeps prompts DRY (Don’t Repeat Yourself): updates to the partial propagate everywhere it’s used. In contrast, basic template literals have no concept of partials or includes — you’d likely be copying and pasting the same text in multiple places, which is error-prone. The designers of llm-exe explicitly chose Handlebars to leverage features like <em>if</em>, <em>each</em>, and partials because they make prompt templates much more expressive and modular than raw JavaScript templates.</p><p>Finally, you can even define <strong>custom helpers</strong> if needed (for example, formatting a date, special validation, or advanced conditional logic) and register them with the templating engine. llm-exe comes with some helpers out of the box (we saw <em>eq</em> for equality; it also supports the standard <em>if</em>, <em>each</em>, etc., through Handlebars). This means your prompt can include small transformations or checks right inline with the text.</p><p>To sum up, the prompt module gives you all the benefits of Handlebars.js for your LLM prompts — expressions, loops, conditionals, partials — but wrapped in a convenient API suited to chat prompts. Your prompt logic stays in the template, making it easier to read and to tweak without touching surrounding code. And since the prompt is just a template until you format it, you could even load these templates from external files or a CMS, enabling non-developers to help iterate on prompt wording without redeploying code (a nice separation of concerns benefit).</p><h3><strong>Prompt Filters</strong></h3><p>Every prompt in llm-exe supports <strong>filters, </strong>which are<strong> </strong>functions you can attach to run <strong>before</strong> or <strong>after</strong> the prompt is formatted. These are useful for modifying inputs, cleaning up data, or injecting shared context.</p><p>You can set them via the filters option when creating the prompt:</p><pre>const prompt = createChatPrompt(&quot;chat&quot;, instruction, {<br>  filters: {<br>    pre: [myPreFilterFn],<br>    post: [myPostFilterFn],<br>  }<br>});</pre><ul><li><strong>Pre-filters</strong> run <em>before</em> rendering the template, giving you a chance to adjust inputs.</li><li><strong>Post-filters</strong> run <em>after</em> rendering, letting you clean up the final output before it’s sent to the LLM.</li></ul><p>Filters are optional, composable, and super handy when you want to DRY up prompt input or inject shared logic across multiple prompts.</p><h3><strong>Conclusion and Next Steps</strong></h3><p>The <em>prompt</em> module of llm-exe brings much-needed structure and reliability to prompt engineering in TypeScript. By using it, you get:</p><ul><li><strong>Clear separation of prompt logic from code:</strong> prompts are defined as templates, keeping your code cleaner and your prompts easier to tweak.</li><li><strong>Strong typing and early validation:</strong> catch mistakes with prompt inputs at compile-time or before sending to an API.</li><li><strong>Templating power:</strong> Handlebars syntax for loops, conditionals, and partials enables complex, dynamic prompts without complex code.</li><li><strong>Multi-role chat support:</strong> first-class handling of system, user, assistant messages and conversation history for chat models.</li><li><strong>Modularity and reuse:</strong> prompts (and sub-prompts) can be written once and reused, and even tested in isolation, improving maintainability.</li></ul><p>In the broader llm-exe toolkit, the prompt module cleanly interfaces with other components — for example, you can pass your <em>prompt</em> into an llm-exe <strong>executor</strong> along with a parser to actually call an LLM and handle its response. This plug-and-play design means you can swap in different LLM backends or add post-processing without changing how the prompt is built.</p><p>We focused on the prompt module here as part of our series on llm-exe. In future articles, we’ll explore other pieces like the parsing module and LLM executors to see how they complement prompt building. For now, if you’re eager to dive deeper, check out the <a href="https://llm-exe.com/">llm-exe documentation and examples</a> for more insights and advanced usage.</p><p>This post is one piece of a series on building with llm-exe. The rest of the series walks through the other core modules, each one designed to work independently but built to fit together.</p><ul><li><a href="https://medium.com/llm-exe/llm-exe-intro-llm-executor-52bb95c76c84"><strong>Executors</strong></a>: Bind model + prompt + parser into a well-typed function.</li><li><strong>Prompts</strong>: Create structured, reusable templates that adapt to your data.</li><li><a href="https://medium.com/llm-exe/llm-exe-intro-parser-aed787f81082"><strong>Parsers</strong></a>: Convert messy LLM output into clean, typed responses.</li><li><a href="https://medium.com/llm-exe/llm-exe-intro-llm-2f5f35e60caf"><strong>LLM</strong></a>: Choose and configure the models that power it all.</li></ul><p>Want to skip ahead? <a href="https://llm-exe.com/">Read the docs</a>, npm install llm-exe, and <a href="https://github.com/llm-exe/llm-exe">⭐ star the GitHub</a> if you&#39;re into it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d9d40dc923d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/llm-exe/llm-exe-intro-prompt-3d9d40dc923d">llm-exe Prompt: Create Typed, Modular Prompt Templates in TypeScript</a> was originally published in <a href="https://medium.com/llm-exe">llm-exe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>