<?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 Tanmaypatil on Medium]]></title>
        <description><![CDATA[Stories by Tanmaypatil on Medium]]></description>
        <link>https://medium.com/@tanmaypatil3151?source=rss-941d5fc0579------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6GoozBGmnNr5Aiv4</url>
            <title>Stories by Tanmaypatil on Medium</title>
            <link>https://medium.com/@tanmaypatil3151?source=rss-941d5fc0579------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 15:18:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tanmaypatil3151/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[Building a Text Generation Streaming Server with ModelQ and FastAPI]]></title>
            <link>https://medium.com/@tanmaypatil3151/building-a-text-generation-streaming-server-with-modelq-and-fastapi-8bdbd7d74f28?source=rss-941d5fc0579------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bdbd7d74f28</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Tanmaypatil]]></dc:creator>
            <pubDate>Thu, 10 Apr 2025 09:03:41 GMT</pubDate>
            <atom:updated>2025-04-10T09:53:20.085Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0d2VFDV0uyQG-Y961mB4tg.png" /></figure><p>In the rapidly evolving landscape of artificial intelligence, real-time text generation has become a cornerstone for applications ranging from chatbots to content creation tools. Leveraging the power of OpenAI’s GPT-2 model, developers can create responsive and efficient text generation services. This blog post delves into building a text generation streaming server using <a href="https://github.com/ModelsLab/modelq">ModelQ</a>, <a href="https://fastapi.tiangolo.com/">FastAPI</a>, and the GPT-2 model from <a href="https://huggingface.co/openai-community/gpt2">Hugging Face</a>.</p><h3>Introduction to ModelQ and FastAPI</h3><p><a href="https://github.com/ModelsLab/modelq">ModelQ</a> is an innovative framework designed to streamline the deployment of machine learning models, facilitating seamless integration into production environments. When combined with <a href="https://fastapi.tiangolo.com/">FastAPI</a>, a modern web framework for building APIs with Python 3.7+, developers can create high-performance, asynchronous web services with minimal boilerplate code.</p><h3>Harnessing the Power of GPT-2</h3><p><a href="https://huggingface.co/openai-community/gpt2">GPT-2</a> is a transformer-based language model developed by OpenAI, renowned for its ability to generate coherent and contextually relevant text. By integrating GPT-2 into our server, we can provide users with real-time text generation capabilities, enhancing applications such as chat interfaces, content generators, and more.</p><h3>Project Overview</h3><p>Our project comprises three primary components:​</p><ol><li><strong>app.py</strong>: Defines the FastAPI endpoints to handle incoming requests and stream responses.​</li><li><strong>tasks.py</strong>: Contains the ModelQ tasks responsible for loading the GPT-2 model and generating text.​</li><li><strong>runner.py</strong>: Initiates the ModelQ worker to process tasks asynchronously.​</li></ol><p>The complete code is available in the <a href="https://github.com/ModelsLab/modelq/tree/main/examples/text-streaming-server">ModelQ GitHub repository</a>.</p><h3>Setting Up the Streaming Server</h3><h4>1. FastAPI Endpoints (app.py)</h4><p>In app.py, we set up a FastAPI application with an endpoint that handles text generation requests. The /completion/{question} endpoint receives a query parameter and returns a streaming response:</p><pre># app.py<br>from tasks import modelq_app, stream<br>from fastapi import FastAPI<br>from fastapi.responses import StreamingResponse<br><br># Initialize the FastAPI application<br>app = FastAPI()<br><br># Define a GET endpoint that takes a &#39;question&#39; as a path parameter<br>@app.get(&quot;/completion/{question}&quot;)<br>async def completion(question: str):<br>    # Create a ModelQ task for streaming the response<br>    task = stream(question)<br>    # Return a streaming response using the task&#39;s stream generator<br>    return StreamingResponse(<br>        task.get_stream(modelq_app.redis_client), media_type=&quot;text/event-stream&quot;<br>    )</pre><p><strong>Explanation:</strong></p><ul><li>We import the necessary modules and functions, including modelq_app and stream from tasks.py, and FastAPI components.​</li><li>An instance of the FastAPI application is created.​</li><li>The /completion/{question} endpoint is defined to handle GET requests with a question parameter.​</li><li>Within the endpoint function, we create a ModelQ task by calling the stream function with the provided question.​</li><li>We return a StreamingResponse that streams the generated text in real-time using the task&#39;s stream generator.</li></ul><p>This setup ensures that clients receive generated text tokens in real-time as they are produced by the model</p><h4>2. ModelQ Tasks (tasks.py)</h4><p>The tasks.py file is pivotal, as it defines the ModelQ tasks and manages the GPT-2 model:</p><pre># tasks.py<br>from modelq import ModelQ<br>from modelq.app.middleware import Middleware<br>from redis import Redis<br>from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer<br><br># Initialize the Redis client<br>redis_client = Redis(host=&quot;localhost&quot;, port=6379, db=0)<br># Create an instance of the ModelQ application<br>modelq_app = ModelQ(redis_client=redis_client)<br><br># Define a class to manage the GPT-2 model and tokenizer<br>class Model:<br>    def __init__(self):<br>        self.model = None<br>        self.tok = None<br><br>    # Method to load the GPT-2 model and tokenizer<br>    def load_model(self):<br>        self.tok = AutoTokenizer.from_pretrained(&quot;openai-community/gpt2&quot;)<br>        self.model = AutoModelForCausalLM.from_pretrained(&quot;openai-community/gpt2&quot;)<br><br># Instantiate the Model class<br>MODEL = Model()<br><br># Define a middleware to load the model before the worker starts<br>class ModelInit(Middleware):<br>    def before_worker_boot(self):<br>        MODEL.load_model()<br><br># Assign the middleware to the ModelQ application<br>modelq_app.middleware = ModelInit()<br><br># Define a ModelQ task for streaming text generation<br>@modelq_app.task(timeout=15, stream=True)<br>def stream(params):<br>    # Tokenize the input parameters<br>    inputs = MODEL.tok([params], return_tensors=&quot;pt&quot;)<br>    streamer = TextIteratorStreamer(MODEL.tok)<br>    generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=20)<br>    thread = Thread(target=MODEL.model.generate, kwargs=generation_kwargs)<br>    thread.start()<br><br>    for new_text in streamer:<br>        yield new_text</pre><p><strong>Explanation:</strong></p><ul><li>We import necessary modules, including ModelQ components, Redis client, and Hugging Face’s Transformers library.​</li><li>A Redis client is initialized to facilitate task queuing and result storage.​</li><li>An instance of the ModelQ application is created, associating it with the Redis client.​</li><li>The Model class is defined to manage the GPT-2 model and tokenizer, with a method load_model to load them from the Hugging Face model hub.​</li><li>An instance of the Model class, MODEL, is created to be used across tasks.</li></ul><p>Here, we initialize the GPT-2 model and tokenizer, define a middleware to load the model before the worker starts, and create a streaming task that generates text based on input parameters.</p><h4>3. Running the ModelQ Worker (runner.py)</h4><p>The runner.py script starts the ModelQ worker, ensuring it remains active to process incoming tasks:</p><pre># runner.py<br>from tasks import modelq_app<br>import time<br><br>if __name__ == &quot;__main__&quot;:<br>    modelq_app.start_workers()<br>    try:<br>        while True:<br>            time.sleep(1)<br>    except KeyboardInterrupt:<br>        print(&quot;\nGracefully shutting down...&quot;)</pre><p>This script maintains the worker’s operation, allowing it to handle text generation requests asynchronously.</p><p>​To set up and run your GPT-2 text generation streaming server using ModelQ and FastAPI, follow these steps:</p><h4>1.Start the FastAPI Application (app.py)</h4><p>Begin by launching the FastAPI application using Uvicorn. Open a terminal, navigate to the directory containing your app.py file, and execute the following command:</p><pre>uvicorn app:app --host 127.0.0.1 --port 8000</pre><p><strong>Explanation:</strong></p><ul><li>uvicorn app:app: This command tells Uvicorn to run the app instance from the app.py file.​</li><li>--host 127.0.0.1: Specifies that the server should listen on the local host.​</li><li>--port 8000: Sets the port number to 8000.</li></ul><p>Once the server is running, you should see output indicating that Uvicorn is serving the application at <a href="http://127.0.0.1:8000.">http://127.0.0.1:8000.</a></p><h4>2.Start the ModelQ Worker (runner.py)</h4><p>In a separate terminal window or tab, navigate to the same directory and run the ModelQ worker by executing:</p><pre>python runner.py</pre><p>The worker will initialize and begin processing tasks, ready to handle text generation requests.</p><h4>3.Access the API Endpoints</h4><p>With both the FastAPI application and the ModelQ worker running, you can now interact with the text generation API. Open your browser and navigate to the following URL to access the interactive API documentation:</p><pre>http://127.0.0.1:8000/docs</pre><p>Here, you can test the /completion/{question} endpoint by providing a query parameter and observing the streaming response.</p><p><strong>Note:</strong></p><ul><li>Ensure that both the FastAPI application and the ModelQ worker are running simultaneously in separate terminal instances.​</li><li>If you encounter any issues, verify that all dependencies are installed and that there are no conflicts with the specified host and port.</li></ul><p>After running both scripts you should able to see following things in both terminals :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*PoIKh_Oi8hi9LFeKGfR6Cw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XrGw20-A2r1wgvLiixNiKA.png" /></figure><p>After making get request in browser you should be able to see generated text streaming in output like following :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*zr90hnikxswXeTN3Wp3e2w.png" /></figure><p>This real-time interaction is achieved through token streaming, where the server returns tokens one by one as the model generates them. Such an approach enhances user engagement by reducing latency and providing a more dynamic experience.</p><p>Thank You for reading this tutorial . I hope you enjoyed it 😊.</p><p>Also Don’t forget to star Modelq on github here (<a href="https://github.com/ModelsLab/modelq">https://github.com/ModelsLab/modelq</a>)</p><h3>Contributing to ModelQ</h3><p>The <a href="https://github.com/ModelsLab/modelq">ModelQ project</a> is open-source and thrives on community contributions. Developers are encouraged to explore the repository, provide feedback, report issues, and contribute enhancements. By collaborating, we can advance the capabilities of ModelQ and create more robust AI applications.</p><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P7kA31fGVBOudw-r1pCO_Q.png" /></figure><p>Building a text generation streaming server using ModelQ, FastAPI, and GPT-2 offers a powerful solution for real-time AI applications. This setup ensures efficient handling of text generation requests, providing users with immediate and contextually relevant responses. We invite you to delve into the <a href="https://github.com/ModelsLab/modelq">ModelQ repository</a>, contribute to its development, and star the project to show your support.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bdbd7d74f28" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>