<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Marib Sultan on Medium]]></title>
        <description><![CDATA[Stories by Marib Sultan on Medium]]></description>
        <link>https://medium.com/@g.maribsultan?source=rss-90c9e729efba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*NEuBiAEnr6VInEpy</url>
            <title>Stories by Marib Sultan on Medium</title>
            <link>https://medium.com/@g.maribsultan?source=rss-90c9e729efba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:42:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@g.maribsultan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Leveraging ASTs for LLM assisted source code manipulation]]></title>
            <link>https://generativeai.pub/leveraging-asts-for-llm-assisted-source-code-manipulation-f06bd2f58ea1?source=rss-90c9e729efba------2</link>
            <guid isPermaLink="false">https://medium.com/p/f06bd2f58ea1</guid>
            <category><![CDATA[abstract-syntax-tree]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Marib Sultan]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 19:26:13 GMT</pubDate>
            <atom:updated>2025-05-03T05:47:14.040Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b1KNfczClJJ9j01e" /><figcaption>AI generated illustration of an AST and its source code</figcaption></figure><p>Short while ago we were building a platform that lets users build web apps with simple prompts, akin to <a href="http://v0.dev/">v0</a> and <a href="http://loveable.dev/">loveable</a>. Of course like every other tech startup these days, we leveraged LLMs, to generate the source code and very quickly ran into a plethora of problems ranging from brand/style inconsistencies to syntax errors and many more.</p><h3>The problem</h3><p>One interesting problem that was unique to frontend code was the problem of hallucinated image URLs. As you can imagine, the source code for a webpage page almost always contains a few image elements and when this code is generated by LLMs its almost guaranteed that the image URLs will likely not point to valid images on the web. So, how do we solve this, such that our generated code contains not only <strong>valid</strong> but also <strong>relevant</strong> image URLs.</p><p>If we break down the problem into smaller units they can be represented as follows:</p><ol><li>Find all occurrences in the code which correspond to an image.</li><li>Once you have reference to these image occurrences, use surrounding and additional context to generate <strong>relevant</strong> caption for each image.</li><li>Use text-to-image model to generate images based on the generated captions.</li><li>Replace the hallucinated image URL with the generated one.</li></ol><p>In this text we will mainly focus on #1 and #4 because the other two are pretty straightforward and are simple LLM calls .</p><h3>Options</h3><h4>Regex</h4><p>So… finding image URLs should be pretty straightforward right? we can simply use a regex pattern to grab all image elements in the JSX. Well, not so much because of multiple reasons:</p><p>a. Images within JSX can exist in many forms such as HTML &lt;img&gt; tags, or framework specific image tags &lt;Image&gt; etc.</p><pre>import Image from &#39;next/image&#39;;<br><br>const component = () =&gt; (<br>  &lt;div&gt;<br>    &lt;img src=&quot;https://example.com/image1.png&quot; alt=&quot;Image 1&quot; /&gt;<br>    &lt;Image src=&quot;https://cdn.site.com/pic.jpg&quot; width={300} height={200} /&gt;<br>  &lt;/div&gt;<br>);<br></pre><p>b. Sometimes images can also be represented as custom components &lt;ProfileImage&gt;</p><pre>const component = () =&gt; (<br>  &lt;div&gt;<br>    &lt;ProfileImage src=&quot;https://userpics.com/avatar.png&quot; /&gt;<br>  &lt;/div&gt;<br>);</pre><p>c. A JSX image tag can have its properties refer a list or object defined in JavaScript.</p><pre>const imageList = [<br>  { src: &quot;https://cdn.site.com/img1.png&quot; },<br>  { src: &quot;https://cdn.site.com/img2.png&quot; },<br>];<br><br>const component = () =&gt; (<br>  &lt;div&gt;<br>    {imageList.map((img) =&gt; (<br>      &lt;img src={img.src} key={img.src} /&gt;<br>    ))}<br>  &lt;/div&gt;<br>);</pre><h4>LLMs</h4><p>If regex cant help us, how about we feed our code to an LLM and instruct it to extract all image occurrences regardless of their location or naming convention, because most LLMs will be smart enough to catch those cases. Well, sure… but this approach comes with its own set of drawbacks:</p><ol><li><strong>Overkill</strong> : Using an LLM just to extract a segment of code is like killing a fly with a cannonball.</li><li><strong>Cost :</strong> Even though the cost incurred for these LLM calls may be small but it still is a cost that can, over the period of time, pile up.</li><li><strong>Slow :</strong> API call to an LLM will definitely take a few seconds to resolve.</li><li><strong>Non-deterministic :</strong> We can rely on LLM to catch most of our cases, but the fact is that these are non deterministic functions, and may fail in certain scenarios.</li></ol><h3>Solution</h3><p>With Regex and LLM options out of the way, lets look at a more plausible choice.</p><h4>AST</h4><p>An Abstract Syntax Tree is a “tree” representation of the source code. It breaks down the source code into syntactic components like JSX elements, functions, JavaScript objects/expressions etc and arranges them into a tree structure that can be traversed.</p><p>In context of our problem, if we construct an AST of our source code, we can traverse it to find all image nodes that match our criteria. Babel lets us do that very easily for JavaScript/Typescript. See example below :</p><pre>const babelParser = require(&#39;@babel/parser&#39;);<br>const traverse = require(&#39;@babel/traverse&#39;).default;<br>const generator = require(&#39;@babel/generator&#39;).default;<br>const t = require(&#39;@babel/types&#39;);<br><br>function findImageNodes(code) {<br>  const ast = babelParser.parse(code, {<br>    sourceType: &#39;module&#39;,<br>    plugins: [&#39;jsx&#39;, &#39;typescript&#39;],<br>  });<br><br>  const candidateNodes = [];<br><br>  // Handle images defined as object literals (e.g. { src: &#39;/foo.png&#39;, alt: &#39;foo&#39; })<br>  traverse(ast, {<br>    ObjectExpression(path) {<br>      const properties = path.node.properties;<br>      properties.forEach((prop) =&gt; {<br>        if (<br>          prop.type === &#39;ObjectProperty&#39; &amp;&amp;<br>          (prop.key.name === &#39;src&#39; || prop.key.name === &#39;url&#39; || prop.key.name === &#39;image&#39;)<br>        ) {<br>          const nodeSourceCode = generator(path.node).code;<br>          candidateNodes.push(nodeSourceCode);<br>        }<br>      });<br>    },<br>    JSXElement(path) {<br>      const openingElement = path.node.openingElement;<br>      const tagName = openingElement.name &amp;&amp; openingElement.name.name;<br>      if (tagName === &#39;img&#39; || tagName === &#39;Image&#39;) {<br>        const nodeSourceCode = generator(openingElement).code;<br>        const existingSrcAttr = openingElement.attributes.find(attr =&gt; attr.name.name === &#39;src&#39;);<br>        // We check if the src attribute is a string literal, because we only want to grab the nodes that have a string literal src<br>        // e.g. &lt;Image src=&quot;/placeholder.png&quot; alt=&quot;A placeholder image for a t-shirt&quot; width={1200} height={900} /&gt;<br>        // but not &lt;Image src={someVariable} alt=&quot;A placeholder image for a t-shirt&quot; width={1200} height={900} /&gt;<br>        // because these non-string literal src attributes are already handled by the ObjectExpression path<br>        if (existingSrcAttr) {<br>            if (existingSrcAttr.value.type === &#39;StringLiteral&#39;) {<br>                candidateNodes.push(nodeSourceCode);<br>            }<br>        } else {<br>            // If does not have existing src property, we would still wana capture it to add that. <br>            candidateNodes.push(nodeSourceCode);<br>        }<br>      }<br>    }<br>  });<br><br>  return candidateNodes;<br>}</pre><p>The code above constructs an AST from the given source code and then traverses it to find JSX Elements or JavaScript object expressions that match our criteria.</p><p>Once we have reference to all these candidate image nodes, we can filter them if needed, execute steps 2 &amp; 3 (caption and image generation), plug the results (generated caption and image URL) back into each node and convert the AST back to source code as shown below :</p><pre>function updateImageNodesWithMetaData(code, nodeResults) {<br>  const ast = babelParser.parse(code, {<br>    sourceType: &#39;module&#39;,<br>    plugins: [&#39;jsx&#39;, &#39;typescript&#39;],<br>  });<br><br>  // Create a mapping from the original node source code to its result<br>  const resultMap = new Map(nodeResults);<br><br>  traverse(ast, {<br>    ObjectExpression(path) {<br>      const properties = path.node.properties;<br>      const nodeSourceCode = generator(path.node).code;<br><br>      if (resultMap.has(nodeSourceCode)) {<br>        properties.forEach((prop) =&gt; {<br>          if (<br>            prop.type === &#39;ObjectProperty&#39; &amp;&amp;<br>            (prop.key.name === &#39;src&#39; || prop.key.name === &#39;url&#39; || prop.key.name === &#39;image&#39;)<br>          ) {<br>            // Update the src property with the new image_url<br>            prop.value = t.stringLiteral(resultMap.get(nodeSourceCode)[&#39;image_url&#39;]);<br><br>            // Update the alt property with the description<br>            const existingAlt = properties.find((p) =&gt; p.key.name === &#39;alt&#39;);<br>            if (existingAlt) {<br>              existingAlt.value = t.stringLiteral(resultMap.get(nodeSourceCode)[&#39;description&#39;]);<br>            } else {<br>              const altProperty = t.objectProperty(<br>                t.identifier(&#39;alt&#39;),<br>                t.stringLiteral(resultMap.get(nodeSourceCode)[&#39;description&#39;])<br>              );<br>              path.node.properties.push(altProperty);<br>            }<br>          }<br>        });<br>      }<br>    },<br>    JSXElement(path) {<br>      const openingElement = path.node.openingElement;<br>      const nodeSourceCode = generator(openingElement).code;<br><br>      if (resultMap.has(nodeSourceCode)) {<br>        const srcAttr = openingElement.attributes.find(<br>          (attr) =&gt; attr.type === &#39;JSXAttribute&#39; &amp;&amp; attr.name.name === &#39;src&#39;<br>        );<br><br>        if (srcAttr) {<br>          // Always update src with the new image URL as a string literal.<br>          srcAttr.value = t.stringLiteral(resultMap.get(nodeSourceCode)[&#39;image_url&#39;]);<br><br>          // Update or add the alt attribute with the new description.<br>          const existingAltAttr = openingElement.attributes.find(<br>            (attr) =&gt; attr.type === &#39;JSXAttribute&#39; &amp;&amp; attr.name.name === &#39;alt&#39;<br>          );<br>          if (existingAltAttr) {<br>            existingAltAttr.value = t.stringLiteral(resultMap.get(nodeSourceCode)[&#39;description&#39;]);<br>          } else {<br>            openingElement.attributes.push(<br>              t.jsxAttribute(<br>                t.jsxIdentifier(&#39;alt&#39;),<br>                t.stringLiteral(resultMap.get(nodeSourceCode)[&#39;description&#39;])<br>              )<br>            );<br>          }<br>        }<br>      }<br>    }<br>  });<br><br>  return generator(ast).code;<br>}</pre><h3>Example</h3><p>This section shows an example source code containing hallucinated image URLs in various forms (JSX Elements, Object Expressions) which are then replaced with generated ones along with captions in the output without affecting the structural integrity or syntax of the source code.</p><h4>Input</h4><pre><br>export default function EcommerceTShirts() {<br>  const [menuOpen, setMenuOpen] = useState(false)<br>  const [searchOpen, setSearchOpen] = useState(false)<br><br>  const hats = [<br>    { id: 1, name: &quot;Simple Hat&quot;, price: &quot;$24.99&quot;, image: &quot;/hat.jpg&quot;, alt: &quot;existing&quot; },<br>    { id: 2, name: &quot;New Hat&quot;, price: &quot;$19.99&quot;, image: &quot;/hat-new.jpg&quot; },<br>  ]<br><br>  return (<br>    &lt;div className=&quot;flex flex-col min-h-screen bg-gray-50&quot;&gt;<br>      &lt;main className=&quot;flex-grow mt-20&quot;&gt;<br>        &lt;section className=&quot;py-16&quot;&gt;<br>          &lt;div className=&quot;container mx-auto px-4&quot;&gt;<br>            &lt;h2 className=&quot;text-3xl font-bold mb-8 text-center text-gray-800&quot;&gt;Featured T-Shirts&lt;/h2&gt;<br>            &lt;div className=&quot;grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-8&quot;&gt;<br>              {[<br>                { id: 1, name: &quot;Graphic Tee&quot;, price: &quot;$24.99&quot;, image: &quot;/tshirt1.jpg&quot; },<br>                { id: 2, name: &quot;Pocket Tee&quot;, price: &quot;$19.99&quot;, image: &quot;/tshirt2.jpg&quot; },<br>                { id: 3, name: &quot;V-Neck Tee&quot;, price: &quot;$22.99&quot;, image: &quot;/tshirt3.jpg&quot; },<br>                { id: 4, name: &quot;Crew Neck Tee&quot;, price: &quot;$21.99&quot;, image: &quot;/tshirt4.jpg&quot; },<br>              ].map((shirt) =&gt; (<br>                &lt;Card key={shirt.id} className=&quot;transition transform hover:scale-105 hover:shadow-lg&quot;&gt;<br>                  &lt;CardHeader&gt;<br>                    &lt;Image<br>                      src={shirt.image}<br>                      alt={shirt.name}<br>                      width={300}<br>                      height={300}<br>                      className=&quot;w-full h-64 object-cover rounded-t-lg&quot;<br>                    /&gt;<br>                  &lt;/CardHeader&gt;<br>                  &lt;CardContent&gt;<br>                    &lt;CardTitle className=&quot;text-xl font-semibold&quot;&gt;{shirt.name}&lt;/CardTitle&gt;<br>                    &lt;p className=&quot;text-gray-600&quot;&gt;{shirt.price}&lt;/p&gt;<br>                  &lt;/CardContent&gt;<br>                  &lt;CardFooter&gt;<br>                    &lt;Button className=&quot;w-full bg-indigo-600 text-white hover:bg-indigo-700 transition duration-300&quot;&gt;<br>                      Add to Cart<br>                    &lt;/Button&gt;<br>                  &lt;/CardFooter&gt;<br>                &lt;/Card&gt;<br>              ))}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/section&gt;<br>        <br>        &lt;section className=&quot;py-16&quot;&gt;<br>          &lt;div&gt;<br>            &lt;img<br>              src=&quot;/placeholder.jpg?height=400&amp;width=1200&quot;<br>              alt=&quot;A featured hat displayed in a stylish setting, showcasing a vibrant background with a gradient blending from blue to indigo, creating an inviting atmosphere for potential customers.&quot;<br>              className=&quot;w-full h-96 object-cover opacity-50&quot;<br>              id=&quot;08ba0c93-1f24-4a28-a459-4f115299849f&quot;<br>            /&gt;<br>          &lt;/div&gt;<br>        &lt;/section&gt;<br>        <br>        &lt;section className=&quot;py-16&quot;&gt;<br>          &lt;div&gt;<br>            &lt;Image<br>              height={900}<br>              src=&quot;/placeholder.png&quot;<br>              alt=&quot;A placeholder image for a t-shirt&quot;<br>              width={1200}<br>              className=&quot;w-full h-96 object-cover opacity-50&quot;<br>              id=&quot;08ba0c93-1f24-4a28-a459-4f115299849f&quot;/&gt;<br>          &lt;/div&gt;<br>        &lt;/section&gt;<br><br>        &lt;section className=&quot;py-16&quot;&gt;<br>          &lt;div&gt;<br>            {hats.map((hat) =&gt; (<br>              &lt;img<br>                key={hat.id}<br>                src={hat.image}<br>                alt={hat.name}<br>                className=&quot;w-full h-96 object-cover opacity-50&quot;<br>                id={hat.id.toString()}/&gt;<br>            ))}<br>          &lt;/div&gt;<br>        &lt;/section&gt;<br><br>      &lt;/main&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><h4>Output</h4><pre>export default function EcommerceTShirts() {<br>  const [menuOpen, setMenuOpen] = useState(false)<br>  const [searchOpen, setSearchOpen] = useState(false)<br><br>  const hats = [<br>    {<br>      id: 1,<br>      name: &quot;Simple Hat&quot;,<br>      price: &quot;$24.99&quot;,<br>      image: &quot;s3.productx.hat.jpg&quot;,<br>      alt: &quot;A simple classic hat in a neutral tone displayed on a flat surface&quot;<br>    },<br>    {<br>      id: 2,<br>      name: &quot;New Hat&quot;,<br>      price: &quot;$19.99&quot;,<br>      image: &quot;s3.productx.hat-new.jpg&quot;,<br>      alt: &quot;A modern-style hat with a minimalist logo on the front panel&quot;<br>    },<br>  ]<br><br>  return (<br>    &lt;div className=&quot;flex flex-col min-h-screen bg-gray-50&quot;&gt;<br>      &lt;main className=&quot;flex-grow mt-20&quot;&gt;<br>        &lt;section className=&quot;py-16&quot;&gt;<br>          &lt;div className=&quot;container mx-auto px-4&quot;&gt;<br>            &lt;h2 className=&quot;text-3xl font-bold mb-8 text-center text-gray-800&quot;&gt;Featured T-Shirts&lt;/h2&gt;<br>            &lt;div className=&quot;grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-8&quot;&gt;<br>              {[<br>                { id: 1, name: &quot;Graphic Tee&quot;, price: &quot;$24.99&quot;, image: &quot;s3.productx.tshirt1.jpg&quot;, alt: &quot;A white graphic t-shirt featuring bold abstract art&quot; },<br>                { id: 2, name: &quot;Pocket Tee&quot;, price: &quot;$19.99&quot;, image: &quot;s3.productx.tshirt2.jpg&quot;, alt: &quot;A soft grey t-shirt with a front chest pocket&quot; },<br>                { id: 3, name: &quot;V-Neck Tee&quot;, price: &quot;$22.99&quot;, image: &quot;s3.productx.tshirt3.jpg&quot;, alt: &quot;A navy V-neck t-shirt made from breathable cotton&quot; },<br>                { id: 4, name: &quot;Crew Neck Tee&quot;, price: &quot;$21.99&quot;, image: &quot;s3.productx.tshirt4.jpg&quot;, alt: &quot;A classic black crew neck t-shirt with a tailored fit&quot; },<br>              ].map((shirt) =&gt; (<br>                &lt;Card key={shirt.id} className=&quot;transition transform hover:scale-105 hover:shadow-lg&quot;&gt;<br>                  &lt;CardHeader&gt;<br>                    &lt;Image<br>                      src={shirt.image}<br>                      alt={shirt.alt}<br>                      width={300}<br>                      height={300}<br>                      className=&quot;w-full h-64 object-cover rounded-t-lg&quot;<br>                    /&gt;<br>                  &lt;/CardHeader&gt;<br>                  &lt;CardContent&gt;<br>                    &lt;CardTitle className=&quot;text-xl font-semibold&quot;&gt;{shirt.name}&lt;/CardTitle&gt;<br>                    &lt;p className=&quot;text-gray-600&quot;&gt;{shirt.price}&lt;/p&gt;<br>                  &lt;/CardContent&gt;<br>                  &lt;CardFooter&gt;<br>                    &lt;Button className=&quot;w-full bg-indigo-600 text-white hover:bg-indigo-700 transition duration-300&quot;&gt;<br>                      Add to Cart<br>                    &lt;/Button&gt;<br>                  &lt;/CardFooter&gt;<br>                &lt;/Card&gt;<br>              ))}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/section&gt;<br>        <br>        &lt;section className=&quot;py-16&quot;&gt;<br>          &lt;div&gt;<br>            &lt;img<br>              src=&quot;s3.productx.placeholder.jpg&quot;<br>              alt=&quot;A featured hat displayed in a stylish setting with a vibrant background that fades from blue to indigo, enhancing visual appeal&quot;<br>              className=&quot;w-full h-96 object-cover opacity-50&quot;<br>              id=&quot;08ba0c93-1f24-4a28-a459-4f115299849f&quot;<br>            /&gt;<br>          &lt;/div&gt;<br>        &lt;/section&gt;<br>        <br>        &lt;section className=&quot;py-16&quot;&gt;<br>          &lt;div&gt;<br>            &lt;Image<br>              height={900}<br>              src=&quot;s3.productx.placeholder.png&quot;<br>              alt=&quot;A placeholder image representing a featured t-shirt on a blank background&quot;<br>              width={1200}<br>              className=&quot;w-full h-96 object-cover opacity-50&quot;<br>              id=&quot;08ba0c93-1f24-4a28-a459-4f115299849f&quot;/&gt;<br>          &lt;/div&gt;<br>        &lt;/section&gt;<br><br>        &lt;section className=&quot;py-16&quot;&gt;<br>          &lt;div&gt;<br>            {hats.map((hat) =&gt; (<br>              &lt;img<br>                key={hat.id}<br>                src={hat.image}<br>                alt={hat.alt}<br>                className=&quot;w-full h-96 object-cover opacity-50&quot;<br>                id={hat.id.toString()}/&gt;<br>            ))}<br>          &lt;/div&gt;<br>        &lt;/section&gt;<br><br>      &lt;/main&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>A gist of complete code can be found <a href="https://gist.github.com/m-a-r-i-b/e51a04b25d95b7b85dd4530e20b04a07">here</a>.</p><h3>Additional Use Cases</h3><p>ASTs come in handy for a lot of use cases, see :</p><p>1.<a href="https://aider.chat/2024/05/22/linting.html"> Aider’s blog post on how they lint code for LLMs</a></p><p>2. Excellent <a href="https://www.youtube.com/watch?v=Ve-akpov78Q">talk on code maintenance and manipulation at scale</a> using <a href="https://github.com/getgrit/gritql">GritQL</a> (uses ASTs under the hood)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*gueIb5m7czXcPndS.png" /></figure><p>This story is published on <a href="https://generativeai.pub/">Generative AI</a>. Connect with us on <a href="https://www.linkedin.com/company/generative-ai-publication">LinkedIn</a> and follow <a href="https://www.zeniteq.com/">Zeniteq</a> to stay in the loop with the latest AI stories.</p><p>Subscribe to our <a href="https://www.generativeaipub.com/">newsletter</a> and <a href="https://www.youtube.com/@generativeaipub">YouTube</a> channel to stay updated with the latest news and updates on generative AI. Let’s shape the future of AI together!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*h097gIYa0vPvGDGV.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f06bd2f58ea1" width="1" height="1" alt=""><hr><p><a href="https://generativeai.pub/leveraging-asts-for-llm-assisted-source-code-manipulation-f06bd2f58ea1">Leveraging ASTs for LLM assisted source code manipulation</a> was originally published in <a href="https://generativeai.pub/">Generative AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Orchestrating Agentic Workflows]]></title>
            <link>https://generativeai.pub/orchestrating-agentic-workflows-1e8dec6f6ec5?source=rss-90c9e729efba------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e8dec6f6ec5</guid>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[workflow-automation]]></category>
            <category><![CDATA[orchestration]]></category>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Marib Sultan]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 16:37:46 GMT</pubDate>
            <atom:updated>2025-05-07T01:30:49.800Z</atom:updated>
            <content:encoded><![CDATA[<p>This article talks about an agent orchestration mechanism (not sure whether to call it a framework or a design pattern — likely both, so let’s stick with <em>mechanism</em>) inspired by the thoughts and ideas, developed after going over the design of popular frameworks such as LangGraph and, to some extent, GStreamer. We will begin with the question of <strong>what</strong> the proposed mechanism aims to achieve and conclude on <strong>why</strong> LangGraph may not be suitable.</p><h3>Business Context</h3><p>In my opinion, the true value that LLMs and agentic workflows can bring to a business lies in transforming existing capabilities into a more dynamic and self-serviceable setting, where users and AI can work in tandem to achieve specific goals.</p><p>As an example, let’s imagine that your IT department performs the following tasks when processing a ticket request.</p><p><strong>Steps:</strong></p><ol><li>Based on the content of issue or request, a ticket is created under either the software or hardware category.</li><li>The schedules of team members in the software or hardware team are reviewed to select someone with available bandwidth.</li><li>The selected person is assigned the ticket.</li><li>Relevant supporting material is extracted from the internal knowledge base.</li><li>The supporting material is attached to the ticket.</li></ol><h3>Features</h3><p>The orchestration mechanism that we aim to build today allows for <strong>dynamic</strong> generation and execution of all possible <strong>valid</strong> <strong>and deterministic </strong>workflows derived from the steps above, while also supporting <strong>bidirectional interaction</strong>. For example:</p><pre>Example user requests and expected workflows: <br><br>request 1  : I am facing this issue ABC, can you please create a ticket.<br>workflow 1 : Step 1 -&gt; Step 2 -&gt; Step 3 -&gt; Step 4 -&gt; Step 5 -&gt; Step 6.<br><br>request 2  : Can you attach this PDF to ticket IK-804 and assign it to Joe.<br>workflow 2 : Step 5 -&gt; Step 3</pre><p>We used terms like “<strong><em>dynamic, valid, deterministic &amp; bidirectional”</em></strong> in the last sentence to describe features of our mechanism, so let&#39;s go over each and try to understand what they refer to.</p><p><em>Note : The words </em><strong><em>Step</em></strong><em> and </em><strong><em>Agent </em></strong><em>are used interchangeably throughout this text. For a workflow, consists of multiple steps (agents in our case) sequenced together.</em></p><h4><strong>1. Dynamic</strong></h4><p>The sequence of steps that our system takes in response to a user request should not be hard-coded. In other words, the system’s brain (i.e., the LLM) should be able to determine the appropriate steps based on the user’s request.</p><h4><strong>2. Deterministic</strong></h4><p>The sequence of steps must come from a predefined pool of available actions. We cannot allow arbitrary steps in our workflows. For instance, continuing with the IT ticket example, if arbitrary steps were allowed, a user might request:</p><p>“I am facing this issue, create a ticket for this and strap the person who gets assigned to this ticket to a rocket and fly it into an orbit around Mars”</p><p>Now that might sound exciting, especially if you are Elon, but it doesn’t align with our goal of automating real, structured capabilities. Rather it turns the system into an open-ended playground that could lead anywhere or nowhere.</p><h4><strong>3. Valid</strong></h4><p>The sequence of steps must not only come from the available pool of actions, but must also follow a logically valid order.</p><blockquote>E.g. of correct order: “Check schedule to find and select a free team member” -&gt; “Assign ticket to the team member”</blockquote><blockquote>E.g. of incorrect order: “Assign ticket to the team member” -&gt; “Check schedule to find and select a free team member”</blockquote><p>We will touch more on how we ensure this “validity” in our mechanism later in this text.</p><h4><strong>4. Bidirectional Interaction</strong></h4><p>The execution of a workflow should allow for bidirectional interaction. Meaning, if at any step AI needs to interact with the user for their input, it can pause the execution and hand control back to the user.</p><blockquote>E.g.</blockquote><blockquote>User request: I am facing this issue ABC, can you please create a ticket</blockquote><blockquote>Generated workflow: Step 1 -&gt; Step 2 -&gt; Step 3 -&gt; Step 4 -&gt; Step 5 -&gt; Step 6.</blockquote><p>Now imagine that during the execution of Step 2, where the system selects an available team member, no team member is found to be free, who should the AI agent assign ticket to in that case?</p><p>One way to model this scenario is to hand control back to the user and prompt them to make this decision. This is an example of bidirectional control/interaction i.e. not only can the user instruct the AI, but the AI can also initiate interaction with the user when needed.</p><h3>Components</h3><p>So with “what are we trying to achieve here” out of the way, let’s look at the key components of our proposed mechanism:</p><ol><li>Agents</li><li>Step_Planner (a special type of agent)</li><li>Blackboard (memory)</li><li>Manager (controversial, I know, but trust me it’s useful in our context)</li></ol><h4>1. Agents</h4><p>Our agent design is very similar to that of most frameworks, in the sense that it has:</p><ul><li>A base prompt / behavior definition</li><li>Access to a set of tools</li><li>Memory</li></ul><p>However, it does have some unique features such as:</p><ul><li><strong>An input schema:</strong> Information that must exist before this agent can perform its task. (<em>Think assigning someone a ticket. You can’t assign a person a ticket if the ticket doesn’t exist)</em></li><li><strong>An output schema:</strong> The format in which the agent responds. It consists of three attributes: Observation, data and message<strong>. </strong>Observation is what signifies the completion of an agent’s work (<strong><em>DONE</em>)</strong> or if it needs to interact with the user (<strong><em>INTERACT_WITH_USER</em></strong>). Data, holds the<strong> information</strong> that this agent produces once it has completed its working (For instance, “supporting material” from our step/agent #4). Each agent writes this information only to their section of blackboard (memory). And lastly, a message key that contains a message, used when the agent needs to interact with the user or publish a progress update.</li></ul><pre>Agent response schema template: <br>{<br> observation : Enum ( DONE | INTERACT_WITH_USER )<br> data : {}<br> msg : str<br>}</pre><p><em>Note that the response schema does not need to be strictly JSON, but it has to be structured, to ensure </em><strong><em>validity </em></strong><em>of generated workflows.</em></p><ul><li>Conversation memory, which holds all interactions that <strong>this</strong> agent had with the user. Keeping the conversation history per agent level prevents the overall context of the workflow from being polluted by a single agent. Especially in the case of multiple back and forth turns between the user and AI at a particular step. This also limits the context each agent has to work with, improving their capability to perform tasks. ( <em>Of course we do keep a global/overall conversation history separately inside the </em><strong><em>Blackboard</em></strong><em>, to be presented neatly to the frontend )</em>. Now you may be wondering, if each agent only has context about themselves, how do they know the bigger picture or make use of information that has been deduced from earlier steps? That’s where input schema comes into play. Each agent can read any <strong>information</strong>, stored in the <strong>Blackboard.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*tSi2c1CNrbVPwPIKlzPZBQ.png" /><figcaption>Figure 1 ( Illustrates Agent’s components )</figcaption></figure><p>Now following along the example of IT ticket request, lets define 5 agents for our example system.</p><pre><br>Ticket Generator<br> - Input   : Description of issue or ticket<br> - Output  : Reference to created ticket and category of ticket (software/hardware)<br><br><br>Team member finder<br> - Input   : A category (software/hardware)<br> - Output  : Reference to team member with available bandwidth of team with provided category<br><br><br>Ticket Assigner<br> - Input   : Reference to ticket, a person<br> - Output  : N/A (Assigns ticket to a person)<br><br><br>Supporting material extractor<br> - Input   : Description of issue or ticket<br> - Output  : Supporting material or reference to a file<br><br><br>File attacher<br> - Input   : Reference to ticket, reference to a file<br> - Output  : N/A (Attaches the file to ticket)</pre><p>The design of agent, in particular its input and output schemas are inspired by GStreamer elements and their sink/source pads. Just like how each element in a GStreamer pipeline has a source and a sink pad and you chain together these elements based on matching an elements sink capabilities with the source capabilities of previous element, our agents are chained together based on input and output schemas.</p><p>The key difference is that in our workflow, an agent doesn’t just rely on output from the agent immediately before it. Instead, it can also make use of outputs from all agents that precede it in the current workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GvZiIrq4Ljtnged5KSqyOw.png" /><figcaption>Figure 2 ( Illustrates agent dependency on output of another agent, similar to GStreamer pipeline )</figcaption></figure><p>Do note that, the diagram above illustrates only the dependability of one agent’s input on the outputs of others. It does not imply that the agents pass information directly among themselves <em>(because an agent’s output may not be immediately needed by the following agent)</em>. In practice, each agent writes their set of information to the <strong>Blackboard</strong>, from where its read by other agents if needed. This is more clearly depicted in Figure 3.</p><h4>2. Step_Planner</h4><p>A special kind of agent that ensures generation of a <strong>valid</strong> workflow based on user intent. As discussed earlier, a <strong>valid workflow</strong> is one in which the agents are arranged in a correct and logical order. This order is derived from user’s intent and validated by checking whether the input_schema of each agent in the workflow is satisfied by the output_schema of the agents that precede it.</p><p>An example of a valid workflow is shown in Figure 2 above. In contrast, an <strong>invalid</strong> workflow would be one in which the Ticket_Assigner agent follows the Ticket_Generator agent directly. This is invalid because Ticket_Assigner requires not just a reference to the generated ticket, but also a reference to a team member to whom the ticket should be assigned.</p><h4>3. Blackboard</h4><p>Blackboard is really just a… blackboard. It’s a shared <strong>memory layer</strong> where every piece of information related to a workflow and its execution state is recorded.</p><p>It stores:</p><ul><li>The <strong>current step</strong> scheduled for execution.</li><li>A record of <strong>previous steps</strong> that have been completed.</li><li>The list of <strong>next steps</strong> yet to be executed.</li><li><strong>All interactions</strong> between the user and the AI up to this point.</li><li>And every <strong>bit of data</strong> gathered or produced by each agent so far.</li></ul><p>In short, the Blackboard acts as the <strong>single source of truth</strong> for the entire workflow. Agents don’t communicate directly with one another — instead, they contribute to and consume from the Blackboard, enabling loose coupling and modularity.</p><pre>Blackboard {<br>  state {<br>    current_step : Enum = Ticket_Assigner,<br>    previous_steps : List[Enum] = [Ticket_Generator, Team_Member_Finder],<br>    in_execution: boolean = True,<br>    planned_steps: : List[Enum] = [Supporting_Material_Extractor, File_Attacher]<br>  }<br>  <br>  information {<br>    Ticket_Generator : Type&lt;Ticket_Generator_Output_Schema&gt; = {<br>      ticket_reference: any<br>    }<br>    Team_Member_Finder : Type&lt;Team_Member_Finder_Output_Schema&gt; = {<br>      member_reference: any<br>    }<br>    ...<br>  }<br>  <br>  global_conversation_history [<br>    {step : Enum , user_msg : str },<br>    {step : Enum , ai_msg : str },<br>    {step : Enum , user_msg : str },<br>    {step : Enum , ai_msg : str }<br>  ]</pre><p>Note that the <strong>Information </strong>section within the Blackboard holds data from the output_schema of each agent and is written or updated when an agent has completed its task i.e. the agent observation status becomes “<strong>DONE</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kSyC_38pn8gfCAldushIQQ.png" /><figcaption>Figure 3 ( Illustrates how agents read and write to blackboard )</figcaption></figure><h4>4. Manager</h4><p>The Manager is the centerpiece of the system. It is responsible for:</p><ul><li><strong>Managing system state</strong> throughout the lifecycle of a workflow.</li><li><strong>Orchestrating the execution loop</strong> over the workflow generated by the StepPlanner agent.</li><li><strong>Handling control flow decisions</strong>, such as when to continue or pause execution based on runtime conditions.</li></ul><p><strong>Execution Lifecycle</strong></p><p><strong>New User Request</strong><br>When a new user query or request is received:</p><ul><li>The Manager invokes the StepPlanner agent to generate a <strong>workflow</strong>.</li><li>This workflow is then <strong>loaded into state</strong> (within the Blackboard).</li><li>Execution of the workflow begins, proceeding step by step through the agents.</li></ul><p><strong>Control Flow Management</strong><br>During execution, the Manager:</p><ul><li>Monitors the OBSERVATION from the <strong>currently executing agent</strong>.</li><li>Decides whether to <strong>continue execution</strong> or <strong>pause</strong>, based on the agent’s status.</li><li>For example, if the observation is &quot;INTERACT_WITH_USER&quot;, it pauses.</li><li>If it’s &quot;DONE&quot;, it proceeds to the next step.</li></ul><p><strong>Resuming Paused Workflows</strong><br>When a paused workflow receives <strong>new input or action from the user</strong>:</p><ul><li>The Manager <strong>resumes execution</strong> from the saved state.</li><li>It continues from where it left off, reacting to the updated context.</li></ul><p>Think of it as a glorified while loop, but one that can pause and resume based on the dynamic <strong>OBSERVATION</strong> from the agent currently being executed.</p><h3>Pieced Together</h3><p>With everything pieced together, when a fresh or new user request is received the process looks something like below.</p><ol><li>Manager requests step_planner agent to generate a sequenced workflow, given available agents in the system and the user’s query/intent.</li><li>The generated workflow is <strong>validated</strong> for out of place agents i.e. every agent’s input_schema should be fulfilled by output_schema of agents that precede it.</li><li>State gets initialized with the generated workflow and the first agent in workflow is scheduled for execution.</li><li>Manager’s execution loop begins and continues until we reach an <strong>Observation</strong> of <strong>INTERACT_WITH_USER </strong>or end of workflow<strong>.</strong></li><li>When the current agent produces observation of <strong>INTERACT_WITH_USER, </strong>the execution pauses, and the user is presented with a message or an action item. Note that this interaction gets saved to agent’s memory (conversation history) so that when user responds, it knows what it had asked for.</li><li>When the user responds, manager loads the paused state from blackboard and resumes execution from the paused agent with this new message or action that user just provided.</li><li>The agent checks if provided user action is sufficient for its task, if not it can get back to user again by issuing the INTERACT_WITH_USER observation, If yes and the agent’s work is completed it outputs the observation<strong> DONE</strong> and the data in output_schema gets written to blackboard as information.</li><li>Upon completion of a step, manager moves the workflow state to next agent and the cycle continues until workflow completion.</li></ol><h3>In summary</h3><p>The step planner agent using available pool of agents ensures <strong>dynamic</strong> yet <strong>deterministic</strong> workflows to be created. Input &amp; output schemas help ensure generation of<strong> valid</strong> workflows and lastly, the observation pattern allows for <strong>bidirectional</strong> interaction between user and AI.</p><p>Based on the learning so far, we can see how the proposed mechanism can transform <strong>existing capabilities</strong> into a <strong>dynamic, composable, and self-serviceable system</strong>. Rather than relying on hard-coded paths or static flows, this design:</p><ul><li><strong>Adapts in real-time</strong> to user needs and system capabilities.</li><li><strong>Scales naturally</strong> as more agents or steps are introduced.</li><li>Enables <strong>arbitrary valid workflows</strong> to be constructed and executed, far beyond the two examples discussed.</li></ul><pre>Example user requests and expected workflows: <br><br>request 1  : I am facing this issue ABC, can you please create a ticket.<br>workflow 1 : Step 1 -&gt; Step 2 -&gt; Step 3 -&gt; Step 4 -&gt; Step 5 -&gt; Step 6.<br><br>request 2  : Can you attach this PDF to ticket IK-804 and assign it to Joe.<br>workflow 2 : Step 5 -&gt; Step 3</pre><h3>Vs LangGraph</h3><p>While LangGraph also lets us execute graphs or workflows and hand control to user at certain steps, it does so in a hard-coded way. i.e. you have to pre define your “graph” and user interaction steps before the execution begins and this fails to capture the dynamic needs of many systems.</p><p>Whereas the mechanism proposed above does not have this limitation. It not only allows dynamic yet deterministic workflows to be created and executed, but also enables user interaction on an on-demand basis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*gueIb5m7czXcPndS.png" /></figure><p>This story is published on <a href="https://generativeai.pub/">Generative AI</a>. Connect with us on <a href="https://www.linkedin.com/company/generative-ai-publication">LinkedIn</a> and follow <a href="https://www.zeniteq.com/">Zeniteq</a> to stay in the loop with the latest AI stories.</p><p>Subscribe to our <a href="https://www.generativeaipub.com/">newsletter</a> and <a href="https://www.youtube.com/@generativeaipub">YouTube</a> channel to stay updated with the latest news and updates on generative AI. Let’s shape the future of AI together!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*h097gIYa0vPvGDGV.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e8dec6f6ec5" width="1" height="1" alt=""><hr><p><a href="https://generativeai.pub/orchestrating-agentic-workflows-1e8dec6f6ec5">Orchestrating Agentic Workflows</a> was originally published in <a href="https://generativeai.pub/">Generative AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>