<?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 Chih-Yu Yeh on Medium]]></title>
        <description><![CDATA[Stories by Chih-Yu Yeh on Medium]]></description>
        <link>https://medium.com/@chihyuyeh?source=rss-262d28fa7c81------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WiiK-pqBBNqe-SmekPlEqA@2x.jpeg</url>
            <title>Stories by Chih-Yu Yeh on Medium</title>
            <link>https://medium.com/@chihyuyeh?source=rss-262d28fa7c81------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:38:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chihyuyeh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How do we rewrite Wren AI LLM Service to support 1500+ concurrent users online?]]></title>
            <link>https://medium.com/wrenai/how-do-we-rewrite-wren-ai-llm-service-to-support-1500-concurrent-users-online-9ba5c121afc3?source=rss-262d28fa7c81------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ba5c121afc3</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Chih-Yu Yeh]]></dc:creator>
            <pubDate>Fri, 28 Jun 2024 01:57:09 GMT</pubDate>
            <atom:updated>2024-09-04T13:05:13.912Z</atom:updated>
            <content:encoded><![CDATA[<h4>How Wren AI LLM Service leverages Haystack and Hamilton as performant Generative AI infrastructure</h4><p><strong><em>This blog post is cross-posting from </em></strong><a href="https://www.getwren.ai/blog?utm_source=medium&amp;utm_medium=post&amp;utm_campaign=cross_posting"><strong><em>The Wren AI Blog</em></strong></a></p><h4>Table of Contents</h4><p>· <a href="#95f0">What is Wren AI LLM Service responsible for?</a><br>· <a href="#3137">The Evolution of Wren AI LLM Service architecture</a><br>· <a href="#67b8">Architecture Rewrite Results</a><br>· <a href="#3cf7">Performance Testing Results</a><br>· <a href="#ffdb">Final Remarks</a></p><p>In generative AI applications, often the performance bottleneck is due to the long latency of LLM execution, thus, it’s crucial to combat this issue. In this article, I will share with you how we leverage Haystack and Hamilton to make AI pipelines fully asynchronous and can support 1500+ concurrent users!</p><h3>What is Wren AI LLM Service responsible for?</h3><p><a href="https://www.getwren.ai/">Wren AI</a> is a <strong>text-to-SQL solution</strong> for data teams to get results and insights faster by asking business questions without writing SQL. It’s <a href="https://github.com/Canner/WrenAI">open-source</a>! Wren AI LLM Service is responsible for LLM-related tasks like converting natural language questions into SQL queries and providing step-by-step SQL breakdowns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qywv_xu5-bZwHOvkAp35uw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S0vOoAPZxdIHzBbv7-_ybA.png" /><figcaption>Users can ask questions related to the dataset and understand step-by-step SQL breakdowns.</figcaption></figure><p><em>Notes:</em> The tasks described above are the main tasks for Wren AI LLM Service as of now, and there are several other potential new functionalities in our backlog or progress, such as text-to-chart, recommend follow-up questions, recommend new questions after the user is on-boarded, feedback loop, clarification, llm system evaluation framework, etc. Welcome to discuss with us and share your thoughts, on our <a href="https://discord.gg/5DvshJqG8Z">Discord Server</a>!</p><h3>The Evolution of Wren AI LLM Service Architecture</h3><h4>Wren AI LLM Service 1.0: No LLM Framework</h4><p>The first version of Wren AI LLM Service did not utilize any large language model (LLM) frameworks. Instead, it relied on:</p><ul><li>LiteLLM for connecting to LLMs</li><li>Chroma as the vector database</li></ul><p>As a result, the first version is a <a href="https://arxiv.org/pdf/2312.10997">naive RAG</a> for the text-to-SQL task.</p><p><strong>The Challenge</strong></p><p>After the first version was done, we understood that there are some challenges if we would like to support more complex AI pipelines:</p><ol><li>There should be an easier way to support AI pipelines as DAGs(directed acyclic graphs).</li><li>We may need to support other LLMs and vector databases in the future.</li></ol><h4>Wren AI LLM Service 2.0: Haystack</h4><p>After one week’s survey, we decided to choose Haystack as our infrastructure to build generative AI applications. We started to use it during its 2.0 beta version. There are several reasons why we chose Haystack, listed as follows:</p><ol><li>Simple APIs, intuitive design, great community support, and good code readability</li><li>Extensive pre-built <a href="https://haystack.deepset.ai/integrations?type=Model+Provider&amp;version=2.0">LLM</a> and <a href="https://haystack.deepset.ai/integrations?type=Document+Store&amp;version=2.0">Document Store</a> integrations</li><li>Easy creation of <a href="https://docs.haystack.deepset.ai/docs/custom-components">custom components</a></li><li><a href="https://docs.haystack.deepset.ai/docs/intro">The concept of pipeline as the core design philosophy</a></li></ol><p>As a result, we can easily develop more complex AI pipelines and integrate other LLMs and Document Stores right away.</p><p><strong>The Challenge</strong></p><p>You may think Haystack is a perfect choice for building generative AI applications; unfortunately, there is no perfect software in the world. There is one challenge for our use case: we need to consider the performance of the application in terms of user’s requests per second(a.k.a throughput) and time spent per user’s request(a.k.a latency).</p><p>Since Haystack doesn’t have built-in async support, the pipeline computation is synchronous by default(<em>The bottleneck of the generative AI applications is usually rooted in the long latency of LLM execution</em>). So, we need to make our AI pipelines async to combat the issue. (<em>This issue is one of the popular raised topics, and there is a </em><a href="https://docs.google.com/presentation/d/1SUw-92-XwsC4HO_efSLqJuK1audr-gKecPe1IaBAIyk/edit#slide=id.gf34afcd34d_0_93"><em>slide</em></a><em> shared by the Haystack team introducing several proposals to combat the issue</em>)</p><h4>Wren AI LLM Service 3.0: Haystack + Hamilton</h4><p>We thought a candidate solution should have at least these criteria:</p><ol><li>It can easily provide an asynchronous computation environment for our AI pipelines.</li><li>It can be easily integrated with Haystack</li></ol><p>We found a library called <a href="https://github.com/dagWorks-Inc/hamilton">Hamilton</a>. Hamilton is a lightweight Python library that can help us separate pipeline computation logic from the computation runtime environment.</p><blockquote>Quoted from <a href="https://github.com/dagWorks-Inc/hamilton">Hamilton’s GitHub page</a>:</blockquote><blockquote>Hamilton is a lightweight Python library for directed acyclic graphs (DAGs) of data transformations. Your DAG is portable; it runs anywhere Python runs, whether it’s a script, notebook, Airflow pipeline, FastAPI server, etc. Your DAG is expressive; Hamilton has extensive features to define and modify the execution of a DAG (e.g., data validation, experiment tracking, remote execution).</blockquote><blockquote>To create a DAG, write regular Python functions that specify their dependencies with their parameters. As shown below, it results in readable code that can always be visualized. Hamilton loads that definition and automatically builds the DAG for you!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EiSsEmz2rdZDSgWv.png" /><figcaption>Image from <a href="https://github.com/dagWorks-Inc/hamilton">Hamilton’s GitHub page</a></figcaption></figure><h3>Architecture Rewrite Results</h3><p>You can see the differences between using Haystack alone and Haystack integrated with Hamilton with code snippets provided below:</p><p><strong>Code Snippets Before rewriting the AI pipeline using Hamilton</strong></p><ul><li>We compose the pipeline in the __init__ method of the Generation class with pipeline’s built-in add_component and connect methods.</li><li>We define a run method to invoke the pipeline execution.</li></ul><pre>class Generation(BasicPipeline):<br>    def __init__(<br>        self,<br>        llm_provider: LLMProvider,<br>    ):<br>        self._pipeline = Pipeline()<br>        self._pipeline.add_component(<br>            &quot;text_to_sql_prompt_builder&quot;,<br>            PromptBuilder(template=text_to_sql_user_prompt_template),<br>        )<br>        self._pipeline.add_component(<br>            &quot;text_to_sql_generator&quot;,<br>            llm_provider.get_generator(system_prompt=text_to_sql_system_prompt),<br>        )<br>        self._pipeline.add_component(&quot;post_processor&quot;, init_generation_post_processor())<br><br>        self._pipeline.connect(<br>            &quot;text_to_sql_prompt_builder.prompt&quot;, &quot;text_to_sql_generator.prompt&quot;<br>        )<br>        self._pipeline.connect(<br>            &quot;text_to_sql_generator.replies&quot;, &quot;post_processor.replies&quot;<br>        )<br>        super().__init__(self._pipeline)<br><br>    @timer<br>    def run(<br>        self,<br>        query: str,<br>        contexts: List[Document],<br>        exclude: List[Dict],<br>        include_outputs_from: List[str] | None = None,<br>    ):<br>        logger.info(&quot;Ask Generation pipeline is running...&quot;)<br>        return self._pipeline.run(<br>            {<br>                &quot;text_to_sql_prompt_builder&quot;: {<br>                    &quot;query&quot;: query,<br>                    &quot;documents&quot;: contexts,<br>                    &quot;alert&quot;: TEXT_TO_SQL_RULES,<br>                    &quot;exclude&quot;: exclude,<br>                }<br>            },<br>            include_outputs_from=(<br>                set(include_outputs_from) if include_outputs_from else None<br>            ),<br>        )</pre><p><strong>Code snippets after rewriting the AI pipeline using Hamilton</strong></p><ul><li>We still define Haystack components in the __init__ method of the Generation class; however, we declare how the components should stick together by describing the connections between components using functions.</li><li>We still define a run method for invoking pipeline execution, but under the hood, it’s Hamilton’s AsyncDriver.</li></ul><pre>## Start of Pipeline<br>@timer<br>def prompt(<br>    query: str,<br>    documents: List[Document],<br>    exclude: List[Dict],<br>    alert: str,<br>    prompt_builder: PromptBuilder,<br>) -&gt; dict:<br>    logger.debug(f&quot;query: {query}&quot;)<br>    logger.debug(f&quot;documents: {documents}&quot;)<br>    logger.debug(f&quot;exclude: {exclude}&quot;)<br>    return prompt_builder.run(<br>        query=query, documents=documents, exclude=exclude, alert=alert<br>    )<br><br><br>@async_timer<br>async def generate(prompt: dict, generator: Any) -&gt; dict:<br>    logger.debug(f&quot;prompt: {prompt}&quot;)<br>    return await generator.run(prompt=prompt.get(&quot;prompt&quot;))<br><br><br>@async_timer<br>async def post_process(generate: dict, post_processor: GenerationPostProcessor) -&gt; dict:<br>    logger.debug(f&quot;generate: {generate}&quot;)<br>    return await post_processor.run(generate.get(&quot;replies&quot;))<br><br><br>## End of Pipeline<br><br><br>class Generation(BasicPipeline):<br>    def __init__(<br>        self,<br>        llm_provider: LLMProvider,<br>        engine: Engine,<br>    ):<br>        self.generator = llm_provider.get_generator(<br>            system_prompt=text_to_sql_system_prompt<br>        )<br>        self.prompt_builder = PromptBuilder(template=text_to_sql_user_prompt_template)<br>        self.post_processor = GenerationPostProcessor(engine=engine)<br><br>        super().__init__(<br>            AsyncDriver({}, sys.modules[__name__], result_builder=base.DictResult())<br>        )<br><br>    @async_timer<br>    async def run(<br>        self,<br>        query: str,<br>        contexts: List[Document],<br>        exclude: List[Dict],<br>    ):<br>        logger.info(&quot;Ask Generation pipeline is running...&quot;)<br>        return await self._pipe.execute(<br>            [&quot;post_process&quot;],<br>            inputs={<br>                &quot;query&quot;: query,<br>                &quot;documents&quot;: contexts,<br>                &quot;exclude&quot;: exclude,<br>                &quot;alert&quot;: TEXT_TO_SQL_RULES,<br>                &quot;generator&quot;: self.generator,<br>                &quot;prompt_builder&quot;: self.prompt_builder,<br>                &quot;post_processor&quot;: self.post_processor,<br>            },<br>        )</pre><h3>Performance Testing Results</h3><p>Now, I am going to show you a series of performance testing results to prove that our architecture rewrite is successful and why we say that our LLM service can handle 1500+ concurrent users?(Wren AI LLM Service is a <a href="https://github.com/tiangolo/fastapi">FastAPI</a> server run with one <a href="https://github.com/encode/uvicorn">uvicorn</a> worker)</p><p>First of all, the performance improvement is substantial:</p><ul><li>The number of requests improved from 16 to 716 — <strong><em>improved over 44x</em></strong></li><li>Average requests per second(a.k.a throughput) improved from 0.8 to 34.3 — <strong><em>improved over 42x</em></strong></li><li>Average response time(a.k.a latency) improved from 7857.19ms to 1679.51ms —<strong><em> improved over 4.5x</em></strong></li></ul><p><strong>Performance statistics before rewriting the AI pipeline using Hamilton</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUHlM8PLxyZXl-Wx8GFgYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4O6rN0E5rqpgCXC3n9hqjw.png" /><figcaption>Performance statistics before rewriting the AI pipeline using Hamilton</figcaption></figure><p><strong>Performance statistics after rewriting the AI pipeline using Hamilton</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y9lgD9r2R6hoJNLxyV5jaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c4eZUgk2BbkLXevHo6lAWg.png" /><figcaption>Performance statistics after rewriting the AI pipeline using Hamilton</figcaption></figure><p>Also, to make sure our AI pipeline is indeed capable of doing asynchronous computation, I’ve built a “simulated API” that mimics AI pipeline behavior to compare with the real AI pipeline API.</p><p>You can easily see the similar performance statistics here:</p><p>Number of requests finished</p><ul><li>Simulated API: 30</li><li>Real AI pipeline API: 31</li></ul><p>Average requests per second(a.k.a throughput)</p><ul><li>Simulated API: 1.6</li><li>Real AI pipeline API: 1.6</li></ul><p>Average response time(a.k.a latency)</p><ul><li>Simulated API: 2.53ms</li><li>Real AI pipeline API: 5.35ms</li></ul><p><strong>Simulated API version</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJr4jxIYVmydnb_JKjcvPg.png" /><figcaption>Requests statistics</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Vntvuu5KsxZy7xZiUuH7Q.png" /><figcaption>Total requests per second</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s2ghI_2jgs0hZalGpX1wTg.png" /><figcaption>Response time</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I0j6Udqg4WD1TzHIRzy42w.png" /><figcaption>Number of users</figcaption></figure><p><strong>Real AI pipeline API version</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cgrY8t5kQmNcEdrYTwe7DA.png" /><figcaption>Requests statistics</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uvqHzMUrbky58PMm2gv0IA.png" /><figcaption>Total requests per second</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wr6_nK99r6HESdtcw2LwZg.png" /><figcaption>Response time</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MW5tb7c9FzijElQhKbHn6w.png" /><figcaption>Number of users</figcaption></figure><p>You can see that they both have similar performance statistics, so we believe implementing the third version architecture is successful!</p><p>Finally, I will share with you how we can infer that our LLM service can handle 1500+ concurrent users. Since I’ve shown you that the performance statistics between the simulated API and the real API are similar. Thus I hypothesize that if we can prove the simulated API version can handle 1500+ concurrent users, then I can infer that the real API version can also achieve the same results. (<em>I assume the LLM can handle 1500+ concurrent users here</em>)</p><p>You can see that the performance statistics are quite healthy!</p><ul><li>Number of requests finished: 16358</li><li>Average requests per second(a.k.a throughput): 267.5</li><li>Average response time(a.k.a latency): 92.52ms</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gxrive1u2vh2U8PvJeOEkw.png" /><figcaption>Request statistics</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AAi8mBh6l10iKmZh2Ittwg.png" /><figcaption>Performance chart</figcaption></figure><p><em>Notes: the tests were all done on my MacBook Pro(14-inch, 2023 with Apple M2 Pro, 16GB Memory)</em></p><h3><strong>Final Remarks</strong></h3><p>I hope this article can help you understand some issues you may encounter while building generative AI applications. I also hope the tools I mentioned in this article can help you solve issues more easily! These are all great open-source software tools we can leverage and learn from!</p><p>Feel free to leave a comment in this post if you have any thoughts you would like to discuss on the topic. Thanks!</p><p>Thank you <a href="https://www.linkedin.com/in/chilijung">Howard Chi</a>, <a href="https://www.linkedin.com/in/wwwy3y3">William Chang</a>, who reviewed the post and provided feedback!</p><p>👉 GitHub: <a href="https://github.com/Canner/WrenAI">https://github.com/Canner/WrenAI</a></p><p>👉 X: <a href="https://twitter.com/getwrenai">https://twitter.com/getwrenai</a></p><p>👉 Medium: <a href="https://blog.getwren.ai/">https://blog.getwren.ai</a></p><p>Don’t forget to give <a href="https://github.com/canner/wrenai">⭐ Wren AI a star on GitHub ⭐ </a>if you’ve enjoyed this article, and as always, thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ba5c121afc3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wrenai/how-do-we-rewrite-wren-ai-llm-service-to-support-1500-concurrent-users-online-9ba5c121afc3">How do we rewrite Wren AI LLM Service to support 1500+ concurrent users online?</a> was originally published in <a href="https://medium.com/wrenai">Wren AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>