<?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 Abhishek Nath Tiwari on Medium]]></title>
        <description><![CDATA[Stories by Abhishek Nath Tiwari on Medium]]></description>
        <link>https://medium.com/@abhint2603?source=rss-fd6e8dab532------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0eTrpnzgmtPTzXgx0FWW7A.png</url>
            <title>Stories by Abhishek Nath Tiwari on Medium</title>
            <link>https://medium.com/@abhint2603?source=rss-fd6e8dab532------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 05:25:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhint2603/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[LLM APIs, Streaming, and Conversation State: Building Responsive AI Applications]]></title>
            <link>https://medium.com/@abhint2603/llm-apis-streaming-and-conversation-state-building-responsive-ai-applications-d941216ed711?source=rss-fd6e8dab532------2</link>
            <guid isPermaLink="false">https://medium.com/p/d941216ed711</guid>
            <dc:creator><![CDATA[Abhishek Nath Tiwari]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 11:31:45 GMT</pubDate>
            <atom:updated>2026-11-17T11:31:45.264Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f-NxNjb9mCD0VNgby0rmNw.png" /></figure><p>Imagine opening an AI chatbot and asking:</p><p>“Explain how a vector database works.”</p><p>You press Enter.</p><p>Nothing happens for five seconds.</p><p>Then suddenly, the entire answer appears on your screen.</p><p>Now imagine a different experience. The answer starts appearing almost immediately, word by word, just like ChatGPT.</p><p>Which experience feels better?</p><p>The second one.</p><p>But there’s more happening behind that simple interface than just generating text.</p><p>A production-ready LLM application needs to handle API requests, stream responses, maintain conversation history, manage context windows, and recover from errors.</p><p>In this article, we’ll understand these concepts and build a practical Python application using the OpenAI Responses API.</p><p>By the end, you’ll understand how to:</p><ul><li>Communicate with an LLM through an API.</li><li>Understand the request-response lifecycle.</li><li>Stream model responses in real time.</li><li>Maintain context across multiple conversations.</li><li>Use previous_response_id to continue conversations.</li><li>Build a basic streaming chatbot using Streamlit.</li><li>Handle token limits, errors, and application state.</li></ul><p>Let’s get started.</p><h3>1. What is an LLM API?</h3><p>An LLM API allows an application to communicate with a language model hosted by an AI provider.</p><p>Instead of running a large language model on your own machine, you send a request to a remote service and receive a generated response.</p><p>For example, imagine building a customer support chatbot.</p><p>A user asks:</p><p>“How can I reset my account password?”</p><p>Your application sends the question to an LLM API.</p><p>The model processes the request and returns an answer.</p><p>The basic architecture looks like this:</p><pre>USER<br>          |<br>          v<br>    Python Application<br>          |<br>          v<br>       LLM API<br>          |<br>          v<br>    Language Model<br>          |<br>          v<br>    Generated Response<br>          |<br>          v<br>    Python Application<br>          |<br>          v<br>        USER</pre><p>The application is responsible for collecting the user’s input, calling the API, processing the result, and displaying the answer.</p><p>The model is responsible for generating the response.</p><h3>What happens inside an API request?</h3><p>A typical request contains:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*IUWeOsESuFNqZg8ZawoV_A.png" /></figure><p>Different providers expose different API formats, but the underlying idea is similar.</p><h3>Your first LLM API request</h3><p>Let’s use Python and the OpenAI SDK.</p><p>Install the required package:</p><pre>pip install openai</pre><p>Set your API key as an environment variable.</p><pre>export OPENAI_API_KEY=&quot;your-api-key&quot;<br>export OPENAI_MODEL=&quot;your-supported-model&quot;</pre><p>On Windows PowerShell:</p><pre>$env:OPENAI_API_KEY=&quot;your-api-key&quot;<br>$env:OPENAI_MODEL=&quot;your-supported-model&quot;</pre><p>Now create your first application:</p><pre>import os<br>from openai import OpenAI</pre><pre>client = OpenAI()</pre><pre>model = os.environ[&quot;OPENAI_MODEL&quot;]</pre><pre>response = client.responses.create(<br>    model=model,<br>    input=&quot;Explain vector databases in simple terms.&quot;<br>)</pre><pre>print(response.output_text)</pre><p>That’s it!</p><p>You have successfully connected a Python application to an LLM.</p><p>Notice that we are using the Responses API:</p><pre>client.responses.create()</pre><p>It provides a unified interface for generating text, working with tools, handling multimodal inputs, and managing conversation state.</p><p>For more details:</p><p><a href="https://developers.openai.com/api/docs/guides/text">OpenAI Responses API documentation</a></p><h3>2. Understanding the Request-Response Lifecycle</h3><p>Before implementing streaming, let’s understand what happens when an application calls an LLM API.</p><p>Consider this request:</p><pre>response = client.responses.create(<br>    model=model,<br>    input=&quot;Explain how Redis works.&quot;<br>)</pre><p>The lifecycle looks something like this:</p><pre>1. User submits a question<br>          |<br>          v<br>2. Application validates input<br>          |<br>          v<br>3. Application sends API request<br>          |<br>          v<br>4. API receives the request<br>          |<br>          v<br>5. Model processes the input<br>          |<br>          v<br>6. Model generates output<br>          |<br>          v<br>7. API returns the response<br>          |<br>          v<br>8. Application displays the answer</pre><p>In a normal non-streaming request, your application waits until the response is ready.</p><p>Only then does the user receive the generated output.</p><p>This is perfectly acceptable for short responses.</p><p>However, what happens when the model takes several seconds to generate a long answer?</p><p>The user sees a loading indicator and waits.</p><p>This brings us to streaming.</p><h3>3. What is LLM Streaming?</h3><p>Streaming means receiving a model’s response incrementally instead of waiting for the complete response.</p><p>Let’s understand the difference.</p><h3>Without streaming</h3><p>Imagine the model generates this response:</p><p>“Vector databases store numerical representations of data and allow similarity searches.”</p><p>The application receives the complete response only after generation finishes.</p><pre>Request sent<br>     |<br>     v<br>Model generates complete answer<br>     |<br>     v<br>Response received<br>     |<br>     v<br>Display complete answer</pre><h3>With streaming</h3><p>The model sends parts of the response as they become available.</p><pre>Request sent<br>     |<br>     v<br>Model starts generating<br>     |<br>     +----&gt; &quot;Vector&quot;<br>     |<br>     +----&gt; &quot; databases&quot;<br>     |<br>     +----&gt; &quot; store&quot;<br>     |<br>     +----&gt; &quot; numerical&quot;<br>     |<br>     +----&gt; &quot; representations...&quot;<br>     |<br>     v<br>Response completed</pre><p>The user sees the answer gradually appearing on the screen.</p><p>This improves the perceived responsiveness of an application.</p><h3>How does streaming work technically?</h3><p>Many LLM APIs support streaming through Server-Sent Events (SSE).</p><p>SSE is a mechanism that allows a server to send events to a client over an HTTP connection.</p><p>Instead of returning one complete response, the server sends a sequence of events.</p><p>For example:</p><pre>data: {&quot;delta&quot;: &quot;Vector&quot;}</pre><pre>data: {&quot;delta&quot;: &quot; databases&quot;}</pre><pre>data: {&quot;delta&quot;: &quot; store&quot;}</pre><pre>data: {&quot;delta&quot;: &quot; numerical&quot;}</pre><pre>data: {&quot;delta&quot;: &quot; representations&quot;}</pre><p>These are illustrative event payloads, not the exact wire format of every provider.</p><p>Your application reads each event and updates the user interface.</p><h3>Implement streaming in Python</h3><p>The OpenAI Responses API supports streaming.</p><p>Let’s modify our earlier example.</p><pre>import os<br>from openai import OpenAI</pre><pre>client = OpenAI()<br>model = os.environ[&quot;OPENAI_MODEL&quot;]</pre><pre>stream = client.responses.create(<br>    model=model,<br>    input=&quot;Explain how vector databases work.&quot;,<br>    stream=True<br>)</pre><pre>for event in stream:<br>    if event.type == &quot;response.output_text.delta&quot;:<br>        print(event.delta, end=&quot;&quot;, flush=True)</pre><pre>    elif event.type == &quot;response.completed&quot;:<br>        print(&quot;\n\nResponse completed.&quot;)</pre><p>Let’s understand the important part:</p><pre>stream=True</pre><p>This tells the API that we want incremental events.</p><p>Next:</p><pre>for event in stream:</pre><p>We iterate over the events received from the API.</p><p>Finally:</p><pre>if event.type == &quot;response.output_text.delta&quot;:</pre><p>This event indicates that a new piece of generated text is available.</p><p>We print that text immediately.</p><p><strong>Important:</strong> A stream contains different event types. Your application should handle completion and errors rather than assuming every event contains text.</p><p>For the complete event reference:</p><p><a href="https://developers.openai.com/api/docs/guides/streaming-responses">OpenAI Streaming API documentation</a></p><h3>4. Streaming vs Non-Streaming: What’s the Difference?</h3><p>Both approaches generate model responses, but they offer different user experiences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*i7y6dDhSMlf8fU_7_cQ7bw.png" /></figure><h3>When should you use streaming?</h3><p>Streaming is particularly useful for:</p><ul><li>AI chatbots.</li><li>AI writing assistants.</li><li>Coding assistants.</li><li>Long-form content generation.</li><li>Interactive AI applications.</li></ul><p>Non-streaming is often sufficient for:</p><ul><li>Short classification tasks.</li><li>Background processing.</li><li>Structured data extraction.</li><li>Simple API integrations.</li><li>Tasks where the application needs the complete output before proceeding.</li></ul><p>One important point:</p><p><strong>Streaming does not necessarily make the model generate tokens faster.</strong></p><p>It allows your application to display generated content before the entire response is ready.</p><p>That improves perceived latency, not necessarily total generation time.</p><h3>5. What is Conversation State?</h3><p>Now let’s solve another important problem.</p><p>Imagine you are using an AI chatbot.</p><p>You ask:</p><p>“Who developed Python?”</p><p>The assistant replies:</p><p>“Python was created by Guido van Rossum.”</p><p>Then you ask:</p><p>“When was it first released?”</p><p>A basic LLM API request might not know what “it” refers to unless the application provides the previous conversation context.</p><p>This happens because an individual model request is generally processed using the input supplied for that request.</p><p>The application needs a way to maintain conversation state.</p><p>Conversation state means preserving the relevant context from previous interactions so the model can understand follow-up questions.</p><p>For example:</p><pre>USER:<br>Who developed Python?</pre><pre>ASSISTANT:<br>Python was created by Guido van Rossum.</pre><pre>USER:<br>When was it first released?</pre><pre>ASSISTANT:<br>Python was first released in 1991.</pre><p>The assistant can answer the second question correctly because it has access to the earlier context.</p><h3>How can we maintain conversation state?</h3><p>There are three common approaches.</p><ol><li>Manually maintain conversation history.</li><li>Use previous_response_id.</li><li>Use the Conversations API.</li></ol><p>Let’s understand each one.</p><h3>6. Approach 1: Manually Maintaining Conversation History</h3><p>The simplest approach is to store previous user and assistant messages in a list.</p><p>For example:</p><pre>conversation = [<br>    {<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: &quot;Who developed Python?&quot;<br>    },<br>    {<br>        &quot;role&quot;: &quot;assistant&quot;,<br>        &quot;content&quot;: &quot;Python was created by Guido van Rossum.&quot;<br>    },<br>    {<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: &quot;When was it first released?&quot;<br>    }<br>]</pre><p>When the next question arrives, we send the relevant conversation history along with it.</p><p>Here’s a working example:</p><pre>from openai import OpenAI<br>import os</pre><pre>client = OpenAI()<br>model = os.environ[&quot;OPENAI_MODEL&quot;]</pre><pre>conversation = []</pre><pre>def chat(user_message):</pre><pre>    conversation.append({<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: user_message<br>    })</pre><pre>    response = client.responses.create(<br>        model=model,<br>        input=conversation<br>    )</pre><pre>    assistant_message = response.output_text</pre><pre>    conversation.append({<br>        &quot;role&quot;: &quot;assistant&quot;,<br>        &quot;content&quot;: assistant_message<br>    })</pre><pre>    return assistant_message<br></pre><pre>print(chat(&quot;Who developed Python?&quot;))</pre><pre>print(chat(&quot;When was it first released?&quot;))</pre><h3>Advantages</h3><ul><li>Full control over conversation history.</li><li>Easy to understand and implement.</li><li>You can remove irrelevant messages.</li><li>You can summarize older conversations.</li></ul><h3>Disadvantages</h3><ul><li>You must manage history yourself.</li><li>The input grows as the conversation continues.</li><li>You need to handle persistence.</li><li>Large conversations can exceed the context window.</li></ul><p>This approach is useful when you need complete control over the context sent to the model.</p><p>For production applications, make sure you understand the provider’s response-item requirements. The simplified example above is intended for ordinary text exchanges.</p><h3>7. Approach 2: Using previous_response_id</h3><p>The OpenAI Responses API provides another convenient way to maintain conversation context.</p><p>Instead of manually sending the entire conversation history, you can reference the previous response using:</p><pre>previous_response_id</pre><p>Let’s see how it works.</p><h3>First request</h3><pre>first_response = client.responses.create(<br>    model=model,<br>    input=&quot;Who developed Python?&quot;<br>)</pre><pre>print(first_response.output_text)</pre><p>The response contains an ID.</p><pre>first_response.id</pre><p>Conceptually, this ID identifies the previous response.</p><h3>Second request</h3><p>Now we can continue the conversation:</p><pre>second_response = client.responses.create(<br>    model=model,<br>    previous_response_id=first_response.id,<br>    input=&quot;When was it first released?&quot;<br>)</pre><pre>print(second_response.output_text)</pre><p>The model receives the context from the previous response and can understand the follow-up question.</p><p>The flow looks like this:</p><pre>USER:<br>Who developed Python?<br>       |<br>       v<br>   RESPONSE 1<br>       |<br>       v<br>   response_id<br>       |<br>       v<br>USER:<br>When was it first released?<br>       |<br>       v<br>   RESPONSE 2<br>       |<br>       v<br>Previous context available</pre><h3>Building a reusable conversation function</h3><p>Let’s turn this into a small chat application.</p><pre>import os<br>from openai import OpenAI</pre><pre>client = OpenAI()<br>model = os.environ[&quot;OPENAI_MODEL&quot;]</pre><pre>previous_response_id = None</pre><pre>def chat(user_message):</pre><pre>    global previous_response_id</pre><pre>    response = client.responses.create(<br>        model=model,<br>        instructions=(<br>            &quot;You are a helpful programming assistant. &quot;<br>            &quot;Explain technical concepts clearly.&quot;<br>        ),<br>        previous_response_id=previous_response_id,<br>        input=user_message<br>    )</pre><pre>    previous_response_id = response.id</pre><pre>    return response.output_text<br></pre><pre>while True:</pre><pre>    user_message = input(&quot;You: &quot;)</pre><pre>    if user_message.lower() == &quot;exit&quot;:<br>        break</pre><pre>    answer = chat(user_message)</pre><pre>    print(&quot;Assistant:&quot;, answer)</pre><p>This is a simple conversational application.</p><p>Each new response references the previous response.</p><p><strong>Important:</strong> When chaining responses, resend your stable instructions on each request. Top-level instructions from an earlier response are not automatically carried forward through previous_response_id.</p><p>Also, previous input tokens in the response chain still count toward input usage. Conversation chaining does not make the history free.</p><h3>8. Approach 3: Using the Conversations API</h3><p>What if you want conversations to continue across multiple sessions?</p><p>For example:</p><ul><li>A user starts chatting on a laptop.</li><li>They close the browser.</li><li>They return the next day.</li><li>They expect their previous conversation to remain available.</li></ul><p>A simple Python variable cannot provide that functionality.</p><p>The Conversations API provides a persistent conversation object that can be used with the Responses API.</p><h3>Step 1: Create a conversation</h3><pre>conversation = client.conversations.create()</pre><pre>print(conversation.id)</pre><p>This creates a conversation and returns its identifier.</p><h3>Step 2: Send the first message</h3><pre>response = client.responses.create(<br>    model=model,<br>    conversation=conversation.id,<br>    input=&quot;Explain what an API is.&quot;<br>)</pre><pre>print(response.output_text)</pre><h3>Step 3: Continue the same conversation</h3><pre>response = client.responses.create(<br>    model=model,<br>    conversation=conversation.id,<br>    input=&quot;Give me a real-world example.&quot;<br>)</pre><pre>print(response.output_text)</pre><p>The same conversation identifier is reused.</p><p>The conversation object maintains its associated items across subsequent requests.</p><h3>previous_response_id vs Conversations API</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*RrUmiMWQbZrsERv6r7GR-Q.png" /></figure><p>Which one should you use?</p><p>For a simple chatbot, previous_response_id can be convenient.</p><p>For applications requiring durable conversations across sessions, the Conversations API is worth considering.</p><p>For applications with strict data-retention requirements, review the provider’s storage and retention controls before choosing a stateful approach.</p><p>Documentation:</p><p><a href="https://developers.openai.com/api/docs/guides/conversation-state">OpenAI Conversation State Guide</a></p><h3>9. Build a Streaming Chatbot with Streamlit</h3><p>So far, we’ve learned how to:</p><ul><li>Call an LLM API.</li><li>Stream responses.</li><li>Maintain conversation context.</li></ul><p>Now let’s combine these concepts into a small application.</p><p>We’ll build a chatbot using:</p><ul><li>Python</li><li>OpenAI SDK</li><li>Streamlit</li><li>Responses API</li><li>Streaming</li><li>previous_response_id</li></ul><h3>Step 1: Install dependencies</h3><pre>pip install openai streamlit</pre><h3>Step 2: Create the application</h3><p>Create a file called:</p><pre>app.py</pre><p>Add the following code:</p><pre>import os<br>import streamlit as st<br>from openai import OpenAI</pre><pre>client = OpenAI()</pre><pre>MODEL = os.environ[&quot;OPENAI_MODEL&quot;]</pre><pre>st.set_page_config(<br>    page_title=&quot;GenAI Chatbot&quot;,<br>    page_icon=&quot;🤖&quot;<br>)</pre><pre>st.title(&quot;🤖 GenAI Chatbot&quot;)</pre><pre>st.caption(<br>    &quot;A streaming chatbot powered by the OpenAI Responses API&quot;<br>)</pre><pre># Initialize session state</pre><pre>if &quot;messages&quot; not in st.session_state:<br>    st.session_state.messages = []</pre><pre>if &quot;previous_response_id&quot; not in st.session_state:<br>    st.session_state.previous_response_id = None<br></pre><pre># Display previous messages</pre><pre>for message in st.session_state.messages:</pre><pre>    with st.chat_message(message[&quot;role&quot;]):<br>        st.markdown(message[&quot;content&quot;])<br></pre><pre># Capture user input</pre><pre>if user_input := st.chat_input(&quot;Ask something...&quot;):</pre><pre>    st.session_state.messages.append({<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: user_input<br>    })</pre><pre>    with st.chat_message(&quot;user&quot;):<br>        st.markdown(user_input)</pre><pre>    with st.chat_message(&quot;assistant&quot;):</pre><pre>        placeholder = st.empty()<br>        full_response = &quot;&quot;</pre><pre>        try:</pre><pre>            stream = client.responses.create(<br>                model=MODEL,<br>                instructions=(<br>                    &quot;You are a helpful AI assistant. &quot;<br>                    &quot;Give clear and concise answers.&quot;<br>                ),<br>                previous_response_id=(<br>                    st.session_state.previous_response_id<br>                ),<br>                input=user_input,<br>                stream=True<br>            )</pre><pre>            for event in stream:</pre><pre>                if event.type == &quot;response.output_text.delta&quot;:</pre><pre>                    full_response += event.delta</pre><pre>                    placeholder.markdown(<br>                        full_response + &quot;▌&quot;<br>                    )</pre><pre>                elif event.type == &quot;response.completed&quot;:</pre><pre>                    st.session_state.previous_response_id = (<br>                        event.response.id<br>                    )</pre><pre>            placeholder.markdown(full_response)</pre><pre>            st.session_state.messages.append({<br>                &quot;role&quot;: &quot;assistant&quot;,<br>                &quot;content&quot;: full_response<br>            })</pre><pre>        except Exception as error:</pre><pre>            placeholder.error(<br>                &quot;Something went wrong while generating the response.&quot;<br>            )</pre><pre>            st.error(str(error))</pre><h3>Step 3: Run the application</h3><pre>streamlit run app.py</pre><p>Open the local URL shown in your terminal.</p><p>You should now have a chatbot where:</p><ol><li>Users can enter questions.</li><li>Responses appear incrementally.</li><li>Previous messages remain visible during the session.</li><li>The application maintains conversation context using previous_response_id.</li></ol><h3>Understanding Streamlit session state</h3><p>One important part of this application is:</p><pre>st.session_state</pre><p>Streamlit reruns the application script when users interact with the interface.</p><p>Without session state, normal Python variables would be recreated during those reruns.</p><p>We use session state to preserve:</p><pre>st.session_state.messages</pre><p>This stores the messages displayed in the current Streamlit session.</p><p>And:</p><pre>st.session_state.previous_response_id</pre><p>This stores the ID needed to continue the conversation.</p><p><strong>Important:</strong> Streamlit session state is not permanent storage. It does not automatically provide conversation history across different devices or future sessions. A production application should store conversation metadata and ownership in a persistent database.</p><h3>10. Understanding Context Windows and Token Usage</h3><p>Now comes another important production concern.</p><p>Imagine a user has been chatting with your application for several hours.</p><p>The conversation contains hundreds of messages.</p><p>Should you send the entire conversation to the model every time?</p><p>Not necessarily.</p><p>Every model has a context window.</p><p>A context window represents the maximum number of tokens that can be considered in a request, including input, generated output, and, for applicable models, reasoning tokens.</p><p>For example, imagine a hypothetical context window of 8,000 tokens.</p><p>Your request might use:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*AdilHJ5bqiyYJ0_tmtGCSQ.png" /></figure><p>These numbers are illustrative.</p><p>As conversations become longer, less capacity remains for new input and output.</p><h3>How can we manage context?</h3><p>There are several practical approaches.</p><p><strong>1. Limit conversation history</strong></p><p>Keep only the most relevant recent messages.</p><p><strong>2. Summarize older conversations</strong></p><p>Convert a long conversation into a shorter summary and use that summary as context.</p><p><strong>3. Remove irrelevant information</strong></p><p>Not every message needs to remain available forever.</p><p><strong>4. Monitor token usage</strong></p><p>Track input and output tokens to understand cost and context consumption.</p><p><strong>5. Retrieve information when needed</strong></p><p>For larger knowledge bases, use retrieval-augmented generation (RAG) instead of repeatedly sending large documents in every request.</p><p>We’ll explore RAG in detail in upcoming articles.</p><h3>Does previous_response_id eliminate token costs?</h3><p>No.</p><p>Even when using previous_response_id, previous input tokens in the response chain are still billed as input tokens.</p><p>It simplifies conversation-state management, but it does not eliminate the cost of processing context.</p><p>This is an important consideration when designing AI applications at scale.</p><h3>11. Production Engineering: What Can Go Wrong?</h3><p>A basic chatbot is relatively easy to build.</p><p>A reliable chatbot is a different challenge.</p><p>Let’s discuss some problems that appear when real users start using your application.</p><h3>Problem 1: API timeouts</h3><p>Sometimes the model takes longer than expected to respond.</p><p>Your application should configure sensible timeouts and handle failures gracefully.</p><h3>Problem 2: Network disconnections</h3><p>A streaming connection can break while the model is generating a response.</p><p>Your application should detect incomplete responses and communicate the situation to the user.</p><p>Do not assume that a partially received answer is a completed answer.</p><h3>Problem 3: Rate limits</h3><p>AI providers may limit the number of requests or tokens your application can send within a given period.</p><p>Useful strategies include:</p><ul><li>Exponential backoff.</li><li>Request throttling.</li><li>Queue-based processing.</li><li>Usage monitoring.</li></ul><h3>Problem 4: Context growth</h3><p>Long conversations can increase input token usage and eventually exceed model limits.</p><p>Implement history trimming, summarization, or retrieval.</p><h3>Problem 5: Duplicate requests</h3><p>Users may click the Send button multiple times.</p><p>Your backend should avoid unintentionally creating duplicate operations, especially when the model can call external tools or trigger business actions.</p><h3>Problem 6: Sensitive conversation data</h3><p>Conversation history may contain personal or confidential information.</p><p>You should:</p><ul><li>Protect API keys.</li><li>Restrict access to conversations.</li><li>Avoid exposing one user’s conversation to another.</li><li>Define retention policies.</li><li>Avoid logging sensitive content unnecessarily.</li><li>Understand your AI provider’s data storage and retention settings.</li></ul><h3>Problem 7: Streaming moderation</h3><p>When an application displays partial output, the user may see content before the entire response is available for evaluation.</p><p>Production applications should consider moderation and safety checks appropriate to their use case.</p><h3>12. How I Would Design Conversation Management in Production</h3><p>Let’s put everything together.</p><p>Imagine building an AI knowledge assistant for an organisation.</p><p>It should support:</p><ul><li>Multiple users.</li><li>Multiple conversations per user.</li><li>Streaming responses.</li><li>Conversation history.</li><li>Persistent storage.</li><li>Authentication.</li><li>Monitoring.</li></ul><p>A simplified architecture could look like this:</p><pre>                 USER<br>                   |<br>                   v<br>             Frontend UI<br>                   |<br>                   v<br>              Backend API<br>                   |<br>          +--------+--------+<br>          |                 |<br>          v                 v<br>    Authentication    Conversation DB<br>          |                 |<br>          +--------+--------+<br>                   |<br>                   v<br>             LLM Service<br>                   |<br>                   v<br>              LLM API<br>                   |<br>                   v<br>          Streaming Response<br>                   |<br>                   v<br>              Frontend UI</pre><p>The backend should own important application decisions.</p><p>For example:</p><ul><li>Which user owns a conversation?</li><li>Which conversation ID can be accessed?</li><li>Which model should be used?</li><li>How much context should be included?</li><li>What happens when an API call fails?</li><li>How should token usage be recorded?</li></ul><p>A database could store records like these:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*9Wi6tgU4bVnynqtz06wn4A.png" /></figure><p>The backend can also store the provider’s conversation ID or latest response ID, depending on the state-management approach.</p><p>This gives the application control over user identity, conversation ownership, and the user interface’s history.</p><h3>13. Key Takeaways</h3><p>Let’s recap what we learned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*zaYWpxErF6PG5AeO6CrIHw.png" /></figure><p>The most important engineering lesson is this:</p><p><strong>An LLM application is not just a model API call. It is a complete software system that manages requests, state, context, errors, and user experience.</strong></p><h3>What’s Next?</h3><p>In the next article, we’ll explore one of the most important building blocks of modern GenAI applications:</p><p><strong>Part 7: Embeddings and Vector Search Explained — How AI Finds Meaning, Not Just Keywords</strong></p><p>We’ll learn:</p><ul><li>What embeddings are.</li><li>How text becomes numerical vectors.</li><li>Semantic similarity.</li><li>Cosine similarity.</li><li>Vector databases.</li><li>Building a simple semantic search application with Python.</li></ul><p>We’ll also understand why traditional keyword search is not always enough for AI-powered applications.</p><p>If you’re following this series, make sure to follow along. We’re gradually moving from LLM fundamentals toward building production-ready GenAI applications.</p><h3>References and Further Reading</h3><ol><li><a href="https://developers.openai.com/api/docs/guides/text">OpenAI API — Responses API</a></li><li><a href="https://developers.openai.com/api/docs/guides/streaming-responses">OpenAI API — Streaming Responses</a></li><li><a href="https://developers.openai.com/api/docs/guides/conversation-state">OpenAI API — Conversation State</a></li><li><a href="https://docs.streamlit.io/">Streamlit Documentation</a></li></ol><p>#GenerativeAI #LLM #Python #OpenAI #AIEngineering #SoftwareEngineering #BackendDevelopment #Streamlit #APIs #GenAI</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d941216ed711" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microsoft 365 Outage: Why Outlook, Teams and Other Microsoft Services Went Down]]></title>
            <link>https://medium.com/@abhint2603/microsoft-365-outage-why-outlook-teams-and-other-microsoft-services-went-down-c9f011d28cef?source=rss-fd6e8dab532------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9f011d28cef</guid>
            <category><![CDATA[microsoft-365]]></category>
            <category><![CDATA[outlook]]></category>
            <category><![CDATA[microsoft-outage]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Abhishek Nath Tiwari]]></dc:creator>
            <pubDate>Fri, 13 Nov 2026 10:59:37 GMT</pubDate>
            <atom:updated>2026-11-13T10:59:37.287Z</atom:updated>
            <content:encoded><![CDATA[<p><em>An inside look at the global disruption, the role of Exchange Online, what may have gone wrong inside Microsoft’s infrastructure, and the lessons every cloud engineer should learn.</em></p><p>On November 12, 2026, users across the world began experiencing problems accessing Microsoft’s services. Outlook inboxes failed to load, emails were delayed, and some Microsoft Teams and Microsoft 365 features stopped working as expected.</p><p>The disruption continued into November 13, affecting businesses, organisations, and individual users across multiple countries.</p><p>But this was not simply an Outlook problem.</p><p>The incident exposed an important characteristic of modern cloud platforms: <strong>when multiple products depend on shared infrastructure, a failure in one critical component can affect an entire ecosystem.</strong></p><p>So what actually happened? Why did Outlook, Teams, Copilot, and other services experience problems? And what can engineers learn from this incident?</p><p>Let’s break it down.</p><h3>1. What happened during the Microsoft 365 outage?</h3><p>Microsoft experienced a widespread service disruption that affected multiple products and services in its Microsoft 365 ecosystem.</p><p>Users reported issues such as:</p><ul><li>Outlook inboxes failing to load.</li><li>Emails being delayed or failing to send.</li><li>Problems accessing Exchange Online mailboxes.</li><li>Microsoft Teams calendar and meeting-related issues.</li><li>Copilot failing to load or retrieve work information.</li><li>Disruptions affecting certain SharePoint, OneDrive, Planner, and other Microsoft 365 features.</li><li>Problems with applications that connect to Microsoft 365 through its APIs.</li></ul><p>Reports came from dozens of countries and territories. Downdetector recorded close to 130,000 US reports of Outlook problems at the peak of the disruption.</p><p>The outage also affected some third-party integrations. OpenAI and Anthropic reported issues with Microsoft 365 connections used to access workplace information.</p><p>This demonstrates how an outage in a major cloud ecosystem can affect applications beyond the platform’s own products.</p><h3>2. Which Microsoft services were affected?</h3><p>Not every Microsoft service or feature was completely unavailable. The impact varied depending on the underlying component each service relied on.</p><p>Here’s a simplified breakdown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*fPUN5EFNzvPykLBVUQ-iyg.png" /></figure><p>An important distinction: Teams meetings, calls, and core messaging did not necessarily stop working for everyone. Some Teams functionality remained available while calendar and other dependent features were affected.</p><p>This is why describing the incident as every Microsoft application going completely offline would be misleading.</p><h3>3. Understanding the architecture: Why one problem affected multiple services</h3><p>To understand the incident, we first need to understand how Microsoft 365 works at a high level.</p><p>Most users interact with applications such as Outlook, Teams, and Copilot. However, these applications depend on underlying cloud services to perform their operations.</p><p>For example:</p><p><strong>Outlook</strong></p><ul><li>Provides the interface for accessing emails.</li><li>Connects to Exchange Online.</li><li>Exchange Online manages mailbox data and email-related operations.</li></ul><p><strong>Microsoft Teams</strong></p><ul><li>Provides messaging, meetings, and collaboration.</li><li>Depends on multiple backend services for identity, messaging, calendars, files, and integrations.</li></ul><p><strong>Microsft 365 Copilot</strong></p><ul><li>Provides AI-powered assistance.</li><li>May need to retrieve information from emails, calendars, documents, and other connected services.</li></ul><p>Microsoft Graph provides APIs through which applications can interact with Microsoft 365 data and capabilities.</p><p>This creates a dependency chain.</p><pre>             USERS<br>               |<br>               v<br>       Microsoft 365 Apps<br>               |<br>      +--------+--------+<br>      |        |        |<br>      v        v        v<br>   Outlook   Teams   Copilot<br>      |        |        |<br>      v        v        v<br>   Exchange  Multiple  Microsoft<br>    Online   Services   Graph<br>      |        |        |<br>      +--------+--------+<br>               |<br>               v<br>       Shared Cloud Infrastructure<br>               |<br>               v<br>       Networking and Routing</pre><p>This is a simplified conceptual architecture, not Microsoft’s internal infrastructure diagram.</p><p>The key idea is that applications may look independent to users while depending on shared infrastructure behind the scenes.</p><p>If a critical dependency becomes unavailable, multiple products can experience problems simultaneously.</p><h3>4. What went wrong inside Microsoft’s infrastructure?</h3><p>This is the most interesting part from an engineering perspective.</p><p>Microsoft initially reported elevated infrastructure load and connectivity errors affecting Exchange Online.</p><p>Subsequent updates described a problem involving a core process on affected servers responsible for establishing secure connections. That process became overwhelmed, causing servers to stop processing requests normally.</p><p>Let’s understand the possible failure sequence based on the information Microsoft has shared.</p><h3>Step 1: A critical infrastructure component becomes overloaded</h3><p>A backend component responsible for establishing secure connections experiences excessive load.</p><p>As the component struggles to process requests, servers begin experiencing connectivity problems.</p><h3>Step 2: Servers become unavailable</h3><p>Some affected servers stop responding or fail automated health checks.</p><p>This reduces the number of healthy servers available to handle incoming requests.</p><h3>Step 3: Remaining servers receive more traffic</h3><p>When some servers become unavailable, traffic must be handled by the remaining infrastructure.</p><p>This can increase pressure on already overloaded components.</p><p>The situation can become self-reinforcing:</p><pre>      Increased Traffic<br>              |<br>              v<br>       Infrastructure<br>          Overload<br>              |<br>              v<br>       Server Failures<br>              |<br>              v<br>       Reduced Capacity<br>              |<br>              v<br>       More Load on<br>       Remaining Servers<br>              |<br>              +-------&gt; More Failures</pre><p>This is a simplified illustration of a cascading capacity problem.</p><h3>Step 4: Recovery becomes difficult</h3><p>One particularly challenging aspect was that some servers became unresponsive again after being restarted and receiving traffic.</p><p>In other words, restarting servers was not enough to guarantee stable recovery.</p><p>Microsoft also investigated whether recent network configuration changes had contributed to the incident.</p><p>As of November 13, the company had not published a final root-cause analysis.</p><p><strong>Important:</strong> The exact initiating trigger and the complete technical root cause remain subject to Microsoft’s investigation. The explanation above describes the failure pattern Microsoft reported, not a confirmed final post-incident diagnosis.</p><h3>5. Why couldn’t Microsoft simply restart its servers?</h3><p>This is a question many people ask during major cloud outages.</p><p>If a server stops responding, why not restart it?</p><p>Because restarting a server does not necessarily fix the condition that caused it to fail.</p><p>Imagine a service running on 100 servers.</p><p>If 40 servers become unhealthy, the remaining 60 must handle a much larger workload.</p><p>Now imagine restarting those 40 servers.</p><p>When they reconnect, they begin receiving traffic again. If the underlying issue still exists, they may become unhealthy once more.</p><p>This creates a difficult recovery situation.</p><p>Engineers must consider:</p><ul><li>Whether the original failure condition has been removed.</li><li>Whether servers are healthy under real traffic.</li><li>Whether traffic is distributed correctly.</li><li>Whether backend dependencies can handle the returning load.</li><li>Whether recovery itself could overload the infrastructure.</li></ul><p>This is why large-scale cloud recovery is not always as simple as turning servers off and on again.</p><h3>6. How did Microsoft attempt to restore services?</h3><p>Microsoft described several recovery efforts during the incident.</p><p>These included:</p><p><strong>1. Returning affected servers to service</strong></p><p>Engineers worked to restore infrastructure that had become unavailable.</p><p><strong>2. Shifting traffic to alternative routes</strong></p><p>Microsoft attempted to move traffic through alternative pathways to reduce pressure on affected infrastructure.</p><p><strong>3. Increasing infrastructure capacity</strong></p><p>The company explored capacity improvements, including scaling virtual machines where possible.</p><p><strong>4. Applying configuration changes and patches</strong></p><p>Microsoft worked on infrastructure and configuration changes to improve server stability.</p><p><strong>5. Monitoring recovery</strong></p><p>The company monitored server health and the effectiveness of its recovery changes.</p><p>By November 13, Microsoft reported positive results for server stability after applying an upstream authentication/routing configuration component patch to part of its infrastructure.</p><p>However, recovery was gradual, and Microsoft continued working to restore affected services.</p><h3>7. Was this a cyberattack?</h3><p>As of the updates available on November 13, Microsoft said it had no indication that malicious activity or a cyberattack caused the incident.</p><p>This distinction matters.</p><p>A large-scale outage does not automatically mean that a company has been hacked.</p><p>Cloud services can fail because of:</p><ul><li>Software defects.</li><li>Configuration changes.</li><li>Infrastructure overload.</li><li>Networking problems.</li><li>Failed deployments.</li><li>Dependency failures.</li><li>Capacity-management issues.</li></ul><p>A security incident and an availability incident are different categories of operational failure.</p><p>Microsoft said it would provide more information through a post-incident report after the situation was mitigated.</p><h3>8. What can software engineers learn from this outage?</h3><p>This incident is an excellent real-world example of several important distributed-systems concepts.</p><h3>Lesson 1: Avoid single points of failure</h3><p>A critical shared component can become a bottleneck for many applications.</p><p>Engineers should identify critical dependencies and design systems to tolerate their failure wherever possible.</p><h3>Lesson 2: Design for graceful degradation</h3><p>Not every feature needs to stop working when one dependency fails.</p><p>For example, if a calendar service becomes unavailable, a messaging application should ideally continue supporting independent messaging functionality.</p><p>This approach is called graceful degradation.</p><h3>Lesson 3: Health checks must represent real application health</h3><p>A server can respond to a basic health-check endpoint while still being unable to process actual user requests.</p><p>Health checks should evaluate meaningful dependencies and application behaviour.</p><h3>Lesson 4: Recovery must be tested under load</h3><p>A service that works when traffic is low may fail when normal traffic returns.</p><p>Engineers should consider recovery scenarios, traffic spikes, and load distribution when designing restoration procedures.</p><h3>Lesson 5: Configuration changes need strong safeguards</h3><p>Infrastructure configuration changes can have consequences across large numbers of services.</p><p>Useful safeguards include:</p><ul><li>Gradual rollouts.</li><li>Canary deployments.</li><li>Automated rollback.</li><li>Configuration validation.</li><li>Change monitoring.</li><li>Clear ownership and incident procedures.</li></ul><h3>Lesson 6: Observability is essential</h3><p>During an outage, engineers need to understand what is failing and why.</p><p>Useful signals include:</p><ul><li>Request latency.</li><li>Error rates.</li><li>Server health.</li><li>Connection failures.</li><li>Queue depth.</li><li>CPU and memory utilisation.</li><li>Traffic distribution.</li><li>Dependency availability.</li></ul><p>Monitoring only whether a service is running is not enough.</p><p>Engineers need visibility into whether the service is actually working for users.</p><h3>9. How can businesses prepare for outages like this?</h3><p>Cloud platforms provide scalability and reliability, but they do not eliminate outages.</p><p>Businesses should plan for the possibility that a major cloud provider or one of its critical services may become unavailable.</p><p>Some practical measures include:</p><ol><li><strong>Maintain alternative communication channels:</strong> Keep emergency phone numbers and backup communication tools available.</li><li><strong>Document business continuity procedures:</strong> Employees should know what to do when email or collaboration tools stop working.</li><li><strong>Identify critical dependencies:</strong> Understand which business applications depend on Exchange Online, Microsoft Graph, or other services.</li><li><strong>Back up important information:</strong> Follow appropriate backup and recovery practices rather than relying on a single service.</li><li><strong>Monitor official service status:</strong> Use Microsoft’s service health dashboard and communicate verified updates to employees.</li><li><strong>Test disaster recovery plans:</strong> A recovery document is useful only if the organisation has tested it.</li></ol><p>For organisations that rely heavily on cloud productivity tools, resilience is not just an infrastructure concern. It is a business continuity requirement.</p><h3>10. The bigger lesson: Cloud reliability is about dependencies, not just uptime</h3><p>The Microsoft 365 outage highlights an important reality of modern software architecture.</p><p>Users see separate products:</p><ul><li>Outlook for email.</li><li>Teams for communication.</li><li>SharePoint for collaboration.</li><li>OneDrive for storage.</li><li>Copilot for AI assistance.</li></ul><p>But behind these products are interconnected services, APIs, networking components, authentication systems, and shared infrastructure.</p><p>A failure in one critical dependency can affect many products at once.</p><p>This is why modern cloud engineering focuses on more than simply keeping servers running.</p><p>It requires:</p><ul><li>Fault isolation.</li><li>Resilient architecture.</li><li>Capacity planning.</li><li>Safe deployments.</li><li>Observability.</li><li>Automated recovery.</li><li>Disaster recovery planning.</li></ul><p>The real measure of a reliable system is not whether it never fails.</p><p><strong>It is how well the system contains failures, recovers from them, and continues serving users when something goes wrong.</strong></p><h3>Final Thoughts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zMXWK2rTqShx3fGJ8cAvSQ.png" /></figure><p>The November 2026 Microsoft 365 outage is a reminder that even the world’s largest technology companies are not immune to infrastructure failures.</p><p>The most interesting engineering lesson is not simply that Outlook went down.</p><p>It is how a problem involving critical backend infrastructure and server capacity could affect multiple interconnected services, and why restoring a large distributed system can be more complicated than restarting a few machines.</p><p>As engineers, incidents like this give us an opportunity to understand distributed systems beyond textbook definitions.</p><p>Because in production, reliability is not just a feature.</p><p>It is an engineering responsibility.</p><h3>What’s Next?</h3><p>In the next article, we’ll return to our practical GenAI engineering series:</p><p><strong>Part 6: LLM APIs, Streaming, and Conversation State — Building Responsive AI Applications</strong></p><p>We’ll explore how LLM applications communicate with model APIs, stream responses in real time, and maintain conversation context.</p><h3>Sources and Further Reading</h3><ul><li><a href="https://apnews.com/article/d92547a821930290db2964388016979a">Microsoft 365 outage coverage — Associated Press</a></li><li><a href="https://www.business-standard.com/technology/tech-news/microsoft-365-outage-continues-as-company-sees-limited-recovery-in-services-126111300464_1.html">Microsoft 365 outage and service impact — Business Standard</a></li><li><a href="https://www.theguardian.com/technology/2026/nov/13/microsoft-outage-outlook-teams-word-excel-reports">Microsoft begins restoring services — The Guardian</a></li><li><a href="https://www.theguardian.com/technology/live/2026/nov/13/microsoft-outage-down-today-live-update-outlook-teams-365-when-fixed-latest-status-cause-news">Microsoft outage updates — The Guardian live coverage</a></li></ul><p><em>Note: This article reflects information available on November 13, 2026. Microsoft’s final post-incident report may provide additional details or revise the technical explanation.</em></p><p>#Microsoft365 #MicrosoftOutage #Outlook #MicrosoftTeams #CloudComputing #DistributedSystems #SystemDesign #SoftwareEngineering #TechNews #CloudArchitecture</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9f011d28cef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structured Outputs and Function Calling: Making LLMs Work With Real Applications]]></title>
            <link>https://medium.com/@abhint2603/structured-outputs-and-function-calling-making-llms-work-with-real-applications-4da27c1d0bb2?source=rss-fd6e8dab532------2</link>
            <guid isPermaLink="false">https://medium.com/p/4da27c1d0bb2</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Abhishek Nath Tiwari]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 21:50:59 GMT</pubDate>
            <atom:updated>2026-11-05T21:50:59.033Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Learn how to get predictable JSON responses from LLMs and connect AI models to external functions using Python.</em></p><p>Imagine you’re building an AI-powered customer support application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*AuI6bsQApztHIWrTVUSMaQ.png" /></figure><p>A user asks:</p><p>“Where is my order, and when will it arrive?”</p><p>A normal chatbot might generate a helpful-sounding answer. But your application needs more than text. It needs to identify the order number, retrieve the actual order status, and return the result in a format your backend can process.</p><p>How can an LLM interact with your application instead of simply generating text?</p><p>Two important capabilities make this possible:</p><ol><li><strong>Structured Outputs:</strong> Make model responses follow a predefined data structure.</li><li><strong>Function Calling:</strong> Allow a model to request functions that your application executes.</li></ol><p>These capabilities are fundamental to building practical AI applications, assistants, and agentic workflows.</p><p>In Part 4, we built a basic LLM application using Python and Streamlit. In this article, we’ll extend that foundation and learn how to make LLMs return structured data and interact with application-defined tools.</p><p>We’ll use Python and the OpenAI Responses API for the examples. The concepts are applicable to other LLM providers as well, although their SDKs and APIs may differ.</p><h3>1. Why Do We Need Structured Outputs?</h3><p>Let’s start with a simple problem.</p><p>Suppose you ask an LLM:</p><p>“Extract the name, email address, and priority from this support ticket.”</p><p>You might receive:</p><pre>The customer is John Smith.<br>His email address is john@example.com.<br>The ticket priority is high.</pre><p>This is readable for a human, but what if your backend needs to save the result in a database?</p><p>Your application would have to extract the individual values from the generated text.</p><p>That introduces unnecessary complexity.</p><p>Now imagine receiving:</p><pre>{<br>  &quot;name&quot;: &quot;John Smith&quot;,<br>  &quot;email&quot;: &quot;john@example.com&quot;,<br>  &quot;priority&quot;: &quot;HIGH&quot;<br>}</pre><p>This is much easier for a program to consume.</p><p>Your backend can access individual fields, validate them, and pass them to other services.</p><p>This is the basic idea behind structured outputs.</p><p><strong>Structured Outputs allow you to define a schema that constrains the structure of the model’s response.</strong></p><p>Instead of relying only on instructions such as “Please return JSON,” you provide a formal definition of the expected output.</p><h3>2. JSON Mode vs. Structured Outputs</h3><p>These two concepts are related, but they are not the same.</p><h3>JSON Mode</h3><p>JSON mode is designed to produce syntactically valid JSON on supported models and API configurations.</p><p>For example:</p><pre>{<br>  &quot;name&quot;: &quot;John Smith&quot;,<br>  &quot;priority&quot;: &quot;HIGH&quot;<br>}</pre><p>However, valid JSON does not necessarily mean that the response contains the exact fields or values your application expects.</p><p>The model might return:</p><pre>{<br>  &quot;customer&quot;: &quot;John Smith&quot;,<br>  &quot;priority&quot;: &quot;URGENT&quot;,<br>  &quot;extra&quot;: &quot;Some additional information&quot;<br>}</pre><p>This is valid JSON, but it doesn’t match a schema that requires name and restricts priority to LOW, MEDIUM, or HIGH.</p><h3>Structured Outputs</h3><p>Structured Outputs go further by constraining the generated response to a supported JSON Schema.</p><p>For example, you can define:</p><pre>{<br>  &quot;type&quot;: &quot;object&quot;,<br>  &quot;properties&quot;: {<br>    &quot;name&quot;: {<br>      &quot;type&quot;: &quot;string&quot;<br>    },<br>    &quot;priority&quot;: {<br>      &quot;type&quot;: &quot;string&quot;,<br>      &quot;enum&quot;: [&quot;LOW&quot;, &quot;MEDIUM&quot;, &quot;HIGH&quot;]<br>    }<br>  },<br>  &quot;required&quot;: [&quot;name&quot;, &quot;priority&quot;],<br>  &quot;additionalProperties&quot;: false<br>}</pre><p>The model is constrained to return the defined fields and allowed priority values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*8ojcMQhqq1j74xPkZb_T6A.png" /></figure><p>One important distinction: schema compliance does not guarantee that the extracted information is factually correct. Your application still needs appropriate validation and business rules.</p><h3>3. Build Your First Structured Output With Python</h3><p>Let’s implement a practical example.</p><p>We’ll extract information from a customer support ticket.</p><h4>Step 1: Install dependencies</h4><p>If you followed Part 4, you should already have the OpenAI SDK installed.</p><p>Otherwise:</p><pre>pip install openai pydantic python-dotenv</pre><h4>Step 2: Configure the API client</h4><p>Create a .env file:</p><pre>OPENAI_API_KEY=your_api_key_here<br>OPENAI_MODEL=your_supported_model</pre><p>Load the configuration:</p><pre>import os</pre><pre>from dotenv import load_dotenv<br>from openai import OpenAI</pre><pre>load_dotenv()</pre><pre>client = OpenAI(<br>    api_key=os.environ[&quot;OPENAI_API_KEY&quot;]<br>)</pre><pre>MODEL = os.environ[&quot;OPENAI_MODEL&quot;]</pre><p>Replace the model placeholder with a model supported by your API account.</p><h4>Step 3: Define the output schema using Pydantic</h4><p>Pydantic lets us define the expected structure using Python classes.</p><pre>from pydantic import BaseModel<br>from typing import Literal<br></pre><pre>class SupportTicket(BaseModel):<br>    customer_name: str<br>    email: str<br>    category: Literal[<br>        &quot;BILLING&quot;,<br>        &quot;TECHNICAL&quot;,<br>        &quot;ACCOUNT&quot;<br>    ]<br>    priority: Literal[<br>        &quot;LOW&quot;,<br>        &quot;MEDIUM&quot;,<br>        &quot;HIGH&quot;<br>    ]<br>    summary: str</pre><p>Let’s understand this.</p><ul><li>customer_name: Must be a string.</li><li>email: Must be a string.</li><li>category: Must be one of the three allowed values.</li><li>priority: Must be LOW, MEDIUM, or HIGH.</li><li>summary: Must be a string.</li></ul><p>We have now defined the structure expected by our application.</p><h4>Step 4: Generate a structured response</h4><p>The OpenAI Python SDK supports client.responses.parse() with a Pydantic model.</p><pre>ticket_text = &quot;&quot;&quot;<br>Hi, my name is Rahul Sharma.</pre><pre>I am unable to access my account after<br>resetting my password.</pre><pre>My email is rahul@example.com.</pre><pre>I have an important meeting today and<br>need this fixed urgently.<br>&quot;&quot;&quot;</pre><pre>response = client.responses.parse(<br>    model=MODEL,<br>    input=[<br>        {<br>            &quot;role&quot;: &quot;system&quot;,<br>            &quot;content&quot;: (<br>                &quot;Extract customer support information &quot;<br>                &quot;from the supplied ticket. &quot;<br>                &quot;Do not invent missing information.&quot;<br>            )<br>        },<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: ticket_text<br>        }<br>    ],<br>    text_format=SupportTicket<br>)</pre><pre>ticket = response.output_parsed</pre><pre>if ticket is None:<br>    raise ValueError(<br>        &quot;The model did not return a parsed ticket.&quot;<br>    )</pre><pre>print(ticket.model_dump())</pre><h3>Example output</h3><pre>{<br>  &quot;customer_name&quot;: &quot;Rahul Sharma&quot;,<br>  &quot;email&quot;: &quot;rahul@example.com&quot;,<br>  &quot;category&quot;: &quot;ACCOUNT&quot;,<br>  &quot;priority&quot;: &quot;HIGH&quot;,<br>  &quot;summary&quot;: &quot;Customer cannot access their account after resetting their password and needs urgent assistance.&quot;<br>}</pre><p>The exact summary may vary.</p><p>The important part is that the application receives a parsed object that follows the defined schema when the API returns a successful structured result.</p><h3>What happens behind the scenes?</h3><pre>Customer Support Ticket<br>          |<br>          v<br>     Python Application<br>          |<br>          v<br>    Pydantic Schema<br>          |<br>          v<br>       LLM API<br>          |<br>          v<br> Structured Generation<br>          |<br>          v<br>    Parsed Response<br>          |<br>          v<br>    Python Object<br>          |<br>          v<br>    Database / Backend</pre><p>This is especially useful when building:</p><ul><li>Document extraction systems.</li><li>Invoice processing applications.</li><li>Customer support automation.</li><li>Resume parsing systems.</li><li>Data classification pipelines.</li><li>AI-powered form generation.</li></ul><h3>4. What Is Function Calling?</h3><p>Structured Outputs help us control the format of an LLM response.</p><p>But what if the model needs information that isn’t present in the prompt?</p><p>For example:</p><p>“What is the current status of my order?”</p><p>The model cannot reliably know the latest order status from its training data.</p><p>Your application has access to the order database, so it should retrieve that information.</p><p>This is where function calling becomes useful.</p><p><strong>Function Calling allows an LLM to request that your application execute a predefined function using arguments generated by the model.</strong></p><p>The model does not directly execute your Python code.</p><p>Instead, it identifies a function it wants to use and supplies the arguments. Your application receives that request, validates it, executes the function, and sends the result back to the model.</p><p>The distinction is important:</p><ul><li>The model decides when a tool may be useful.</li><li>Your application controls which tools exist.</li><li>Your application executes the actual functions.</li><li>The model uses the returned result to formulate its final answer.</li></ul><h3>5. How Does Function Calling Work?</h3><p>Let’s understand the workflow.</p><p>Suppose a user asks:</p><p>“What is 25 multiplied by 16?”</p><p>We provide the model with a function called multiply_numbers.</p><p>The function accepts two numbers and returns their product.</p><p>The workflow looks like this:</p><pre>User Question<br>     |<br>     v<br>Python Application<br>     |<br>     v<br>Send Prompt + Tool Definition<br>     |<br>     v<br>      LLM<br>     |<br>     v<br>Model Requests Function Call<br>     |<br>     v<br>Python Receives Function Name<br>and Arguments<br>     |<br>     v<br>Python Executes Function<br>     |<br>     v<br>Function Result Returned<br>to the Model<br>     |<br>     v<br>LLM Generates Final Answer<br>     |<br>     v<br>Response to User</pre><p>Notice that the model doesn’t calculate the result by executing your Python function itself.</p><p>It requests the function call. Your application performs the operation.</p><p>This separation gives developers control over what the AI can access and do.</p><h3>6. Build Your First Function-Calling Application</h3><p>Let’s implement this using Python.</p><p>We’ll create a calculator tool that can perform multiplication.</p><h4>Step 1: Define the Python function</h4><pre>def multiply_numbers(<br>    a: float,<br>    b: float<br>) -&gt; float:<br>    return a * b</pre><p>This is an ordinary Python function.</p><p>It doesn’t know anything about LLMs.</p><h4>Step 2: Define the tool schema</h4><p>Now we need to describe this function to the model.</p><pre>tools = [<br>    {<br>        &quot;type&quot;: &quot;function&quot;,<br>        &quot;name&quot;: &quot;multiply_numbers&quot;,<br>        &quot;description&quot;: (<br>            &quot;Multiply two numbers and return the result.&quot;<br>        ),<br>        &quot;parameters&quot;: {<br>            &quot;type&quot;: &quot;object&quot;,<br>            &quot;properties&quot;: {<br>                &quot;a&quot;: {<br>                    &quot;type&quot;: &quot;number&quot;,<br>                    &quot;description&quot;: &quot;First number&quot;<br>                },<br>                &quot;b&quot;: {<br>                    &quot;type&quot;: &quot;number&quot;,<br>                    &quot;description&quot;: &quot;Second number&quot;<br>                }<br>            },<br>            &quot;required&quot;: [&quot;a&quot;, &quot;b&quot;],<br>            &quot;additionalProperties&quot;: False<br>        },<br>        &quot;strict&quot;: True<br>    }<br>]</pre><p>Let’s understand the important properties.</p><p><strong>type</strong></p><p>Defines the tool as a function.</p><p><strong>name</strong></p><p>The name the model uses when requesting the function.</p><p><strong>description</strong></p><p>Explains what the function does and when it should be used.</p><p><strong>parameters</strong></p><p>Defines the arguments using JSON Schema.</p><p><strong>required</strong></p><p>Specifies which arguments must be present.</p><p><strong>additionalProperties</strong></p><p>Prevents additional, undefined arguments.</p><p><strong>strict</strong></p><p>Enables strict schema adherence for function arguments, subject to supported schema requirements.</p><p>A well-defined tool description matters because the model uses it to decide when and how to request the function.</p><h4>Step 3: Send the request to the model</h4><pre>response = client.responses.create(<br>    model=MODEL,<br>    input=&quot;What is 25 multiplied by 16?&quot;,<br>    tools=tools<br>)</pre><pre>print(response.output)</pre><p>The model may return a function-call item instead of a normal text answer.</p><p>For example, the call might look conceptually like this:</p><pre>{<br>  &quot;type&quot;: &quot;function_call&quot;,<br>  &quot;name&quot;: &quot;multiply_numbers&quot;,<br>  &quot;arguments&quot;: &quot;{\&quot;a\&quot;:25,\&quot;b\&quot;:16}&quot;<br>}</pre><p>This is a request from the model to your application.</p><p>It is not the final answer to the user.</p><h4>Step 4: Execute the requested function</h4><p>We now inspect the response and execute the function.</p><pre>import json</pre><pre>for item in response.output:<br>    if item.type == &quot;function_call&quot;:<br>        arguments = json.loads(item.arguments)</pre><pre>        if item.name == &quot;multiply_numbers&quot;:<br>            result = multiply_numbers(<br>                arguments[&quot;a&quot;],<br>                arguments[&quot;b&quot;]<br>            )</pre><pre>            print(&quot;Function result:&quot;, result)</pre><p>Expected output:</p><pre>Function result: 400.0</pre><p>Our Python application successfully executed the function.</p><p>But we’re not finished yet.</p><p>We still need to send the result back to the model.</p><h3>7. Complete the Function-Calling Loop</h3><p>A complete function-calling workflow requires another API request.</p><p>The model needs to receive the function’s result so it can generate a final response.</p><p>Here’s the complete implementation:</p><pre>import json<br>import os</pre><pre>from dotenv import load_dotenv<br>from openai import OpenAI</pre><pre>load_dotenv()</pre><pre>client = OpenAI(<br>    api_key=os.environ[&quot;OPENAI_API_KEY&quot;]<br>)</pre><pre>MODEL = os.environ[&quot;OPENAI_MODEL&quot;]<br></pre><pre>def multiply_numbers(a: float, b: float) -&gt; float:<br>    return a * b<br></pre><pre>tools = [<br>    {<br>        &quot;type&quot;: &quot;function&quot;,<br>        &quot;name&quot;: &quot;multiply_numbers&quot;,<br>        &quot;description&quot;: &quot;Multiply two numbers.&quot;,<br>        &quot;parameters&quot;: {<br>            &quot;type&quot;: &quot;object&quot;,<br>            &quot;properties&quot;: {<br>                &quot;a&quot;: {&quot;type&quot;: &quot;number&quot;},<br>                &quot;b&quot;: {&quot;type&quot;: &quot;number&quot;}<br>            },<br>            &quot;required&quot;: [&quot;a&quot;, &quot;b&quot;],<br>            &quot;additionalProperties&quot;: False<br>        },<br>        &quot;strict&quot;: True<br>    }<br>]<br></pre><pre>def ask_calculator(question: str) -&gt; str:<br>    response = client.responses.create(<br>        model=MODEL,<br>        input=question,<br>        tools=tools<br>    )</pre><pre>    # Preserve the model&#39;s output items<br>    # when continuing the interaction.<br>    input_items = list(response.output)</pre><pre>    for item in response.output:</pre><pre>        if item.type != &quot;function_call&quot;:<br>            continue</pre><pre>        if item.name != &quot;multiply_numbers&quot;:<br>            raise ValueError(&quot;Unknown function requested.&quot;)</pre><pre>        arguments = json.loads(item.arguments)</pre><pre>        result = multiply_numbers(<br>            arguments[&quot;a&quot;],<br>            arguments[&quot;b&quot;]<br>        )</pre><pre>        # Send the function result back to the model.<br>        input_items.append({<br>            &quot;type&quot;: &quot;function_call_output&quot;,<br>            &quot;call_id&quot;: item.call_id,<br>            &quot;output&quot;: json.dumps({<br>                &quot;result&quot;: result<br>            })<br>        })</pre><pre>    final_response = client.responses.create(<br>        model=MODEL,<br>        previous_response_id=response.id,<br>        input=input_items,<br>        tools=tools<br>    )</pre><pre>    return final_response.output_text<br></pre><pre>if __name__ == &quot;__main__&quot;:<br>    answer = ask_calculator(<br>        &quot;What is 25 multiplied by 16?&quot;<br>    )</pre><pre>    print(answer)</pre><h3>Example final response</h3><pre>25 multiplied by 16 equals 400.</pre><p>The wording may vary, but the model can now use the actual result returned by your Python function.</p><h3>Understanding the complete flow</h3><p>There are two API calls:</p><p><strong>First API call</strong></p><p>The model receives the question and available tool definitions. It decides whether to request a function.</p><p><strong>Python execution</strong></p><p>Your application parses the arguments and executes the requested function.</p><p><strong>Second API call</strong></p><p>Your application sends the function result back to the model. The model generates the final response.</p><p>The call_id connects the tool output to the specific function call that requested it.</p><p>For applications that execute multiple function calls, the application must process and return the corresponding results for each call.</p><h3>8. Structured Outputs vs. Function Calling</h3><p>These capabilities solve different problems, even though both can use JSON Schema.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*4E6FMZQFvLLRaX2lZtg87g.png" /></figure><p>Think of it this way:</p><p><strong>Structured Outputs answer the question:</strong></p><p>“How should the model return its response?”</p><p><strong>Function Calling answers the question:</strong></p><p>“How can the model request functionality from my application?”</p><p>You can use both in the same application.</p><p>For example, an AI assistant might call a database lookup function and then return the retrieved order details using a structured response schema.</p><h3>9. Real-World Example: An AI Order Assistant</h3><p>Let’s combine these concepts into a practical scenario.</p><p>Imagine an e-commerce company has an order database.</p><p>A customer asks:</p><p>“Can you check the status of order ORD-1024?”</p><p>The application provides a tool:</p><p>get_order_status(order_id)</p><p>The function retrieves the order from the database.</p><p>Example tool implementation:</p><pre>orders = {<br>    &quot;ORD-1024&quot;: {<br>        &quot;status&quot;: &quot;SHIPPED&quot;,<br>        &quot;estimated_delivery&quot;: &quot;2026-11-08&quot;<br>    },<br>    &quot;ORD-1025&quot;: {<br>        &quot;status&quot;: &quot;PROCESSING&quot;,<br>        &quot;estimated_delivery&quot;: &quot;2026-11-10&quot;<br>    }<br>}<br></pre><pre>def get_order_status(order_id: str) -&gt; dict:<br>    order = orders.get(order_id)</pre><pre>    if order is None:<br>        return {<br>            &quot;found&quot;: False,<br>            &quot;message&quot;: &quot;Order not found.&quot;<br>        }</pre><pre>    return {<br>        &quot;found&quot;: True,<br>        &quot;order_id&quot;: order_id,<br>        &quot;status&quot;: order[&quot;status&quot;],<br>        &quot;estimated_delivery&quot;: order[&quot;estimated_delivery&quot;]<br>    }</pre><p>The model can request this function with the order ID extracted from the user’s question.</p><p>Your application executes the lookup and returns the result.</p><p>The model can then generate a natural-language answer:</p><p>“Your order ORD-1024 has been shipped and is currently expected to arrive on November 8, 2026.”</p><p>This is much more useful than asking a model to guess the status of an order.</p><p>The same architecture can be extended to:</p><ul><li>Check payment status.</li><li>Retrieve customer details.</li><li>Search product availability.</li><li>Create support tickets.</li><li>Fetch shipment information.</li><li>Retrieve database records.</li></ul><p>The model handles natural-language interaction, while your application handles actual business operations.</p><h3>10. Important Security Considerations</h3><p>Function calling makes AI applications more powerful, but it also introduces new security responsibilities.</p><p>A model-generated function call should never automatically be treated as trusted application input.</p><p>Consider these practices.</p><h4>1. Use an allowlist of functions</h4><p>Only execute functions explicitly registered by your application.</p><p>Never dynamically execute arbitrary Python code based on a model response.</p><h4>2. Validate arguments</h4><p>Even when strict schemas are enabled, validate important inputs and enforce application-specific rules.</p><p>For example, check that an order belongs to the authenticated customer.</p><h4>3. Apply authorization checks</h4><p>The model should not decide whether a user has permission to access a resource.</p><p>Your backend must enforce authentication and authorization independently.</p><h4>4. Require confirmation for sensitive actions</h4><p>Operations such as sending emails, deleting records, issuing refunds, or making purchases may require explicit user approval.</p><h4>5. Avoid exposing sensitive information</h4><p>Return only the information required for the current task.</p><p>Don’t expose internal database fields or credentials in tool results.</p><h4>6. Handle failures</h4><p>A function may fail because a database is unavailable, an order doesn’t exist, or an external service times out.</p><p>Return controlled errors and let the application decide how to handle them.</p><h4>7. Treat external content as untrusted</h4><p>Retrieved documents, user input, and tool results may contain malicious instructions. Don’t let them override application policies or bypass tool permissions.</p><p>The most important principle is:</p><p><strong>The model can request an action, but your application remains responsible for deciding whether that action is allowed and executing it safely.</strong></p><h3>11. Common Mistakes Developers Make</h3><p><strong>Mistake 1: Thinking function calling executes the function automatically</strong></p><p>It doesn’t. The model requests the function; your application executes it.</p><p><strong>Mistake 2: Assuming JSON Mode guarantees a schema</strong></p><p>Valid JSON and schema compliance are different things. Use Structured Outputs when supported and appropriate.</p><p><strong>Mistake 3: Ignoring tool arguments</strong></p><p>Always parse and validate arguments before using them.</p><p><strong>Mistake 4: Giving the model too many tools</strong></p><p>Too many poorly described tools can make selection less reliable. Start with a small set of clear, focused functions.</p><p><strong>Mistake 5: Allowing unrestricted tool execution</strong></p><p>Never let a model execute arbitrary code or access unrestricted database operations.</p><p><strong>Mistake 6: Forgetting to return tool results</strong></p><p>A function call is only one stage of the interaction. Send the result back to the model if you want it to produce a final answer based on that result.</p><p><strong>Mistake 7: Assuming structured output means factual correctness</strong></p><p>A response can follow a schema and still contain incorrect information. Validate important facts against trusted sources.</p><h3>12. Key Takeaways</h3><p>Let’s summarize what we’ve learned.</p><ul><li><strong>Structured Outputs</strong> constrain model responses to a defined schema.</li><li><strong>JSON Mode</strong> produces JSON but does not guarantee compliance with a specific schema.</li><li><strong>Pydantic</strong> provides a convenient way to define and parse structured data in Python.</li><li><strong>Function Calling</strong> allows models to request application-defined functions.</li><li><strong>Your application executes the functions</strong>, not the model.</li><li><strong>Tool results must be returned to the model</strong> for it to generate a response using those results.</li><li><strong>Security and authorization</strong> must be enforced by your backend.</li><li>Structured Outputs and Function Calling can work together in more advanced AI applications.</li></ul><p>We have now moved beyond a chatbot that simply generates text.</p><p>We can build applications that extract structured information, retrieve external data, and interact with existing software systems.</p><p>This is an important building block for more capable AI assistants and agents.</p><h3>What’s Next?</h3><p>In Part 6, we’ll explore:</p><p><strong>LLM APIs, Streaming, and Conversation State</strong></p><p>We’ll understand how applications communicate with LLM providers, how streaming improves the user experience, and how to manage conversations across multiple requests.</p><p>We’ll continue extending the same AI assistant rather than creating disconnected examples.</p><p><em>This is Part 5 of the Practical GenAI Engineering series, where we move from LLM fundamentals toward building reliable, production-oriented AI applications.</em></p><p>#GenerativeAI #LLM #Python #StructuredOutputs #FunctionCalling #AIEngineering #OpenAI</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4da27c1d0bb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your First LLM Application with Python]]></title>
            <link>https://medium.com/@abhint2603/build-your-first-llm-application-with-python-f5ea500b8729?source=rss-fd6e8dab532------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5ea500b8729</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Abhishek Nath Tiwari]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 21:57:04 GMT</pubDate>
            <atom:updated>2026-10-24T21:57:04.117Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A step-by-step guide to building an LLM-powered application, handling responses and errors, and maintaining conversation history.</em></p><p>In the previous three articles, we explored how Large Language Models work, how tokens and embeddings represent information, and how prompt engineering can improve the quality of AI responses.</p><p>Now it’s time to build something.</p><p>Instead of discussing LLMs only in theory, we’ll create a working Python application that sends questions to an LLM, receives responses, handles errors, and maintains conversation history.</p><p>We’ll also build a simple web interface so you can interact with the application like a chatbot.</p><p>By the end of this tutorial, you’ll understand the basic architecture behind an LLM-powered application and have a foundation you can extend into more advanced AI projects.</p><h3>1. What Are We Building?</h3><p>We’ll build a simple AI assistant with the following capabilities:</p><ul><li>Accept questions from a user.</li><li>Send prompts to an LLM through an API.</li><li>Display generated responses.</li><li>Maintain conversation history.</li><li>Handle API errors gracefully.</li><li>Provide a simple chat interface using Streamlit.</li></ul><p>We’ll use Python, the OpenAI SDK, and Streamlit. The architecture is not tied to a single provider, so you can adapt the same concepts to other LLM APIs.</p><h3>High-level architecture</h3><pre>           User<br>            |<br>            v<br>     Streamlit UI<br>            |<br>            v<br>      Python Backend<br>            |<br>            v<br>       Prompt + History<br>            |<br>            v<br>         LLM API<br>            |<br>            v<br>     Generated Response<br>            |<br>            v<br>       Streamlit UI<br>            |<br>            v<br>          User</pre><p>The important thing to understand is that the LLM is only one component of the application.</p><p>Your Python code controls how prompts are constructed, how conversation history is sent, how errors are handled, and how the response is presented to the user.</p><h3>2. Set Up Your Development Environment</h3><p>Before writing code, let’s prepare the project.</p><h3>Step 1: Create a project directory</h3><pre>mkdir first-llm-app<br>cd first-llm-app</pre><h3>Step 2: Create a virtual environment</h3><p>A virtual environment keeps the dependencies for this project separate from other Python projects.</p><pre>python -m venv .venv</pre><p>Activate it on Windows:</p><pre>.venv\Scripts\activate</pre><p>On macOS or Linux:</p><pre>source .venv/bin/activate</pre><h3>Step 3: Install the required packages</h3><p>We’ll use:</p><ul><li>openai — to communicate with the OpenAI API.</li><li>streamlit — to build the chat interface.</li><li>python-dotenv — to load environment variables from a local .env file during development.</li></ul><p>Install them with:</p><pre>pip install openai streamlit python-dotenv</pre><p>You should now have the basic dependencies needed to build the application.</p><h3>3. Configure Your API Key Securely</h3><p>An API key authenticates your application with the model provider.</p><p>Create an API key through your provider’s official developer platform, making sure your account has access to the model you intend to use.</p><p>Never hard-code API keys in source code or commit them to GitHub.</p><p>For local development, create a file named .env in your project directory:</p><pre>OPENAI_API_KEY=your_api_key_here<br>OPENAI_MODEL=your_supported_model</pre><p>Replace the placeholder values with your actual credentials and a model available to your account.</p><p>Add a .gitignore file:</p><pre>.env<br>.venv/<br>__pycache__/</pre><p>This helps prevent secrets and local environment files from being committed accidentally. Also verify that your .env file is not already tracked by Git.</p><p>Our project structure will look like this:</p><pre>first-llm-app/<br>├── .env<br>├── .gitignore<br>├── app.py<br>└── requirements.txt</pre><p>Create requirements.txt:</p><pre>openai<br>streamlit<br>python-dotenv</pre><p>For a production project, pin and test dependency versions rather than relying on unconstrained versions indefinitely.</p><h3>4. Make Your First LLM API Call</h3><p>Let’s start with the smallest useful example.</p><p>Create a file named app.py:</p><pre>import os</pre><pre>from dotenv import load_dotenv<br>from openai import OpenAI</pre><pre>load_dotenv()</pre><pre>api_key = os.getenv(&quot;OPENAI_API_KEY&quot;)<br>model = os.getenv(&quot;OPENAI_MODEL&quot;)</pre><pre>if not api_key:<br>    raise RuntimeError(&quot;OPENAI_API_KEY is not configured.&quot;)</pre><pre>if not model:<br>    raise RuntimeError(&quot;OPENAI_MODEL is not configured.&quot;)</pre><pre>client = OpenAI(api_key=api_key)<br></pre><pre>def ask_llm(question: str) -&gt; str:<br>    response = client.responses.create(<br>        model=model,<br>        input=question,<br>    )</pre><pre>    return response.output_text<br></pre><pre>if __name__ == &quot;__main__&quot;:<br>    answer = ask_llm(<br>        &quot;Explain database indexes in simple language.&quot;<br>    )</pre><pre>    print(answer)</pre><p>Run the script:</p><pre>python app.py</pre><p>If your API key, model access, network connection, and account configuration are correct, the application should print a generated answer.</p><h3>What is happening here?</h3><p>Let’s break down the important parts.</p><p><strong>1. Load configuration</strong></p><pre>load_dotenv()</pre><pre>api_key = os.getenv(&quot;OPENAI_API_KEY&quot;)<br>model = os.getenv(&quot;OPENAI_MODEL&quot;)</pre><p>The application reads configuration from environment variables instead of storing secrets directly in the source code.</p><p><strong>2. Create the client</strong></p><pre>client = OpenAI(api_key=api_key)</pre><p>The client handles communication with the provider’s API.</p><p><strong>3. Send the request</strong></p><pre>response = client.responses.create(<br>    model=model,<br>    input=question,<br>)</pre><p>We send the selected model and the input text to the API.</p><p><strong>4. Read the generated text</strong></p><pre>return response.output_text</pre><p>The SDK provides a convenient property for retrieving the generated text.</p><p>The provider processes the request and returns a response. Depending on the model and request, the output may contain more than plain text, so applications with more advanced requirements should inspect and handle the relevant response types.</p><p>You’ve now built the core of an LLM application.</p><h3>5. Handle API Errors Properly</h3><p>The previous example works as a starting point, but production applications need to handle failures.</p><p>For example:</p><ul><li>The API key may be invalid.</li><li>The account may have insufficient quota.</li><li>A request may time out.</li><li>The provider may return a rate-limit error.</li><li>The network may be unavailable.</li><li>The requested model may not be accessible.</li></ul><p>Let’s improve our function.</p><pre>from openai import (<br>    OpenAI,<br>    APIConnectionError,<br>    APIStatusError,<br>    APITimeoutError,<br>    RateLimitError,<br>)<br></pre><pre>def ask_llm(question: str) -&gt; str:<br>    try:<br>        response = client.responses.create(<br>            model=model,<br>            input=question,<br>            timeout=30.0,<br>            max_output_tokens=500,<br>        )</pre><pre>        answer = response.output_text</pre><pre>        if not answer:<br>            return &quot;The model returned no text response.&quot;</pre><pre>        return answer</pre><pre>    except RateLimitError:<br>        return &quot;The API rate limit or quota was reached.&quot;</pre><pre>    except APITimeoutError:<br>        return &quot;The request timed out. Please try again.&quot;</pre><pre>    except APIConnectionError:<br>        return &quot;Could not connect to the model provider.&quot;</pre><pre>    except APIStatusError as exc:<br>        return (<br>            f&quot;The model provider returned an API error &quot;<br>            f&quot;(HTTP {exc.status_code}).&quot;<br>        )</pre><p>This example uses the same client and model configured earlier.</p><p>The SDK may also retry some transient errors automatically. Your application should avoid creating uncontrolled retry loops, particularly when requests are expensive or have side effects.</p><h3>A production consideration</h3><p>The function above returns user-friendly messages as strings for simplicity. In a larger application, it’s often better to separate successful results from errors using exceptions, result objects, or a defined error-handling layer.</p><p>This allows your interface to display a helpful message while your backend records the underlying failure for troubleshooting.</p><p>Never expose API keys, raw secrets, or sensitive internal error details to end users.</p><h3>6. Add Conversation History</h3><p>So far, every request is independent.</p><p>Consider this conversation:</p><p><strong>User:</strong> What is a database index?</p><p><strong>Assistant:</strong> A database index helps locate rows more efficiently.</p><p><strong>User:</strong> Can you give me an example?</p><p>Without the earlier conversation, the model may not know what “an example” refers to.</p><p>To support multi-turn conversations, the application needs to send relevant previous messages along with the new question.</p><p>Let’s create a function that accepts a message history.</p><pre>def chat_with_history(messages: list[dict]) -&gt; str:<br>    response = client.responses.create(<br>        model=model,<br>        input=messages,<br>        max_output_tokens=500,<br>    )</pre><pre>    return response.output_text</pre><p>Example usage:</p><pre>messages = [<br>    {<br>        &quot;role&quot;: &quot;system&quot;,<br>        &quot;content&quot;: (<br>            &quot;You are a helpful assistant for &quot;<br>            &quot;software engineers. Explain concepts &quot;<br>            &quot;clearly and use practical examples.&quot;<br>        ),<br>    },<br>    {<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: &quot;What is a database index?&quot;,<br>    },<br>    {<br>        &quot;role&quot;: &quot;assistant&quot;,<br>        &quot;content&quot;: (<br>            &quot;A database index is a data structure &quot;<br>            &quot;that helps a database locate rows &quot;<br>            &quot;more efficiently.&quot;<br>        ),<br>    },<br>    {<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: &quot;Can you give me an example?&quot;,<br>    },<br>]</pre><pre>answer = chat_with_history(messages)<br>print(answer)</pre><p>Here, we supply the conversation as input so the model can use the previous messages when generating its response.</p><p>The roles distinguish instructions, user messages, and assistant replies.</p><p>For this simple example, the history is stored in a Python list. In a web application, conversation history might instead be maintained in session state or persisted in a database.</p><h3>Does the model remember everything automatically?</h3><p>Not necessarily.</p><p>If you send only the latest question, the model generally won’t have access to earlier messages unless the API or application explicitly provides that context through a supported conversation mechanism.</p><p>Your application must decide which history to retain, how much to send, and when to summarize or remove older messages.</p><p>This becomes particularly important as conversations grow, because all that context consumes tokens.</p><h3>7. Build a Chat Interface With Streamlit</h3><p>Let’s turn our command-line program into a small web application.</p><p>Streamlit allows us to build an interactive interface using Python without writing a separate frontend in JavaScript.</p><p>Replace the contents of app.py with the following complete application:</p><pre>import os</pre><pre>import streamlit as st<br>from dotenv import load_dotenv<br>from openai import (<br>    OpenAI,<br>    APIConnectionError,<br>    APIStatusError,<br>    APITimeoutError,<br>    RateLimitError,<br>)</pre><pre>load_dotenv()</pre><pre>api_key = os.getenv(&quot;OPENAI_API_KEY&quot;)<br>model = os.getenv(&quot;OPENAI_MODEL&quot;)</pre><pre>st.set_page_config(<br>    page_title=&quot;AI Assistant&quot;,<br>    page_icon=&quot;🤖&quot;,<br>)</pre><pre>st.title(&quot;🤖 AI Assistant&quot;)<br>st.caption(&quot;Ask questions and explore ideas using an LLM.&quot;)</pre><pre>if not api_key or not model:<br>    st.error(<br>        &quot;Configure OPENAI_API_KEY and OPENAI_MODEL &quot;<br>        &quot;in your environment before starting the app.&quot;<br>    )<br>    st.stop()</pre><pre>client = OpenAI(api_key=api_key, timeout=30.0)<br></pre><pre>def generate_response(messages: list[dict]) -&gt; str:<br>    response = client.responses.create(<br>        model=model,<br>        input=messages,<br>        max_output_tokens=700,<br>    )</pre><pre>    answer = response.output_text</pre><pre>    if not answer:<br>        raise ValueError(&quot;The model returned no text.&quot;)</pre><pre>    return answer<br></pre><pre>if &quot;messages&quot; not in st.session_state:<br>    st.session_state.messages = [<br>        {<br>            &quot;role&quot;: &quot;system&quot;,<br>            &quot;content&quot;: (<br>                &quot;You are a helpful assistant for &quot;<br>                &quot;software engineers. Explain concepts &quot;<br>                &quot;clearly and provide practical examples.&quot;<br>            ),<br>        }<br>    ]<br></pre><pre># Display previous conversation messages.<br>for message in st.session_state.messages:<br>    if message[&quot;role&quot;] == &quot;system&quot;:<br>        continue</pre><pre>    with st.chat_message(message[&quot;role&quot;]):<br>        st.markdown(message[&quot;content&quot;])<br></pre><pre># Accept a new question.<br>if prompt := st.chat_input(&quot;Type your question...&quot;):<br>    st.session_state.messages.append(<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: prompt,<br>        }<br>    )</pre><pre>    with st.chat_message(&quot;user&quot;):<br>        st.markdown(prompt)</pre><pre>    with st.chat_message(&quot;assistant&quot;):<br>        with st.spinner(&quot;Thinking...&quot;):<br>            try:<br>                answer = generate_response(<br>                    st.session_state.messages<br>                )</pre><pre>                st.markdown(answer)</pre><pre>                st.session_state.messages.append(<br>                    {<br>                        &quot;role&quot;: &quot;assistant&quot;,<br>                        &quot;content&quot;: answer,<br>                    }<br>                )</pre><pre>            except RateLimitError:<br>                st.error(<br>                    &quot;The API rate limit or quota was reached.&quot;<br>                )</pre><pre>            except APITimeoutError:<br>                st.error(<br>                    &quot;The request timed out. Please try again.&quot;<br>                )</pre><pre>            except APIConnectionError:<br>                st.error(<br>                    &quot;Could not connect to the model provider.&quot;<br>                )</pre><pre>            except APIStatusError as exc:<br>                st.error(<br>                    f&quot;The provider returned HTTP &quot;<br>                    f&quot;{exc.status_code}.&quot;<br>                )</pre><pre>            except ValueError as exc:<br>                st.error(str(exc))</pre><h3>How does the application work?</h3><p>Let’s examine the key pieces.</p><p><strong>Session state</strong></p><pre>if &quot;messages&quot; not in st.session_state:<br>    st.session_state.messages = [...]</pre><p>Streamlit reruns the application script when users interact with widgets. Session state helps preserve the conversation across these reruns for the current browser session.</p><p><strong>Display previous messages</strong></p><pre>for message in st.session_state.messages:<br>    ...</pre><p>The application renders existing user and assistant messages in the chat interface.</p><p><strong>Accept user input</strong></p><pre>if prompt := st.chat_input(&quot;Type your question...&quot;):<br>    ...</pre><p>The chat input captures the next user message.</p><p><strong>Generate a response</strong></p><pre>answer = generate_response(<br>    st.session_state.messages<br>)</pre><p>The application sends the current conversation history to the model, so it can answer follow-up questions in context.</p><p><strong>Store the response</strong></p><pre>st.session_state.messages.append(<br>    {<br>        &quot;role&quot;: &quot;assistant&quot;,<br>        &quot;content&quot;: answer,<br>    }<br>)</pre><p>The answer is added to the history so the next request can include it.</p><h3>One important limitation</h3><p>This is a learning application, not a production-ready chat service.</p><p>The session state is not a durable database, and the full conversation is sent with each request. A real system needs conversation-length management, persistent storage when required, appropriate authentication, rate limiting, privacy controls, and stronger error handling.</p><h3>8. Run Your Application</h3><p>Save the Streamlit application as app.py.</p><p>Start it using:</p><pre>streamlit run app.py</pre><p>Streamlit will start a local web server and display the address in your terminal. Open the local URL in your browser.</p><p>You should now be able to:</p><ol><li>Enter a question.</li><li>Submit it to the application.</li><li>See the generated response.</li><li>Ask a follow-up question.</li><li>Continue the conversation using the stored session history.</li></ol><p>Try asking:</p><ul><li>“What is a vector database?”</li><li>“How is it different from a relational database?”</li><li>“Give me a simple Python example.”</li></ul><p>The follow-up questions should use the preceding conversation as context.</p><p>If a request fails, check that your API key and model are configured correctly, that your account can access the model, and that you have available API quota.</p><h3>9. Good Practices for LLM Applications</h3><p>A basic application is easy to build. Making it reliable requires additional engineering.</p><h3>Keep secrets out of source code</h3><p>Use environment variables or a proper secret manager. Never expose API keys in browser code, public repositories, or client-side applications.</p><h3>Handle failures gracefully</h3><p>API calls can fail. Use timeouts, handle relevant exceptions, and retry only when appropriate.</p><h3>Manage conversation history</h3><p>Sending every previous message indefinitely can increase token usage and eventually exceed the model’s context limit.</p><p>Consider summarization, truncation strategies, or retrieval when conversations become long.</p><h3>Monitor latency and cost</h3><p>Track request duration, input and output token usage, failures, and usage by application feature.</p><p>This helps you understand the cost and performance of the system.</p><h3>Validate important outputs</h3><p>If an LLM response affects business logic, validate its structure and values before acting on it.</p><p>For example, never treat generated text as a trusted database query or command without suitable controls.</p><h3>Separate application logic from model calls</h3><p>Keep the code that calls the LLM in a dedicated function or module. This makes testing easier and helps you change models or providers without rewriting the entire interface.</p><h3>Protect user data</h3><p>Avoid logging sensitive information unnecessarily. Apply appropriate access controls and retention policies, especially when handling private documents or customer data.</p><h3>10. What Have We Built?</h3><p>Let’s review the application we created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*6VX_qzblbkdgC1dlLmzUAQ.png" /></figure><p>The overall flow is:</p><pre>User<br>  |<br>  v<br>Streamlit interface<br>  |<br>  v<br>Python application<br>  |<br>  +--&gt; Conversation history<br>  |<br>  v<br>LLM API request<br>  |<br>  v<br>Model generates response<br>  |<br>  v<br>Python handles the result<br>  |<br>  v<br>Streamlit displays the answer</pre><p>You now have a simple LLM-powered application that can answer questions and maintain a conversation.</p><p>More importantly, you understand the responsibilities of the major components and how they work together.</p><h3>11. Key Takeaways</h3><ul><li>You can build an LLM application without training a model from scratch.</li><li>An API client allows your Python code to communicate with a hosted model.</li><li>Prompt and conversation history determine the context available to the model.</li><li>Session state can maintain chat history during a Streamlit session.</li><li>API errors, timeouts, credentials, and quota limits need to be handled.</li><li>Conversation history must be managed to control token usage and context size.</li><li>Production systems require security, validation, observability, and cost management.</li></ul><p>The goal is not just to make a model respond to a prompt. It is to build an application that uses the model safely and reliably.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*1ecv2b1w-8RuED87g52Ckg.png" /></figure><h3>What’s Next?</h3><p>In Part 5, we’ll explore <strong>Structured Outputs and Function Calling</strong>.</p><p>We’ll learn how to get predictable, machine-readable responses from an LLM and how to let a model request application-defined tools. These capabilities are essential for building assistants that integrate with APIs, databases, and other software systems.</p><p>We’ll build on the application from this article rather than starting over.</p><p><em>This is Part 4 of the Practical GenAI Engineering series, where we move from LLM fundamentals toward building reliable, production-oriented AI applications.</em></p><p>#GenerativeAI #LLM #Python #AIEngineering #OpenAI #Streamlit #SoftwareEngineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5ea500b8729" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt Engineering: From Basic Prompts to Reliable Outputs]]></title>
            <link>https://medium.com/@abhint2603/prompt-engineering-from-basic-prompts-to-reliable-outputs-73dcc482678c?source=rss-fd6e8dab532------2</link>
            <guid isPermaLink="false">https://medium.com/p/73dcc482678c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Abhishek Nath Tiwari]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 21:47:27 GMT</pubDate>
            <atom:updated>2026-10-24T21:47:27.711Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Learn how to write clear instructions, use proven techniques, and get more consistent results from Large Language Models.</em></p><p>Have you ever asked an AI assistant a question and received an answer that was technically correct but completely different from what you expected?</p><p>Maybe you asked it to summarize a technical article, but it produced a long essay.</p><p>Maybe you asked it to generate JSON, but the response contained extra explanations that broke your application.</p><p>Or perhaps you gave it a coding task, and it returned a solution that ignored one of your requirements.</p><p>The problem isn’t always the model. Sometimes, the instructions need improvement.</p><p>This is where <strong>prompt engineering</strong> becomes important.</p><p>In Part 1, we explored how LLMs generate responses. In Part 2, we learned about tokens, embeddings, context windows, and Transformers.</p><p>In this article, we’ll explore how to communicate more effectively with LLMs, structure prompts, provide examples, request reliable output formats, and improve results through iteration.</p><p>We’ll also look at practical Python examples that you can adapt when building AI applications.</p><h3>1. What Is Prompt Engineering?</h3><p>Prompt engineering is the practice of designing, testing, and improving the instructions and input provided to an LLM to achieve a desired result.</p><p>A prompt can contain much more than a question. It may include:</p><ul><li>Instructions describing the task.</li><li>Context that helps the model understand the situation.</li><li>Examples of the desired output.</li><li>Constraints and rules.</li><li>Input data to process.</li><li>A required output format.</li></ul><p>Consider this request:</p><p><strong>Basic prompt</strong></p><p>“Explain cloud computing.”</p><p>The model has to decide the audience, length, level of detail, and format.</p><p>Now consider an improved prompt:</p><p><strong>Improved prompt</strong></p><p>“You are a technical writer explaining concepts to junior software engineers. Explain cloud computing in simple language using three bullet points and one practical example. Keep the answer under 150 words.”</p><p>The second prompt communicates the audience, task, format, and length.</p><p>It gives the model clearer criteria for producing a useful response.</p><p>However, a detailed prompt does not automatically guarantee correctness. Prompt engineering improves the chances of getting the desired behavior, but important outputs still need to be evaluated.</p><h3>2. Anatomy of a Good Prompt</h3><p>A well-designed prompt often includes six components.</p><h3>1. Role</h3><p>Define the perspective or expertise you want the model to use.</p><p>Example:</p><p>“You are a senior Python developer reviewing code for maintainability.”</p><p>A role can help establish the desired style and focus, but it does not guarantee that the model has expert-level knowledge.</p><h3>2. Context</h3><p>Provide the background information the model needs.</p><p>Example:</p><p>“Our application processes customer orders using Python, FastAPI, and PostgreSQL.”</p><p>Without context, the model might suggest a solution that doesn’t fit your technology stack.</p><h3>3. Instructions</h3><p>Explain exactly what you want the model to do.</p><p>Example:</p><p>“Review this API endpoint and identify potential performance and reliability problems.”</p><p>Use clear action verbs such as explain, summarize, compare, classify, extract, generate, or validate.</p><h3>4. Examples</h3><p>Show the model examples of the input and output you expect.</p><p>Example:</p><p>“Given server error, return SERVER_ERROR. Given invalid input, return INVALID_INPUT.&quot;</p><p>Examples are particularly useful when the desired behavior is difficult to describe using rules alone.</p><h3>5. Constraints</h3><p>Specify limitations or requirements.</p><p>Examples:</p><ul><li>Return no more than five bullet points.</li><li>Use Python 3.12.</li><li>Do not introduce additional dependencies.</li><li>Return only valid JSON matching the requested schema.</li><li>If the supplied text does not contain the answer, state that it is not provided.</li></ul><p>Constraints make the desired behavior more explicit.</p><h3>6. Input data</h3><p>Include the actual material the model should process.</p><p>For example, provide the article, code snippet, database schema, or log output that the model needs to analyze.</p><p>Keep the task instructions separate from the input data where possible. This also makes it easier to handle untrusted content safely.</p><h3>Putting the components together</h3><pre>Role:<br>You are a senior Python developer.</pre><pre>Context:<br>The application uses FastAPI and PostgreSQL.</pre><pre>Task:<br>Review the supplied endpoint for performance issues.</pre><pre>Constraints:<br>Identify the three most important issues.<br>Suggest practical fixes.<br>Do not introduce new dependencies.</pre><pre>Input:<br>[Insert the Python code here]</pre><pre>Output format:<br>Issue | Why it matters | Suggested fix</pre><p>Not every prompt needs all six components. A simple question may need only a direct instruction, while a complex application task may benefit from all of them.</p><p>The goal is clarity, not making every prompt unnecessarily long.</p><h3>3. Basic Prompt vs. Improved Prompt</h3><p>Let’s compare two prompts for a common software engineering task.</p><p><strong>Scenario:</strong> You want an LLM to summarize a technical article about cloud computing.</p><h3>Basic prompt</h3><pre>Summarize this article about cloud computing.</pre><p>This prompt leaves several decisions unspecified.</p><p>The model may return a paragraph, a long explanation, or a summary that focuses on details you don’t need.</p><h3>Improved prompt</h3><pre>You are a technical writer.</pre><pre>Summarize the following article for a junior<br>software engineer.</pre><pre>Requirements:<br>- Identify the three most important ideas.<br>- Use concise bullet points.<br>- Preserve important technical details.<br>- Avoid introducing facts not supported by the article.<br>- Keep the response under 150 words.</pre><pre>Article:<br>[Insert article text here]</pre><p>The improved version defines the audience, expected content, format, and constraints.</p><p>It also asks the model to stay grounded in the supplied article. That instruction can help, although it cannot guarantee that every statement will be accurate.</p><h3>What makes the second prompt better?</h3><p>It reduces ambiguity.</p><p>The model has a clearer understanding of what to produce and how the result will be judged.</p><p>This principle applies to many tasks, including code generation, document summarization, data extraction, classification, and customer support.</p><h3>4. Important Prompt Engineering Techniques</h3><p>There is no single technique that works best for every task. Different approaches are useful depending on the problem.</p><h3>Technique 1: Zero-shot prompting</h3><p>Zero-shot prompting means asking the model to perform a task without providing task-specific examples in the prompt.</p><p>Example:</p><pre>Classify the following message as POSITIVE,<br>NEGATIVE, or NEUTRAL.</pre><pre>Message:<br>&quot;The application is easy to use, but it is slow.&quot;</pre><pre>Return one label only.</pre><p>This approach is simple and often works well for straightforward tasks.</p><p><strong>Use it when:</strong> The task is easy to describe and the desired output is clear.</p><h3>Technique 2: Few-shot prompting</h3><p>Few-shot prompting provides a small number of examples to demonstrate the expected behavior.</p><p>Example:</p><pre>Convert each message into a support category.</pre><pre>Message: &quot;I cannot log in.&quot;<br>Category: ACCOUNT_ACCESS</pre><pre>Message: &quot;My payment failed.&quot;<br>Category: BILLING</pre><pre>Message: &quot;The application crashes on startup.&quot;<br>Category: BUG_REPORT</pre><pre>Now classify:</pre><pre>Message: &quot;I forgot my password.&quot;<br>Category:</pre><p>The examples show the model the classification pattern and output labels you expect.</p><p><strong>Use it when:</strong> The task follows a specific pattern or requires a consistent output style.</p><p>Be careful when selecting examples. Incorrect, contradictory, or unrepresentative examples can lead to worse results.</p><h3>Technique 3: Role prompting</h3><p>Role prompting establishes a perspective or working style.</p><p>Example:</p><pre>You are a backend engineer conducting a code review.</pre><pre>Focus on:<br>- Correctness<br>- Error handling<br>- Performance<br>- Security<br>- Maintainability</pre><pre>Review the following Python function and<br>prioritize the most important findings.</pre><p>This helps direct the model’s attention toward relevant criteria.</p><p><strong>Use it when:</strong> You want the output to follow a particular professional perspective, audience, or review process.</p><h3>Technique 4: Structured-output prompting</h3><p>Sometimes you need a machine-readable response rather than a natural-language explanation.</p><p>For example, a backend service may need to extract information from a support ticket and return JSON.</p><p>Prompt:</p><pre>Extract the following fields from the text:<br>- ticket_id<br>- category<br>- priority</pre><pre>Return a JSON object with exactly these fields.<br>Use null if a field is missing.</pre><pre>Do not include explanatory text.</pre><p>Possible output:</p><pre>{<br>  &quot;ticket_id&quot;: &quot;T-1042&quot;,<br>  &quot;category&quot;: &quot;BILLING&quot;,<br>  &quot;priority&quot;: &quot;HIGH&quot;<br>}</pre><p>This makes the output easier for another program to consume.</p><p>For production systems, don’t rely on prompt wording alone to guarantee valid JSON. Where available, use API-supported structured outputs or schema constraints, then validate the response in your application.</p><h3>Technique 5: Decomposition</h3><p>Complex tasks are often easier to manage when divided into smaller steps.</p><p>Suppose you ask an LLM to analyze a large technical document, identify architectural risks, recommend improvements, and create an implementation plan in a single prompt.</p><p>A more manageable workflow could be:</p><ol><li>Extract the system’s components and dependencies.</li><li>Identify potential reliability and performance risks.</li><li>Prioritize the risks by impact.</li><li>Generate recommendations for the highest-priority issues.</li><li>Produce an implementation plan.</li></ol><p>The steps can be executed separately or orchestrated by an application.</p><p><strong>Use it when:</strong> The task contains multiple distinct stages or intermediate results need to be checked.</p><p>Decomposition is a workflow design technique, not a guarantee that the model’s reasoning will be correct.</p><h3>Technique 6: Iterative refinement</h3><p>Your first prompt doesn’t have to be your final prompt.</p><p>Start with a prompt, inspect the output, identify the problem, and refine the instructions.</p><p>For example:</p><p><strong>Attempt 1:</strong> The answer is too long.</p><p><strong>Refinement:</strong> Specify a maximum length and a concise format.</p><p><strong>Attempt 2:</strong> The answer is concise but misses important details.</p><p><strong>Refinement:</strong> Ask for the three most important technical points and require that each be preserved.</p><p><strong>Attempt 3:</strong> The output is useful but inconsistent across inputs.</p><p><strong>Refinement:</strong> Add representative examples, define the output schema, and test it on a wider set of cases.</p><p>This process turns prompt engineering into a practical engineering discipline rather than guesswork.</p><h3>5. Using Prompt Engineering With Python</h3><p>Let’s look at a realistic example using the OpenAI Python SDK.</p><p>We’ll compare a basic prompt with a more structured prompt.</p><h3>Step 1: Install the SDK</h3><pre>pip install openai</pre><h3>Step 2: Configure the API client</h3><p>Set your API key through an environment variable named OPENAI_API_KEY. Never hard-code a secret key in source code or commit it to a public repository.</p><pre>import os<br>from openai import OpenAI</pre><pre>client = OpenAI(<br>    api_key=os.environ[&quot;OPENAI_API_KEY&quot;]<br>)</pre><h3>Step 3: Create a basic prompt</h3><pre>article = &quot;&quot;&quot;<br>Cloud computing provides computing resources<br>such as servers, storage, and databases over<br>the internet. It helps organizations scale<br>infrastructure based on demand.<br>&quot;&quot;&quot;</pre><pre>basic_prompt = f&quot;&quot;&quot;<br>Summarize this article:</pre><pre>{article}<br>&quot;&quot;&quot;</pre><pre>response = client.responses.create(<br>    model=&quot;YOUR_SUPPORTED_MODEL&quot;,<br>    input=basic_prompt<br>)</pre><pre>print(response.output_text)</pre><p>Replace YOUR_SUPPORTED_MODEL with a model available to your API account.</p><p>This example uses the Responses API. The exact model availability and capabilities depend on your account and the model you select.</p><h3>Step 4: Improve the prompt</h3><p>Now let’s make the task more specific.</p><pre>improved_prompt = f&quot;&quot;&quot;<br>You are a technical writer.</pre><pre>Summarize the following article for a<br>junior software engineer.</pre><pre>Requirements:<br>- Return exactly three bullet points.<br>- Preserve the key technical information.<br>- Use simple, direct language.<br>- Do not introduce unsupported facts.<br>- Keep each bullet point concise.</pre><pre>Article:<br>{article}<br>&quot;&quot;&quot;</pre><pre>response = client.responses.create(<br>    model=&quot;YOUR_SUPPORTED_MODEL&quot;,<br>    input=improved_prompt<br>)</pre><pre>print(response.output_text)</pre><p>The improved prompt makes the expected output clearer.</p><p>Notice that the article is supplied as input data, while the instructions describe what to do with it.</p><p>For more complex applications, you can also use clear delimiters around input text and explicitly instruct the model to treat that text as data rather than as instructions.</p><h3>What should you measure?</h3><p>Don’t assume the second prompt is better simply because it is longer.</p><p>Test both prompts on several representative articles and compare:</p><ul><li>Whether important facts are preserved.</li><li>Whether the response follows the requested format.</li><li>Whether unsupported claims are introduced.</li><li>Whether the output is concise enough.</li><li>Whether the results are consistent across different inputs.</li><li>The token usage, latency, and cost.</li></ul><p>A good prompt is one that improves the outcomes that matter for your application.</p><h3>6. Getting Reliable JSON Output</h3><p>Let’s go one step further.</p><p>Imagine you’re building a support-ticket processing service. Your backend receives a ticket and needs to extract a category and priority.</p><p>You want a predictable response that your Python code can process.</p><p>A prompt might look like this:</p><pre>ticket = &quot;&quot;&quot;<br>Customer says the payment failed twice<br>and they were charged for one attempt.<br>&quot;&quot;&quot;</pre><pre>prompt = f&quot;&quot;&quot;<br>Extract information from the support ticket.</pre><pre>Return a JSON object containing:<br>- category: string<br>- priority: LOW, MEDIUM, or HIGH<br>- summary: string</pre><pre>Use only information supported by the ticket.<br>Do not invent missing details.</pre><pre>Ticket:<br>&lt;ticket&gt;<br>{ticket}<br>&lt;/ticket&gt;<br>&quot;&quot;&quot;</pre><p>This is a useful start, but the prompt alone does not guarantee that the output will always be valid JSON or use an allowed priority.</p><p>For production applications, a stronger approach is to use a supported structured-output feature where available and validate the result against a schema.</p><p>For example, using Pydantic:</p><pre>from pydantic import BaseModel<br>from typing import Literal</pre><pre>class SupportTicket(BaseModel):<br>    category: str<br>    priority: Literal[&quot;LOW&quot;, &quot;MEDIUM&quot;, &quot;HIGH&quot;]<br>    summary: str</pre><p>You can then validate data parsed from the model’s response:</p><pre>data = {<br>    &quot;category&quot;: &quot;BILLING&quot;,<br>    &quot;priority&quot;: &quot;HIGH&quot;,<br>    &quot;summary&quot;: &quot;Customer reports repeated payment failure.&quot;<br>}</pre><pre>ticket_result = SupportTicket.model_validate(data)</pre><pre>print(ticket_result.model_dump())</pre><p>Here, data is an illustrative Python dictionary representing a parsed response. It is not a real model response.</p><p>Pydantic checks that the values conform to the declared schema and rejects invalid values. In a real application, you’ll also need to handle parsing failures, API errors, and cases where the model cannot extract the required information.</p><p><strong>The key lesson:</strong> Use prompts to communicate intent, structured-output capabilities to constrain the response where possible, and application-level validation to protect downstream systems.</p><h3>7. Common Prompt Engineering Mistakes</h3><p>Even experienced developers can create prompts that produce unreliable results.</p><h3>Mistake 1: Being too vague</h3><p>Weak:</p><p>“Improve this code.”</p><p>Better:</p><p>“Review this Python function for correctness, performance, and error handling. Identify the three most important issues and suggest minimal changes.”</p><h3>Mistake 2: Providing insufficient context</h3><p>Weak:</p><p>“Why is my API slow?”</p><p>Better:</p><p>“Here is a FastAPI endpoint, its SQL query, and the observed latency. Identify likely bottlenecks and explain which measurements would help confirm the cause.”</p><h3>Mistake 3: Giving conflicting instructions</h3><p>For example:</p><p>“Explain every detail in depth, but keep the response to one sentence.”</p><p>These requirements may conflict.</p><p>Define priorities or separate the task into stages when necessary.</p><h3>Mistake 4: Assuming the model will always follow the requested format</h3><p>A prompt saying “return valid JSON” is not, by itself, a complete validation strategy.</p><p>Use structured outputs, parsing, schema validation, and appropriate error handling.</p><h3>Mistake 5: Putting too much into one prompt</h3><p>A request to analyze, rewrite, validate, compare, and deploy a system in one step can make it difficult to isolate errors.</p><p>Break complex work into stages when the task benefits from intermediate checks.</p><h3>Mistake 6: Ignoring input token limits</h3><p>Large documents, long conversations, and excessive examples consume context.</p><p>Retrieve relevant information, summarize history where appropriate, and monitor token usage.</p><h3>Mistake 7: Never testing the prompt</h3><p>A prompt that works on one example may fail on another.</p><p>Test with normal cases, edge cases, ambiguous inputs, and unexpected data.</p><h3>Mistake 8: Treating prompt injection as a wording problem</h3><p>If an application processes untrusted documents or user-supplied text, that content may contain malicious instructions.</p><p>Separating instructions from data can help, but it is not a complete defense. Applications also need appropriate access controls, tool permissions, input handling, and security testing.</p><h3>8. Best Practices for Production Prompt Engineering</h3><p>If you’re building a real AI application, treat prompts as part of your software system.</p><p>Here are practical guidelines.</p><p><strong>Be specific.</strong> Describe the task and the expected outcome clearly.</p><p><strong>Provide relevant context.</strong> Include the information required for the task, but avoid unnecessary material.</p><p><strong>Define output requirements.</strong> Specify the format, allowed values, and length where these matter.</p><p><strong>Use examples selectively.</strong> Few-shot examples should be accurate and representative.</p><p><strong>Separate instructions from untrusted input.</strong> Use clear delimiters and treat external content as data, not as trusted instructions.</p><p><strong>Validate important outputs.</strong> Check JSON, types, ranges, and business rules before using the results.</p><p><strong>Build an evaluation set.</strong> Maintain representative inputs and expected outcomes so you can compare prompt changes.</p><p><strong>Version your prompts.</strong> Track changes to prompts just as you track changes to application code.</p><p><strong>Monitor cost and latency.</strong> A prompt can improve quality while increasing token usage, so measure both.</p><p><strong>Evaluate before deploying changes.</strong> Test prompt revisions against the same cases to understand whether they improve overall performance.</p><p>A prompt is not reliable just because it works once. Reliability comes from clear instructions, testing, evaluation, and application-level safeguards.</p><h3>9. A Simple Prompt Evaluation Framework</h3><p>Suppose you have three versions of a prompt for summarizing technical documents.</p><p>Instead of choosing the one that sounds best, define evaluation criteria.</p><p>CriterionWhat to checkAccuracyDoes the summary preserve the source’s facts?CompletenessAre the important points included?FormatDoes the output follow the required structure?ConsistencyDoes it behave well across different documents?CostHow many input and output tokens are used?LatencyHow long does the request take?</p><p>You can score each criterion using a simple rubric, such as 1 to 5, and compare the prompt versions on the same test cases.</p><p>For tasks where incorrect answers are costly, use stronger verification and domain-specific evaluation rather than relying only on subjective quality scores.</p><p>For larger systems, evaluation may include automated checks, human review, model-based grading with appropriate safeguards, and monitoring of real-world failures.</p><p>The aim is to make prompt improvements measurable.</p><h3>10. Key Takeaways</h3><p>Let’s recap what we’ve learned.</p><ul><li><strong>Prompt engineering</strong> is the process of designing and improving model inputs to achieve a desired result.</li><li><strong>Good prompts</strong> often specify the role, context, instructions, examples, constraints, and input data.</li><li><strong>Zero-shot prompting</strong> performs a task without task-specific examples; <strong>few-shot prompting</strong> includes examples.</li><li><strong>Structured outputs</strong> make it easier to integrate LLM responses into software applications.</li><li><strong>Decomposition and iteration</strong> can help with complex tasks and improve results.</li><li><strong>Prompting alone does not guarantee correctness or valid output.</strong></li><li><strong>Production systems need evaluation, validation, security controls, and monitoring.</strong></li><li><strong>Prompt quality should be measured</strong>, not judged only by a single impressive response.</li></ul><p>Prompt engineering is an important skill, but it is only one component of GenAI engineering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*uEOBcPXgyM93ehYbN7Pm6w.png" /></figure><p>The real goal is not to write clever instructions. It is to build an application that produces useful, consistent, and verifiable results for the tasks it needs to perform.</p><h3>What’s Next?</h3><p>In Part 4, we’ll move from concepts into application development:</p><p><strong>Build Your First LLM Application with Python</strong></p><p>We’ll create a small application that sends requests to an LLM, handles responses and errors, and establishes the foundation for more advanced features such as conversation state, streaming, retrieval, and tool use.</p><p>We’ll begin with a simple working application and gradually evolve it into a more practical AI engineering project.</p><p><em>This article is Part 3 of the </em><strong><em>Practical GenAI Engineering series</em></strong><em>, moving from LLM fundamentals toward reliable, production-oriented AI applications.</em></p><p>#GenerativeAI #PromptEngineering #LLM #Python #AIEngineering #MachineLearning</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73dcc482678c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tokens, Context Windows, Embeddings, and Transformers]]></title>
            <link>https://medium.com/@abhint2603/tokens-context-windows-embeddings-and-transformers-a7fb534c28ec?source=rss-fd6e8dab532------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7fb534c28ec</guid>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <dc:creator><![CDATA[Abhishek Nath Tiwari]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 21:42:02 GMT</pubDate>
            <atom:updated>2026-10-24T21:42:02.897Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The building blocks every GenAI engineer should understand.</em></p><p>In Part 1 of this series, we explored how Large Language Models (LLMs) work, why they predict the next token, and how they generate responses.</p><p>Now let’s look deeper.</p><p>When you send a message to an AI assistant, the model doesn’t process your words in exactly the same way a human reads them. Your text is converted into numerical representations, processed through neural network layers, and used to generate a response.</p><p>Four concepts help explain this process:</p><ul><li><strong>Tokens:</strong> How text is divided into smaller units.</li><li><strong>Context windows:</strong> How much information a model can process in one request.</li><li><strong>Embeddings:</strong> How tokens and other data are represented as vectors.</li><li><strong>Transformers:</strong> The neural network architecture that helps models process relationships between tokens.</li></ul><p>Understanding these concepts will make it easier to build LLM applications, implement Retrieval-Augmented Generation (RAG), manage API costs, and debug AI systems.</p><p>Let’s explore each concept with examples.</p><h3>1. What Are Tokens?</h3><p>Humans communicate using words and sentences. LLMs typically process text as sequences of tokens.</p><p>A token can represent:</p><ul><li>A complete word.</li><li>Part of a word.</li><li>Punctuation.</li><li>A number or other text fragment.</li><li>Whitespace or other characters, depending on the tokenizer.</li></ul><p>For example, consider this sentence:</p><p>Generative AI is amazing!</p><p>A tokenizer might divide it into pieces such as:</p><pre>Generative | AI | is | amazing | !</pre><p>This is only an illustrative split. The actual tokenization depends on the model’s tokenizer.</p><p>Each token is mapped to a numerical identifier called a <strong>token ID</strong>. The model processes these IDs through its embedding and neural network layers.</p><p>Conceptually, the process looks like this:</p><pre>Input text<br>    |<br>    v<br>&quot;Generative AI is amazing!&quot;<br>    |<br>    v<br>Tokenizer<br>    |<br>    v<br>Token IDs<br>    |<br>    v<br>Embedding layer<br>    |<br>    v<br>Transformer</pre><p>The token IDs are not the meaning of the words. They are identifiers used to look up learned numerical representations.</p><h3>Why don’t LLMs simply use whole words?</h3><p>Imagine creating a vocabulary containing every possible word, name, technical term, spelling variation, and word in every language.</p><p>That vocabulary would be enormous, and unfamiliar words would be difficult to handle.</p><p>Modern tokenizers often use subword tokenization. A common family of approaches is <strong>Byte Pair Encoding (BPE)</strong>, which can represent frequent text fragments efficiently while still handling less common words through smaller units.</p><p>For example, an unfamiliar word might be split into several subword tokens rather than requiring the tokenizer to know the entire word as one unit.</p><p>This helps models handle:</p><ul><li>Technical terminology.</li><li>New or uncommon words.</li><li>Names and spelling variations.</li><li>Multiple languages.</li><li>Different forms of the same word.</li></ul><h3>Why should developers care about tokens?</h3><p>Tokens matter because many LLM APIs use them to determine:</p><p><strong>Input usage:</strong> How much text and context you send to the model.</p><p><strong>Output usage:</strong> How much generated content the model produces.</p><p><strong>Context limits:</strong> Whether a request fits within the model’s supported context window.</p><p><strong>Cost:</strong> API pricing is often based partly on input and output token counts.</p><p>A 1,000-word document does not always produce the same number of tokens as another 1,000-word document. The token count depends on the text and tokenizer.</p><p>This is why measuring tokens is more reliable than estimating usage by word count alone.</p><h3>2. How to Count Tokens Using Python</h3><p>Let’s try a practical example.</p><p>For this demonstration, we’ll use tiktoken, a Python library that provides tokenization for supported OpenAI model encodings.</p><p>First, install it:</p><pre>pip install tiktoken</pre><p>Now tokenize a sentence:</p><pre>import tiktoken</pre><pre>text = &quot;Generative AI is amazing!&quot;</pre><pre>encoding = tiktoken.get_encoding(&quot;cl100k_base&quot;)</pre><pre>tokens = encoding.encode(text)</pre><pre>print(&quot;Token IDs:&quot;, tokens)<br>print(&quot;Token count:&quot;, len(tokens))<br>print(&quot;Decoded tokens:&quot;, encoding.decode(tokens))</pre><p>The output includes the token IDs, the number of tokens, and the reconstructed text.</p><p>The exact token IDs and count depend on the encoding and input. Don’t assume that this encoding matches every model.</p><h3>What did we learn?</h3><p>The tokenizer converts text into token IDs that a compatible model can process.</p><p>The example above demonstrates tokenization only. It does not generate embeddings, call an LLM, or produce an AI response.</p><p><strong>Practical takeaway:</strong> Before sending large documents to an LLM API, estimate their token count. This helps you avoid context-limit errors and make better cost estimates.</p><h3>3. What Are Embeddings?</h3><p>Token IDs are useful identifiers, but they don’t directly express semantic meaning.</p><p>For a model to learn useful relationships, tokens are represented using numerical vectors called <strong>embeddings</strong>.</p><p>An embedding is a list of numbers representing an item in a mathematical space.</p><p>For example, a simplified embedding might look like this:</p><pre>&quot;cat&quot; -&gt; [0.12, -0.45, 0.81, 0.27, ...]</pre><pre>&quot;dog&quot; -&gt; [0.15, -0.40, 0.77, 0.31, ...]</pre><pre>&quot;car&quot; -&gt; [-0.62, 0.18, 0.09, -0.53, ...]</pre><p>These numbers are illustrative, not actual embeddings from a particular model.</p><p>Real embeddings can contain hundreds or thousands of dimensions.</p><p>During training, embedding representations are learned so that they help the model perform its task.</p><h3>How do embeddings capture relationships?</h3><p>Consider these words:</p><ul><li>Cat</li><li>Dog</li><li>Car</li></ul><p>In a well-trained embedding space, representations of related concepts may share useful patterns. A semantic embedding model might place “cat” and “dog” closer together than “cat” and “car”.</p><p>However, this is not guaranteed for every embedding model, and similarity depends on how the model was trained.</p><p>Embeddings can represent much more than individual words. Depending on the model, they can represent:</p><ul><li>Sentences.</li><li>Paragraphs.</li><li>Documents.</li><li>Images.</li><li>Other kinds of data.</li></ul><p>For text applications, sentence and document embeddings are particularly useful because they can capture meaning beyond exact word matches.</p><h3>Token embeddings vs. contextual representations</h3><p>There is an important distinction here.</p><p><strong>Token embeddings</strong> are the initial learned vectors associated with token IDs.</p><p>As tokens pass through Transformer layers, their representations are updated using surrounding context. The resulting <strong>contextual representations</strong> can encode different information about the same token depending on where it appears.</p><p>For example:</p><p>“The bank approved the loan.”</p><p>“We sat beside the river bank.”</p><p>The word “bank” appears in two different contexts. A Transformer can build different contextual representations for the token in each sentence.</p><p>This is one reason Transformers are more powerful than systems that treat every word as having a single fixed representation.</p><h3>4. What Are Embeddings Used For?</h3><p>Embeddings are a fundamental building block of semantic search and Retrieval-Augmented Generation.</p><p>Suppose you have thousands of technical documents.</p><p>A traditional keyword search might look for documents containing the exact phrase “reduce database query time.”</p><p>But a user might ask:</p><p>“How can I make my database queries faster?”</p><p>The wording differs, yet the intent is similar.</p><p>A semantic search system can convert the query and documents into embeddings, then compare their vector representations to identify relevant content.</p><p>A simplified workflow looks like this:</p><pre>Documents<br>    |<br>    v<br>Embedding model<br>    |<br>    v<br>Document vectors<br>    |<br>    v<br>Vector index or database</pre><p>When a user submits a question:</p><pre>User question<br>    |<br>    v<br>Embedding model<br>    |<br>    v<br>Query vector<br>    |<br>    v<br>Similarity search<br>    |<br>    v<br>Relevant documents</pre><p>Those retrieved documents can then be supplied to an LLM to help it generate a grounded answer.</p><p>This approach is a core component of many RAG applications, which we’ll build in a later part of this series.</p><h3>Are embeddings the same as a vector database?</h3><p>No.</p><p>An <strong>embedding model</strong> generates vector representations.</p><p>A <strong>vector database or vector index</strong> stores or indexes vectors and helps retrieve similar items efficiently.</p><p>They solve different parts of the problem and are often used together.</p><h3>5. What Is a Context Window?</h3><p>A context window is the maximum amount of tokenized information a model can process within a single request, subject to the model’s specific limits.</p><p>It may include:</p><ul><li>System instructions.</li><li>User messages.</li><li>Conversation history.</li><li>Retrieved documents.</li><li>Tool outputs.</li><li>Other supplied context.</li><li>Space needed for generated output, depending on the API and model limits.</li></ul><p>Imagine a model with a context window of 128,000 tokens.</p><p>That does not mean you should always send 128,000 tokens. Your actual request needs to fit within the model’s limits, including the input and any output budget that applies.</p><p>Consider this simplified illustration:</p><pre>Example context budget: 10,000 tokens</pre><pre>+----------------------------------+<br>| System instructions:   500       |<br>| Conversation history: 1,500       |<br>| Retrieved documents:  5,000       |<br>| Current question:      500       |<br>| Remaining budget:    2,500       |<br>+----------------------------------+</pre><p>These numbers are illustrative. Actual limits and accounting vary by model and API.</p><h3>What happens when the context window is exceeded?</h3><p>Depending on the API and application, the request may be rejected, or the application may need to shorten, summarize, or otherwise reduce the input.</p><p>A longer conversation can eventually exceed the available context if the application keeps sending the entire history with every request.</p><p>This is why production applications need a strategy for managing conversation history.</p><h3>How can developers manage context efficiently?</h3><p>Useful techniques include:</p><p><strong>1. Keep relevant history</strong></p><p>Send the information needed to answer the current question rather than blindly including every previous message.</p><p><strong>2. Summarize older conversations</strong></p><p>Maintain a concise summary of relevant decisions and facts instead of resending a lengthy conversation.</p><p><strong>3. Retrieve relevant documents</strong></p><p>Use search or RAG to select the most useful sections rather than including an entire document collection.</p><p><strong>4. Limit unnecessary output</strong></p><p>Set appropriate output limits and avoid generating content the application doesn’t need.</p><p><strong>5. Monitor token usage</strong></p><p>Track input and output tokens to understand cost, latency, and context consumption.</p><p>A larger context window can be useful, but it does not guarantee that the model will use every piece of information equally well. Relevance and retrieval quality still matter.</p><h3>6. What Is a Transformer?</h3><p>A Transformer is a neural network architecture that uses attention mechanisms and other neural network operations to process sequences.</p><p>Transformers became central to modern language models because they can learn complex relationships across token sequences and can be trained efficiently at scale.</p><p>At a high level, a text-generating Transformer processes information through several stages.</p><pre>Input text<br>    |<br>    v<br>Tokenization<br>    |<br>    v<br>Token IDs<br>    |<br>    v<br>Token embeddings<br>    |<br>    v<br>Positional information<br>    |<br>    v<br>Transformer layers<br>    |<br>    v<br>Output scores<br>    |<br>    v<br>Next-token selection</pre><p>Let’s understand the main components.</p><h3>Token embeddings</h3><p>Each token ID is mapped to a learned numerical vector.</p><p>These vectors provide the initial representations that the Transformer processes.</p><h3>Positional information</h3><p>The model needs information about token order.</p><p>Different Transformer architectures use different ways to represent or incorporate position. The essential idea is that the model must be able to distinguish sequences where order changes the meaning.</p><p>For example:</p><p>“The dog chased the cat.”</p><p>“The cat chased the dog.”</p><p>The same words appear, but their order changes the meaning.</p><h3>Self-attention</h3><p>Self-attention allows a token’s representation to incorporate information from other relevant positions in the sequence.</p><p>This helps the model process relationships between words and other tokens in context.</p><h3>Feed-forward network</h3><p>Transformer layers also contain neural network operations that transform the token representations after attention.</p><p>Multiple layers build increasingly sophisticated representations of the input.</p><h3>Output layer</h3><p>For a typical autoregressive language model, the final representation is used to calculate scores for possible next tokens.</p><p>A decoding strategy then selects the next token, and the process repeats to generate a response.</p><h3>7. Understanding Self-Attention With an Example</h3><p>Consider this sentence:</p><p>“The developer placed the laptop in the bag because it was heavy.”</p><p>What does “it” refer to?</p><p>The likely interpretation is that the laptop was heavy, although the exact interpretation can depend on context.</p><p>Self-attention gives a model a mechanism for processing relationships between positions in the sentence. When computing a representation for a token, the attention mechanism uses learned queries, keys, and values to combine information from other positions.</p><p>At a high level, attention involves three concepts:</p><ul><li><strong>Query:</strong> What information a position is looking for.</li><li><strong>Key:</strong> Information used to determine how relevant another position is.</li><li><strong>Value:</strong> The information that can be combined from that position.</li></ul><p>The model calculates attention weights and uses them to combine value vectors.</p><p>You do not need to memorize the equations to understand the idea: attention lets the model weigh information from different parts of the input rather than treating every token independently.</p><p>Modern Transformers commonly use multi-head attention, which lets the model process different learned relationships in parallel.</p><p>Importantly, attention is a computational mechanism, not proof that the model understands language exactly as a human does.</p><h3>8. Putting It All Together</h3><p>Let’s follow a question through a simplified LLM pipeline.</p><p>Suppose the user asks:</p><p>“Explain how database indexes improve query performance.”</p><h3>Step 1: Tokenization</h3><p>The text is divided into tokens, which are mapped to token IDs.</p><h3>Step 2: Embedding</h3><p>The token IDs are mapped to learned vectors.</p><h3>Step 3: Transformer processing</h3><p>The model processes the sequence through its Transformer layers, using attention and other neural network operations to build contextual representations.</p><h3>Step 4: Next-token prediction</h3><p>The model calculates scores for possible next tokens.</p><h3>Step 5: Token selection</h3><p>A decoding strategy selects a token, which is added to the generated sequence.</p><h3>Step 6: Repeated generation</h3><p>The model repeats the prediction process until it reaches a stopping condition or an applicable generation limit.</p><p>The complete process can be summarized as:</p><pre>User question<br>      |<br>      v<br>   Tokenizer<br>      |<br>      v<br>    Token IDs<br>      |<br>      v<br>Token embeddings<br>      |<br>      v<br> Transformer layers<br>      |<br>      v<br> Next-token scores<br>      |<br>      v<br>  Select a token<br>      |<br>      v<br> Repeat until done<br>      |<br>      v<br>Generated response</pre><p>This is a simplified explanation of a typical text-generation workflow. Real applications may also use retrieval, tools, safety controls, and output validation.</p><h3>9. A Common Confusion: Are Tokens, Embeddings, and Context the Same Thing?</h3><p>No. They are related, but each has a different role.</p><p>ConceptWhat it meansWhy it mattersTokenA unit of text processed by the modelDetermines how text is dividedToken IDA numerical identifier for a tokenLets the model look up its representationEmbeddingA learned vector representationProvides numerical features for model processingContext windowThe model’s token-capacity limit for a requestDetermines how much information can fitTransformerA neural network architectureProcesses relationships and builds representationsAttentionA mechanism used within TransformersHelps incorporate information from other positions</p><p>Understanding these distinctions will make it easier to reason about LLM API limits, semantic search, retrieval pipelines, and model behavior.</p><h3>10. Key Takeaways</h3><p>Let’s summarize the most important ideas.</p><ul><li><strong>Tokens</strong> are the units into which text is divided for model processing.</li><li><strong>Token IDs</strong> are numerical identifiers, not representations of semantic meaning by themselves.</li><li><strong>Embeddings</strong> map tokens or other inputs into numerical vectors.</li><li><strong>Context windows</strong> limit how much tokenized information a model can process in a request.</li><li><strong>Transformers</strong> process token representations through attention and neural network layers.</li><li><strong>Self-attention</strong> helps models incorporate information from different positions in a sequence.</li><li><strong>Semantic search</strong> uses embeddings to retrieve content based on similarity, not just exact keyword matches.</li><li><strong>Context management</strong> is essential for building efficient and reliable AI applications.</li></ul><p>You now have a clearer picture of how text becomes numerical data, how models process context, and why embeddings are important for modern AI applications.</p><h3>What’s Next?</h3><p>In Part 3, we’ll explore <strong>Prompt Engineering: From Basic Prompts to Reliable Outputs</strong>.</p><p>We’ll learn how to write clearer instructions, provide examples, structure prompts, separate instructions from input data, and evaluate whether a prompt consistently produces the output your application needs.</p><p>The goal is to move from understanding the model to learning how to communicate with it effectively.</p><p><em>This article is Part 2 of the </em><strong><em>Practical GenAI Engineering series</em></strong><em>, where we move from LLM fundamentals toward building reliable, production-oriented AI applications.</em></p><p>#GenerativeAI #LLM #AIEngineering #Python #MachineLearning #Embeddings #Transformers</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7fb534c28ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generative AI Explained: How LLMs Actually Work]]></title>
            <link>https://medium.com/@abhint2603/generative-ai-explained-how-llms-actually-work-3cea170b6a5d?source=rss-fd6e8dab532------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cea170b6a5d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Abhishek Nath Tiwari]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 16:18:16 GMT</pubDate>
            <atom:updated>2026-10-17T16:18:16.371Z</atom:updated>
            <content:encoded><![CDATA[<p><em>From understanding large language models to learning what happens when you send your first prompt.</em></p><p>Generative AI has quickly become one of the most talked-about technologies in software engineering.</p><p>Developers are using it to write code, summarize documents, build chatbots, analyze data, and create applications that interact with users through natural language.</p><p>But have you ever wondered what actually happens when you type a question into an AI assistant and receive an answer seconds later?</p><p>Is it searching the internet? Is it retrieving a stored answer? Does it understand language the way humans do?</p><p>To build reliable AI applications, we need to understand what happens beneath the interface.</p><p>In this article, we’ll explore the fundamentals of Generative AI and Large Language Models (LLMs), how they generate text, how training differs from inference, and how developers can start building applications with them.</p><p>No advanced mathematics or machine learning background is required.</p><h3>1. What Is Generative AI?</h3><p>Generative AI refers to AI systems that can produce new content based on patterns learned from data.</p><p>That content can include:</p><ul><li>Text and conversations</li><li>Images and illustrations</li><li>Audio and speech</li><li>Video</li><li>Computer code</li></ul><p>Traditional software generally follows explicitly programmed instructions. A generative model, on the other hand, learns statistical patterns from training data and uses those patterns to generate outputs.</p><p>For example, consider these two systems.</p><p><strong>Traditional program</strong></p><p>You provide two numbers, and the program calculates their sum using a defined operation.</p><p><strong>Generative AI application</strong></p><p>You provide a question such as, “Explain how a database index improves query performance,” and the model generates a natural-language explanation.</p><p>The important distinction is that the second system generates an answer rather than simply executing a predefined response for that exact question.</p><p>Generative AI isn’t limited to text. The same broad idea applies to models that generate images, audio, video, and other forms of content.</p><h3>2. What Is a Large Language Model?</h3><p>A Large Language Model, commonly called an LLM, is a machine learning model trained on large amounts of data to learn patterns in language and generate text.</p><p>Examples include models from OpenAI, Google, Anthropic, and Meta.</p><p>LLMs are commonly built using a neural network architecture called the <strong>Transformer</strong>.</p><p>At a high level, an LLM learns relationships between words, parts of words, and other tokens. Given an input, it uses the context to predict what token should come next.</p><p>Consider this sentence:</p><blockquote><em>The capital of France is ___</em></blockquote><p>A model might assign a high probability to “Paris.”</p><p>Now consider:</p><blockquote><em>She opened the refrigerator and took out a bottle of ___</em></blockquote><p>Depending on the surrounding context and what the model learned during training, it might assign higher probabilities to words such as “water” or “milk.”</p><p>These are simplified examples, but they illustrate the central idea: the model uses context to estimate likely continuations.</p><p>Modern LLMs can use this capability to perform many tasks, including answering questions, writing code, translating text, and summarizing documents.</p><h3>Does an LLM simply memorize answers?</h3><p>Not exactly.</p><p>An LLM learns patterns and relationships from training data. Some information can be memorized, but its behavior is not equivalent to a conventional database that stores a complete answer for every possible question.</p><p>The model generates responses using its learned parameters and the context provided at inference time.</p><p>This also explains one of its limitations: a fluent, confident-sounding answer is not necessarily a correct answer.</p><h3>3. The Architecture Behind an LLM</h3><p>Let’s look at the high-level journey from a user prompt to a generated response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*3azdNWMR972jWIVyZKLf6A.png" /></figure><p><em>Figure 1: How an LLM processes a prompt and generates a response.</em></p><p>This is a simplified view of a typical text-generation pipeline. Real systems may also include system instructions, safety checks, retrieval, tool calls, and post-processing.</p><p>Let’s understand the important components.</p><h3>4. Tokens: How Models Process Text</h3><p>Humans read words and sentences. Language models typically process <strong>tokens</strong>, which are numerical representations of text units.</p><p>A token might represent:</p><ul><li>A complete word</li><li>Part of a word</li><li>Punctuation</li><li>Whitespace or another text fragment</li></ul><p>For example, the sentence:</p><p>Generative AI is useful.</p><p>could be split into several tokens. The exact split depends on the tokenizer used by the model.</p><p>The resulting tokens are converted into token IDs, which the model can process.</p><p>Why does this matter?</p><p>Because many model limits and costs are based on tokens rather than the number of words or characters you write.</p><p>Tokens are used to measure things such as:</p><ul><li>Input length</li><li>Output length</li><li>Context-window usage</li><li>API consumption and pricing</li></ul><p>A <strong>context window</strong> is the amount of tokenized information a model can process within a single request, including relevant instructions, conversation history, and other supplied content.</p><p>A larger context window can accommodate more information, but it does not guarantee that a model will use every part of that information equally well.</p><p>We’ll explore tokenization, embeddings, and context windows in greater detail in Part 2.</p><h3>5. What Makes Transformers Special?</h3><p>Before Transformers became dominant, many language models used architectures that processed sequences differently, including recurrent neural networks.</p><p>The Transformer architecture introduced a mechanism called <strong>attention</strong>, which helps a model determine how different parts of a sequence relate to one another.</p><p>Consider this sentence:</p><blockquote><em>The developer placed the laptop in the bag because it was heavy.</em></blockquote><p>What does “it” refer to?</p><p>Understanding the sentence requires considering relationships between different words. Attention mechanisms help models weigh information from different positions when constructing representations of the input.</p><p>At a simplified level, a Transformer-based language model uses:</p><p><strong>Token embeddings:</strong> Numerical vectors representing tokens.</p><p><strong>Positional information:</strong> Information that helps represent token order.</p><p><strong>Self-attention:</strong> A mechanism that allows token representations to incorporate information from other relevant positions.</p><p><strong>Neural network layers:</strong> Repeated transformations that build increasingly useful representations.</p><p><strong>Output layer:</strong> Produces scores for possible next tokens.</p><p>A key point: attention does not mean the model thinks like a human. It is a computational mechanism for processing relationships in data.</p><p>Transformers made it practical to train large models that can learn complex patterns from extensive datasets and use those patterns across many language tasks.</p><h3>6. How Does an LLM Learn?</h3><p>The process of creating an LLM involves substantial computation and data. A simplified training pipeline looks like this:</p><pre>Training data<br>     |<br>     v<br>Tokenization<br>     |<br>     v<br>Model processes token sequences<br>     |<br>     v<br>Predict next tokens<br>     |<br>     v<br>Compare predictions with training targets<br>     |<br>     v<br>Calculate loss<br>     |<br>     v<br>Update model parameters<br>     |<br>     v<br>Repeat across many training examples</pre><p>Let’s break it down.</p><h3>Step 1: Collect and prepare training data</h3><p>Training datasets may include text, code, and other data relevant to the model’s intended capabilities.</p><p>The data must be prepared for training, with appropriate filtering and processing.</p><h3>Step 2: Predict tokens</h3><p>In a common training approach called next-token prediction, the model receives a sequence and learns to predict the next token.</p><p>For example:</p><p><strong>Input:</strong> The Earth revolves around the</p><p><strong>Target:</strong> Sun</p><p>The model’s actual prediction is a distribution over possible tokens, not simply a hard-coded answer.</p><h3>Step 3: Calculate the loss</h3><p>A loss function measures how far the model’s predictions are from the training targets.</p><p>When the model assigns a low probability to the correct target, the loss generally penalizes that prediction more heavily.</p><h3>Step 4: Update the parameters</h3><p>Training uses optimization techniques and backpropagation to adjust the model’s parameters.</p><p>These parameters are numerical values that influence how the model transforms input tokens into predictions.</p><h3>Step 5: Repeat</h3><p>This process happens across many examples and training iterations.</p><p>Over time, the model learns statistical patterns that help it predict tokens across a wide variety of contexts.</p><h3>Is training the only step?</h3><p>No.</p><p>Many conversational AI systems go through additional stages after initial pretraining. These can include supervised fine-tuning, preference-based optimization, safety training, and other techniques designed to make the model more useful for particular tasks.</p><p>The exact training pipeline varies by model.</p><h3>7. Training vs. Inference</h3><p>This is one of the most important distinctions in AI engineering.</p><p>TrainingInferenceTeaches the model through optimizationUses the trained model to produce outputsUpdates model parametersNormally keeps model parameters fixedOften requires substantial computeRuns when an application sends a requestProcesses training examplesProcesses prompts and other supplied contextHappens during model development or fine-tuningHappens when users interact with the model</p><p>Imagine you are building a customer-support assistant.</p><p>During training, a model learns patterns from its training data and may be further adapted for particular behaviors.</p><p>During inference, a user asks:</p><p>“How do I reset my password?”</p><p>The application sends the prompt to the model, which generates a response using its learned parameters and the supplied context.</p><p><strong>As an application developer, you will spend much of your time working with models during inference rather than training a foundation model from scratch.</strong></p><p>That means understanding APIs, prompts, context management, retrieval, latency, cost, evaluation, and security becomes especially important.</p><h3>8. How Does an LLM Generate a Response?</h3><p>Suppose you send this prompt:</p><p>Explain APIs in simple language.</p><p>A typical autoregressive language model generates a response token by token.</p><p>Conceptually:</p><ol><li>The model processes the input prompt.</li><li>It calculates scores for possible next tokens.</li><li>A decoding strategy selects the next token.</li><li>The selected token becomes part of the growing sequence.</li><li>The model predicts another token using the updated context.</li><li>The process continues until a stopping condition is reached.</li></ol><p>For illustration, generation might proceed like this:</p><pre>Prompt:<br>Explain APIs in simple language.</pre><pre>Illustrative generated sequence:<br>An<br>An API<br>An API is<br>An API is a<br>An API is a way<br>...</pre><p>These are illustrative intermediate stages, not the literal internal trace of a specific model.</p><h3>What determines which token is selected?</h3><p>The model produces scores that can be converted into probabilities. A decoding strategy determines how the next token is selected.</p><p>Depending on the system, this may involve:</p><ul><li><strong>Greedy decoding:</strong> Select the highest-scoring token.</li><li><strong>Sampling:</strong> Select from a probability distribution.</li><li><strong>Temperature:</strong> Adjust the distribution’s sharpness before sampling.</li><li><strong>Other decoding controls:</strong> Apply additional strategies or constraints.</li></ul><p>These choices can affect how predictable or varied a response is.</p><p>A lower temperature often makes sampled output more predictable, while a higher temperature can make it more varied. Temperature does not directly increase the model’s intelligence or guarantee creativity.</p><h3>9. Why Can LLMs Hallucinate?</h3><p>An LLM can generate a convincing answer that contains incorrect or fabricated information. This behavior is commonly called a <strong>hallucination</strong>.</p><p>Why does it happen?</p><p>A language model is optimized to produce outputs according to its training and objective. Unless the application includes suitable mechanisms for grounding and verification, the model may generate a plausible continuation even when the underlying facts are uncertain or missing.</p><p>For example, you might ask:</p><p>“Which research paper introduced a fictional algorithm called QuantumTree-9000 in 2018?”</p><p>A model may produce an invented paper title, authors, or publication details rather than clearly admitting that it cannot verify the premise.</p><p>Hallucinations can arise for multiple reasons, including:</p><ul><li>Missing or unreliable information</li><li>Ambiguous questions</li><li>Incorrect assumptions in the prompt</li><li>Limitations in the model’s learned knowledge</li><li>Errors in reasoning or generation</li></ul><h3>How do developers reduce hallucinations?</h3><p>There is no single solution, but useful techniques include:</p><ul><li>Providing trusted source material.</li><li>Using Retrieval-Augmented Generation (RAG).</li><li>Asking for structured outputs with explicit constraints.</li><li>Requiring citations to supplied sources where appropriate.</li><li>Validating outputs against business rules or external systems.</li><li>Evaluating the application on representative test cases.</li><li>Designing the system to admit uncertainty when evidence is insufficient.</li></ul><p>RAG, in particular, is an important technique for applications that need to answer questions using private documents or up-to-date information. We’ll build toward it later in this series.</p><h3>10. An LLM Is Not the Same as a GenAI Application</h3><p>This distinction is crucial for software engineers.</p><p>A model is only one component of a production AI system.</p><p>Consider a document-question-answering application:</p><pre>User<br> |<br> v<br>Application API<br> |<br> v<br>Document retrieval<br> |<br> v<br>Prompt construction<br> |<br> v<br>LLM<br> |<br> v<br>Output validation<br> |<br> v<br>Response to user</pre><p>A production application may also need authentication, authorization, logging, retries, rate limiting, monitoring, evaluation, and cost controls.</p><p>The model generates the response, but the surrounding application determines which information it receives, which actions it can take, and how its output is handled.</p><p>This is where <strong>GenAI engineering</strong> becomes more than simply writing prompts.</p><p>For example, a useful AI assistant may need to:</p><ul><li>Retrieve relevant documents before answering.</li><li>Call an API to obtain current information.</li><li>Return data in a defined JSON schema.</li><li>Reject unauthorized requests.</li><li>Track failures and measure response quality.</li><li>Prevent sensitive information from being exposed.</li></ul><p>The engineering challenge is building a system that behaves reliably — not merely getting a model to produce an impressive response once.</p><h3>11. Can You Build an LLM Application Without Training a Model?</h3><p>Absolutely.</p><p>Most developers start by using an existing model through an API or running a suitable open-weight model locally.</p><p>A basic application often follows this pattern:</p><pre>def answer_question(question: str, model_client) -&gt; str:<br>    response = model_client.generate(<br>        prompt=question<br>    )<br>    return response.text</pre><p>This is illustrative pseudocode. The model_client and generate() method are placeholders; actual SDKs use provider-specific interfaces.</p><p>The underlying workflow is simple:</p><ol><li>Accept a user question.</li><li>Send the question to a model.</li><li>Receive the generated output.</li><li>Return the result to the user.</li></ol><p>Real applications need additional error handling, timeouts, security controls, and evaluation. But the core idea is accessible without training a model from scratch.</p><p>As the series progresses, we’ll add practical capabilities to this basic pattern, including structured outputs, conversation state, retrieval, tool use, evaluation, and deployment.</p><h3>12. Key Takeaways</h3><p>Let’s recap the concepts covered in this article.</p><ul><li><strong>Generative AI</strong> creates new content using patterns learned from data.</li><li><strong>LLMs</strong> are models that process language and generate text, commonly using Transformer architectures.</li><li><strong>Tokens</strong> are the units through which text is represented for model processing.</li><li><strong>Attention</strong> helps Transformer models process relationships between different parts of a sequence.</li><li><strong>Training</strong> adjusts model parameters; <strong>inference</strong> uses the trained model to produce outputs.</li><li><strong>Next-token prediction</strong> is central to how many text-generating LLMs operate.</li><li><strong>Hallucinations</strong> are a real limitation and require appropriate grounding, validation, and evaluation.</li><li><strong>GenAI engineering</strong> involves designing the entire application around the model, not just calling an API.</li></ul><p>You don’t need to understand every mathematical detail of a Transformer before building useful AI applications. You do need a solid mental model of what the model does, what it cannot guarantee, and how software engineering can make it more reliable.</p><h3>What’s Next?</h3><p>In Part 2, we’ll explore foundational concepts that every GenAI engineer should understand:</p><p><strong>Tokens, Context Windows, Embeddings, and Transformers</strong></p><p>We’ll look at how text becomes numerical representations, why context-window limits matter, and how embeddings enable semantic search and retrieval.</p><p>The objective is to move from understanding how LLMs work to understanding the building blocks used to create real AI applications.</p><p><em>If you’re learning Generative AI as a software engineer, follow this series as we move from fundamentals to practical, production-oriented AI systems.</em></p><p>#GenerativeAI #LLM #ArtificialIntelligence #Python #AIEngineering #MachineLearning</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cea170b6a5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build an End-to-End Dataform Project: From Raw Data to Production in BigQuery]]></title>
            <link>https://medium.com/@abhint2603/build-an-end-to-end-dataform-project-from-raw-data-to-production-in-bigquery-03ca2e53d02e?source=rss-fd6e8dab532------2</link>
            <guid isPermaLink="false">https://medium.com/p/03ca2e53d02e</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[dataform]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[analytics-engineering]]></category>
            <dc:creator><![CDATA[Abhishek Nath Tiwari]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 21:25:34 GMT</pubDate>
            <atom:updated>2026-10-09T21:25:34.692Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the last 14 articles, we’ve explored different parts of Dataform.</p><p>We’ve learned how to write SQLX models, manage dependencies, build incremental tables, test data quality, optimize BigQuery queries, and prepare transformations for production.</p><p>But how do all these pieces fit together in a real project?</p><p>That’s what we’ll build in this final article.</p><p>We’ll design a practical e-commerce data pipeline that transforms raw order data into reliable business reporting tables using <strong>Google Cloud, BigQuery, and Dataform</strong>.</p><p>By the end, you’ll understand how the individual concepts from this series fit into one complete workflow.</p><h3>1. The Project: E-Commerce Analytics</h3><p>Imagine an e-commerce company that receives thousands of orders every day.</p><p>Its business team wants to answer questions such as:</p><ul><li>How much revenue did we generate yesterday?</li><li>How many orders were completed?</li><li>Which customers generate the most revenue?</li><li>Are there duplicate or invalid orders?</li><li>Can the dashboard be updated automatically every morning?</li></ul><p>The source data is stored in BigQuery.</p><p>Our responsibility is to transform that raw data into reliable analytics tables.</p><h3>Our architecture</h3><pre>        Source Application<br>                |<br>                v<br>        BigQuery Raw Tables<br>                |<br>                v<br>             Dataform<br>                |<br>        +-------+--------+<br>        |                |<br>        v                v<br>    Staging Models   Assertions<br>        |<br>        v<br>  Intermediate Models<br>        |<br>        v<br>     Analytics Marts<br>        |<br>        v<br>   Business Dashboard</pre><p>Around this pipeline, we also need Git-based development, workflow scheduling, monitoring, and a controlled production deployment process.</p><p>One important distinction: Dataform manages SQL transformations and their dependencies. Source ingestion and dashboard refreshes may require separate services or orchestration, depending on your architecture.</p><h3>2. Step One: Define the Raw Data</h3><p>Let’s assume our source table is:</p><pre>my_project.raw_orders.orders</pre><p>It contains the following columns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*LPUgwdgKfyV3k4kwWTAMMw.png" /></figure><p>Example records:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*QY0-2-NlUK7zvXp1pET_9A.png" /></figure><p>For this tutorial, we’ll assume the raw table is already populated and order_id uniquely identifies an order.</p><p>In a real project, confirm the source’s grain, data types, update behavior, and handling of late-arriving records before designing the transformations.</p><h3>3. Step Two: Create a Staging Model</h3><p>The staging layer prepares source data for downstream transformations.</p><p>Typical responsibilities include:</p><ul><li>Selecting required columns</li><li>Standardizing values</li><li>Converting data types</li><li>Applying basic cleanup</li><li>Establishing consistent column names</li></ul><p>Create:</p><pre>definitions/staging/stg_orders.sqlx</pre><p>Add the following code:</p><pre>config {<br>  type: &quot;view&quot;,<br>  description: &quot;Standardized order records from the raw source&quot;<br>}</pre><pre>SELECT<br>  order_id,<br>  customer_id,<br>  CAST(order_date AS DATE) AS order_date,<br>  CAST(amount AS NUMERIC) AS amount,<br>  LOWER(TRIM(status)) AS status,<br>  updated_at<br>FROM `my_project.raw_orders.orders`</pre><p>Replace my_project.raw_orders.orders with your actual project, dataset, and table.</p><p>Why use a view here?</p><p>A view can provide a lightweight logical transformation without storing another complete copy of the source data. Whether a view or a physical table is best depends on source size, query patterns, and reuse.</p><p>Notice that the source is a fully qualified BigQuery table. Dataform’s ref() is appropriate when referencing another Dataform-managed action; external source tables can be referenced directly or declared as Dataform declarations.</p><p>Our first layer is now ready:</p><pre>Raw Orders<br>    |<br>    v<br>stg_orders</pre><h3>4. Step Three: Build an Incremental Model</h3><p>Now imagine our raw table grows to hundreds of millions of records.</p><p>Rebuilding a complete historical table on every run may be expensive.</p><p>We can use an incremental Dataform model to maintain the completed-orders dataset.</p><p>Create:</p><pre>definitions/intermediate/completed_orders.sqlx</pre><p>Use:</p><pre>config {<br>  type: &quot;incremental&quot;,<br>  uniqueKey: [&quot;order_id&quot;],<br>  description: &quot;Completed orders maintained incrementally&quot;<br>}</pre><pre>SELECT<br>  order_id,<br>  customer_id,<br>  order_date,<br>  amount,<br>  updated_at<br>FROM ${ref(&quot;stg_orders&quot;)}<br>WHERE status = &quot;completed&quot;</pre><pre>${when(incremental(), `<br>  AND updated_at &gt;= (<br>    SELECT COALESCE(<br>      TIMESTAMP_SUB(MAX(updated_at), INTERVAL 2 DAY),<br>      TIMESTAMP(&quot;2000-01-01&quot;)<br>    )<br>    FROM ${self()}<br>  )<br>`)}</pre><p>Let’s understand the important pieces.</p><p><strong>type: &quot;incremental&quot;</strong></p><p>Dataform maintains the target table incrementally rather than rebuilding it on every normal run.</p><p><strong>uniqueKey: [&quot;order_id&quot;]</strong></p><p>This tells Dataform that order_id identifies a record for incremental updates. The key must genuinely be unique in the intended output.</p><p><strong>when(incremental(), ...)</strong></p><p>This condition applies the additional filter during incremental runs, while the initial build processes the source dataset.</p><p><strong>${self()}</strong></p><p>This references the current model’s target table.</p><h3>Why look back two days?</h3><p>Suppose an order from yesterday was initially pending but becomes completed today.</p><p>A filter that only processes newly created orders could miss that update.</p><p>Looking back over a recent window helps capture some late-arriving changes.</p><p>However, this example assumes updated_at is reliable and that the target table&#39;s incremental strategy correctly handles updates. For a production pipeline, use an appropriate merge strategy, test late-arriving records, and design a full-refresh or reconciliation process for changes outside the lookback window.</p><p>Also note that this model filters out non-completed orders. If an order was previously completed and later becomes cancelled, simply filtering it out doesn’t necessarily remove the old record from the target. That business case requires an explicit deletion or status-change strategy.</p><p>This is why incremental processing must be designed around the source’s actual update behavior.</p><h3>5. Step Four: Create a Daily Sales Mart</h3><p>The business team doesn’t necessarily need every individual order.</p><p>It may need an aggregated table showing daily sales.</p><p>Create:</p><pre>definitions/marts/daily_sales.sqlx</pre><p>Add:</p><pre>config {<br>  type: &quot;table&quot;,<br>  description: &quot;Daily order counts and revenue from completed orders&quot;<br>}</pre><pre>SELECT<br>  order_date,<br>  COUNT(*) AS total_orders,<br>  SUM(amount) AS total_revenue,<br>  CURRENT_TIMESTAMP() AS calculated_at<br>FROM ${ref(&quot;completed_orders&quot;)}<br>GROUP BY order_date</pre><p>The resulting table might look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*e7rQz_IbbcAQvB4uTE65GQ.png" /></figure><p>These numbers are illustrative.</p><p>We now have a clear transformation path:</p><pre>raw_orders<br>     |<br>     v<br>stg_orders<br>     |<br>     v<br>completed_orders<br>     |<br>     v<br>daily_sales</pre><p>Dataform understands these dependencies through ref().</p><p><strong>Production consideration:</strong> This example rebuilds the daily aggregate table from the completed-orders model. For very large datasets, consider partitioning the output and using an incremental aggregation strategy that correctly recalculates affected dates. Incrementalizing an aggregate requires care when historical orders can change.</p><h3>6. Step Five: Add Data Quality Assertions</h3><p>A pipeline that produces a table is not necessarily a pipeline that produces trustworthy data.</p><p>Let’s add assertions.</p><h3>Test A: Detect duplicate order IDs</h3><p>Create:</p><pre>definitions/assertions/assert_orders_unique.sqlx</pre><pre>config {<br>  type: &quot;assertion&quot;<br>}</pre><pre>SELECT<br>  order_id<br>FROM ${ref(&quot;completed_orders&quot;)}<br>GROUP BY order_id<br>HAVING COUNT(*) &gt; 1</pre><p>If an order ID appears more than once, the assertion fails.</p><h3>Test B: Detect invalid amounts</h3><p>Create:</p><pre>definitions/assertions/assert_orders_valid.sqlx</pre><pre>config {<br>  type: &quot;assertion&quot;<br>}</pre><pre>SELECT<br>  order_id,<br>  amount<br>FROM ${ref(&quot;completed_orders&quot;)}<br>WHERE order_id IS NULL<br>   OR amount IS NULL<br>   OR amount &lt; 0</pre><p>This catches missing identifiers, missing amounts, and negative amounts.</p><p>These checks assume those conditions are invalid under the business rules.</p><p>Dataform also supports built-in assertions such as nonNull and uniqueKey configuration for applicable models, so you can choose between built-in checks and custom SQL assertions.</p><p>Our pipeline now includes data quality validation:</p><pre>completed_orders<br>       |<br>       +----&gt; Duplicate assertion<br>       |<br>       +----&gt; Amount assertion<br>       |<br>       v<br>   daily_sales</pre><p>Assertions should be connected to the models they validate and included in the intended workflow execution. A failed assertion must also have a defined operational response.</p><h3>7. Step Six: Organize Models With Tags</h3><p>As the project grows, tags make it easier to classify related actions.</p><p>For example, you might add tags to the staging model:</p><pre>config {<br>  type: &quot;view&quot;,<br>  tags: [&quot;orders&quot;, &quot;daily&quot;]<br>}</pre><p>And to the daily sales model:</p><pre>config {<br>  type: &quot;table&quot;,<br>  tags: [&quot;sales&quot;, &quot;daily&quot;, &quot;critical&quot;]<br>}</pre><p>You could establish a small tagging convention:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*7sGGvKnXQ_n-xvkFoE2NtA.png" /></figure><p>Tags classify models, but <strong>they do not replace dependencies</strong>.</p><p>When selecting actions by tag, understand Dataform’s compilation and dependency-selection behavior. A selected downstream model may require upstream actions that aren’t in the same tag group.</p><p>For production use, test the exact selection behavior before relying on it for scheduling.</p><h3>8. Step Seven: Understand the DAG</h3><p>Our Dataform dependency graph now looks like this:</p><pre>       Raw Orders<br>            |<br>            v<br>        stg_orders<br>            |<br>            v<br>     completed_orders<br>        /         \<br>       v           v<br>Duplicate Test   Amount Test<br>            |<br>            v<br>        daily_sales</pre><p>The diagram is conceptual; assertions and models should be connected according to their actual declared dependencies.</p><p>A DAG, or Directed Acyclic Graph, describes relationships between actions.</p><p>Dataform uses those relationships to determine valid execution order.</p><p>For example:</p><ul><li>completed_orders depends on stg_orders.</li><li>daily_sales depends on completed_orders.</li><li>Assertions can validate completed_orders.</li></ul><p>If the staging model fails, dependent downstream actions cannot successfully complete using that run’s required output.</p><p>Independent branches may be able to execute without waiting for unrelated branches.</p><p>This is why correct dependencies are so important.</p><h3>9. Step Eight: Use Git for Development</h3><p>Treat your Dataform project like a software codebase.</p><p>A simple workflow looks like this:</p><pre>Developer<br>    |<br>    v<br>Feature Branch<br>    |<br>    v<br>Modify SQLX Models<br>    |<br>    v<br>Compile and Test<br>    |<br>    v<br>Pull Request<br>    |<br>    v<br>Code Review<br>    |<br>    v<br>Merge<br>    |<br>    v<br>Production Release</pre><p>For example, you might create a branch named:</p><pre>feature/daily-sales-model</pre><p>Then make your changes, validate the compiled SQL, test the relevant actions, and request review.</p><p>Avoid treating production as a place to experiment directly.</p><p>Git gives you version history and collaboration, but deployment and rollback procedures still need to be configured.</p><h3>10. Step Nine: Schedule the Workflow</h3><p>Once the models are ready, the next question is:</p><p><strong>When should they run?</strong></p><p>Suppose the business requires daily sales reporting by 7 AM.</p><p>A conceptual schedule could be:</p><pre>01:00 AM<br>Source ingestion completes<br>       |<br>       v<br>02:00 AM<br>Data availability validation<br>       |<br>       v<br>02:30 AM<br>Dataform workflow starts<br>       |<br>       v<br>Transformations and assertions<br>       |<br>       v<br>04:30 AM<br>Validate results<br>       |<br>       v<br>05:00 AM<br>Reporting tables ready<br>       |<br>       v<br>07:00 AM<br>Business reporting deadline</pre><p>These times are illustrative, not recommended defaults.</p><p>In Google Cloud Dataform, you can use workflow configurations and workflow invocations to execute selected actions on a schedule. Cloud Scheduler and other orchestration services can also trigger workflows through the appropriate API or service integration.</p><p>The correct setup depends on the deployment architecture.</p><p>A schedule should account for source data availability, expected runtime, retries, and the business reporting deadline.</p><h3>11. Step Ten: Monitor Failures and Recover Safely</h3><p>Production pipelines will eventually encounter failures.</p><p>Possible causes include:</p><ul><li>Missing source data</li><li>Permission errors</li><li>SQL compilation errors</li><li>BigQuery job failures</li><li>Assertion failures</li><li>Incorrect incremental logic</li></ul><p>A basic operational flow looks like this:</p><pre>Scheduled Workflow<br>        |<br>        v<br>Dataform Invocation<br>        |<br>        v<br>Check Invocation Status<br>        |<br>   +----+----+<br>   |         |<br>   v         v<br> Success   Failure<br>   |         |<br>   v         v<br>Publish    Investigate<br>Results       |<br>              v<br>          Correct Cause<br>              |<br>              v<br>         Retry Safely</pre><p>For monitoring, capture information such as:</p><ul><li>Workflow invocation status</li><li>Failed action names</li><li>Execution duration</li><li>Assertion results</li><li>BigQuery job details</li><li>Data volume and freshness</li></ul><p>Don’t blindly retry every failure.</p><p>A permission error needs a different response from an assertion failure. A retry should also be safe for the model’s incremental behavior.</p><h3>12. Optimize the Pipeline for BigQuery</h3><p>As the dataset grows, optimization becomes increasingly important.</p><p>For this project, I would evaluate the following:</p><p><strong>Partitioning:</strong> Consider partitioning large tables by a suitable date column.</p><p><strong>Clustering:</strong> Consider clustering when the query patterns and data distribution justify it.</p><p><strong>Incremental processing:</strong> Process only the required changes while accounting for updates and late-arriving records.</p><p><strong>Column selection:</strong> Avoid carrying unnecessary columns through transformations.</p><p><strong>Query analysis:</strong> Use BigQuery execution details and query history to identify expensive scans, joins, and aggregations.</p><p><strong>Cost monitoring:</strong> Track bytes processed and workload behavior over time.</p><p>One key point: incremental processing does not automatically mean a query is cheap. An incremental model can still scan a large portion of the source if its filters don’t enable effective pruning.</p><p>Measure performance before and after changes rather than assuming an optimization helped.</p><h3>13. The Complete Project Architecture</h3><p>Let’s bring everything together.</p><pre>                SOURCE SYSTEM<br>                       |<br>                       v<br>                 BIGQUERY RAW<br>                       |<br>                       v<br>                +--------------+<br>                |  DATAFORM    |<br>                |              |<br>                |  Staging     |<br>                |  Incremental |<br>                |  Models      |<br>                |  Assertions  |<br>                |  Tags        |<br>                +------+-------+<br>                       |<br>                       v<br>                 ANALYTICS MARTS<br>                       |<br>                       v<br>                  DASHBOARDS</pre><p>The operational layer surrounds the transformation flow:</p><pre>              Git and Code Review<br>                      |<br>                      v<br>               Production Release<br>                      |<br>                      v<br>               Workflow Schedule<br>                      |<br>                      v<br>               Dataform Execution<br>                      |<br>                      v<br>              Monitoring and Alerts</pre><p>The complete system has multiple responsibilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*J9rBow1ZgB8Sa1mU9h1clw.png" /></figure><p>Together, these components form a maintainable analytics pipeline.</p><h3>14. Production Readiness Checklist</h3><p>Before calling this project production-ready, I would review the following:</p><ul><li>Source tables and schemas are documented.</li><li>Models follow a consistent naming convention.</li><li>Dependencies are declared correctly.</li><li>Incremental logic handles updates and late-arriving data.</li><li>Data quality assertions cover critical business rules.</li><li>Large tables use appropriate partitioning and clustering.</li><li>BigQuery costs and query performance are monitored.</li><li>Git reviews are part of the development process.</li><li>Development and production environments are separated.</li><li>Workflow schedules respect source availability and business SLAs.</li><li>Failures generate actionable alerts.</li><li>Retry and recovery procedures are documented.</li><li>Access permissions follow least-privilege principles.</li><li>Historical rebuilds and backfills have a defined procedure.</li></ul><p>You don’t need every advanced feature on the first day.</p><p>Start with a small, understandable pipeline and introduce complexity only when the business requires it.</p><h3>15. What We Learned From This Series</h3><p>Across these 15 articles, we’ve moved from basic concepts to a complete production-oriented design.</p><p>Here’s the journey:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*_20_O8dK-RBVDOgAqD5P6A.png" /></figure><p>The individual concepts are useful on their own, but their real value comes from understanding how they work together.</p><h3>Final Thoughts</h3><p>When I started exploring Dataform, it was easy to think of it as a tool for organizing SQL files.</p><p>But a production Dataform project is much more than that.</p><p>It brings together transformation logic, dependencies, testing, incremental processing, version control, scheduling, and operational monitoring.</p><p>The objective isn’t simply to make a SQL query run.</p><p>It’s to build a pipeline that produces trustworthy data, can be maintained by other engineers, and behaves predictably as the business grows.</p><p>If there’s one lesson I would take from this entire series, it’s this:</p><p><strong>Good data engineering is not just about transforming data. It’s about making that transformation reliable, repeatable, and trustworthy.</strong></p><p>That is the difference between a collection of SQL queries and a production data pipeline.</p><h3>The End of the Dataform Series — What’s Next?</h3><p>This concludes our 15-part Dataform series, from beginner concepts to production architecture.</p><p>If you’ve followed the series, you now have a foundation for understanding how Dataform fits into a modern analytics engineering workflow on Google Cloud.</p><p>The next step is to apply these concepts to a real project, experiment with different data volumes, and learn from the failures and performance bottlenecks you encounter.</p><p>I’ll continue exploring more topics in data engineering, BigQuery, and Google Cloud.</p><p>Thanks for following this series.</p><p>#Dataform #BigQuery #DataEngineering #GoogleCloud #GCP #SQL #ETL #ELT #AnalyticsEngineering #CloudComputing</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03ca2e53d02e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dataform Data Quality Testing: 7 Checks Every Data Engineer Should Know]]></title>
            <link>https://medium.com/@abhint2603/dataform-data-quality-testing-7-checks-every-data-engineer-should-know-39d449bb1605?source=rss-fd6e8dab532------2</link>
            <guid isPermaLink="false">https://medium.com/p/39d449bb1605</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[data-engineering-101]]></category>
            <dc:creator><![CDATA[Abhishek Nath Tiwari]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 21:12:51 GMT</pubDate>
            <atom:updated>2026-10-09T21:12:51.750Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine your Dataform pipeline runs successfully.</p><p>No SQL errors. No failed jobs. Everything looks green.</p><p>But when the business team opens its dashboard, sales have suddenly dropped by 70%.</p><p>What happened?</p><p>Maybe the source data was incomplete. Maybe duplicate orders entered the system. Maybe a transformation introduced incorrect values.</p><p><strong>Your SQL can execute successfully while your data is still wrong.</strong></p><p>This is why data quality testing is one of the most important responsibilities of a data engineer.</p><p>In this article, we’ll explore seven practical data quality checks using Dataform and BigQuery.</p><p>We’ll use an e-commerce example throughout the article.</p><h3>1. Why Data Quality Testing Matters</h3><p>Suppose your pipeline looks like this:</p><pre>Source Data<br>    ↓<br>BigQuery<br>    ↓<br>Dataform Transformations<br>    ↓<br>Analytics Tables<br>    ↓<br>Business Dashboard</pre><p>If incorrect data enters the pipeline, it can travel through every downstream model.</p><p>For example:</p><pre>Duplicate Orders<br>      ↓<br>Incorrect Order Count<br>      ↓<br>Inflated Revenue<br>      ↓<br>Misleading Dashboard<br>      ↓<br>Wrong Business Decisions</pre><p>The problem isn’t necessarily the dashboard or even the SQL transformation.</p><p>The problem may be the absence of proper data quality checks.</p><p>A reliable pipeline should validate not only whether a transformation ran, but also whether its output meets the expected rules.</p><h3>2. How Dataform Assertions Work</h3><p>Dataform provides a feature called <strong>assertions</strong>.</p><p>An assertion checks whether data satisfies a condition.</p><p>For a manual assertion, the idea is simple:</p><ul><li>Write a SQL query that returns invalid rows.</li><li>If the query returns no rows, the check passes.</li><li>If the query returns one or more rows, the check fails.</li></ul><p>For example, suppose completed orders should never have a negative amount.</p><pre>config {<br>  type: &quot;assertion&quot;<br>}</pre><pre>SELECT<br>  order_id,<br>  amount<br>FROM ${ref(&quot;completed_orders&quot;)}<br>WHERE amount &lt; 0</pre><p>If the query returns invalid orders, the assertion fails.</p><p>If no invalid rows are found, it passes.</p><p>Think of an assertion as a test for your data.</p><pre>Data<br>  ↓<br>Assertion<br>  ↓<br>┌──────────────┐<br>│ Valid rows?  │<br>└──────┬───────┘<br>       │<br>   ┌───┴────┐<br>   ↓        ↓<br>  Pass     Fail</pre><p>Assertions don’t automatically repair bad data. They help detect problems so that your team can investigate and respond.</p><h3>3. Check #1 — Detect NULL Values</h3><p>Let’s start with one of the most common data quality problems.</p><p>Imagine your orders table contains:</p><p>order_idcustomer_idamount1015011200102NULL800103503450</p><p>Order 102 has no customer ID.</p><p>If every order is expected to have a customer, this record violates the business rule.</p><p>Create an assertion:</p><pre>config {<br>  type: &quot;assertion&quot;<br>}</pre><pre>SELECT<br>  order_id,<br>  customer_id<br>FROM ${ref(&quot;completed_orders&quot;)}<br>WHERE customer_id IS NULL</pre><p>This identifies orders with missing customer IDs.</p><p>You can apply the same principle to:</p><ul><li>Order IDs</li><li>Transaction IDs</li><li>Required dates</li><li>Product IDs</li><li>Other mandatory fields</li></ul><p><strong>Important:</strong> Not every NULL value is an error. Some fields are legitimately optional. Your checks should reflect the actual business rules.</p><h3>4. Check #2 — Detect Duplicate Records</h3><p>Duplicate records can cause serious reporting problems.</p><p>Suppose your table contains:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*4PbHctv2jBAgRQG6nW4wVA.png" /></figure><p>If each order_id is supposed to represent exactly one order, the duplicate can inflate order counts and revenue.</p><p>Use this assertion:</p><pre>config {<br>  type: &quot;assertion&quot;<br>}</pre><pre>SELECT<br>  order_id<br>FROM ${ref(&quot;completed_orders&quot;)}<br>GROUP BY order_id<br>HAVING COUNT(*) &gt; 1</pre><p>The query groups records by order_id and returns IDs that appear more than once.</p><p>For example:</p><pre>order_id = 102<br>count = 2</pre><p>The assertion fails because the expected uniqueness rule has been violated.</p><h3>A practical distinction</h3><p>Duplicates aren’t always wrong.</p><p>An order-line table might contain multiple records for one order because an order can contain multiple products.</p><p>Before writing a uniqueness assertion, understand what one row represents.</p><p>Is it one order, one order line, one payment, or one event?</p><p>Your test should match the table’s intended grain.</p><h3>5. Check #3 — Validate Numeric Values</h3><p>Business metrics often have rules about acceptable values.</p><p>For example:</p><ul><li>Order amounts shouldn’t be negative.</li><li>Product quantities should be positive.</li><li>Discount percentages should fall within an allowed range.</li></ul><p>For completed orders, we might expect non-negative amounts.</p><pre>config {<br>  type: &quot;assertion&quot;<br>}</pre><pre>SELECT<br>  order_id,<br>  amount<br>FROM ${ref(&quot;completed_orders&quot;)}<br>WHERE amount &lt; 0</pre><p>If zero-value orders are also invalid for your business, you could use:</p><pre>WHERE amount &lt;= 0</pre><p>But choose carefully.</p><p>A free promotional order or a fully discounted order might legitimately have a zero amount.</p><p>The correct condition depends on the business rule, not simply on what looks unusual.</p><h3>6. Check #4 — Validate Relationships Between Tables</h3><p>Now let’s look at referential integrity.</p><p>Suppose you have two tables:</p><pre>customers<br>   └── customer_id</pre><pre>completed_orders<br>   └── customer_id</pre><p>Every non-NULL customer ID in completed_orders is expected to exist in customers.</p><p>What happens if an order references a customer who doesn’t exist?</p><p>Your reporting might contain orphaned records.</p><p>You can detect them using a left join:</p><pre>config {<br>  type: &quot;assertion&quot;<br>}</pre><pre>SELECT<br>  o.order_id,<br>  o.customer_id<br>FROM ${ref(&quot;completed_orders&quot;)} AS o<br>LEFT JOIN ${ref(&quot;stg_customers&quot;)} AS c<br>  ON o.customer_id = c.customer_id<br>WHERE o.customer_id IS NOT NULL<br>  AND c.customer_id IS NULL</pre><p>This returns orders whose customer IDs cannot be found in the customer table.</p><p>However, be careful with legitimate scenarios such as late-arriving customer records or historical data.</p><p>Sometimes the right response is to quarantine the record temporarily rather than permanently reject it.</p><p><strong>The goal is to detect unexpected relationships, not blindly reject every unusual record.</strong></p><h3>7. Check #5 — Validate Dates and Business Rules</h3><p>Suppose your business rule says that an order cannot have an order date in the future.</p><p>You can create an assertion:</p><pre>config {<br>  type: &quot;assertion&quot;<br>}</pre><pre>SELECT<br>  order_id,<br>  order_date<br>FROM ${ref(&quot;completed_orders&quot;)}<br>WHERE order_date &gt; CURRENT_DATE()</pre><p>This identifies future-dated orders.</p><p>You might also validate:</p><ul><li>Shipment date isn’t before order date.</li><li>Cancellation date isn’t before order creation.</li><li>Account opening date isn’t after account closure.</li><li>Transaction dates fall within an expected period.</li></ul><p>For example, if your model contains both order and shipment dates:</p><pre>config {<br>  type: &quot;assertion&quot;<br>}</pre><pre>SELECT<br>  order_id,<br>  order_date,<br>  shipment_date<br>FROM ${ref(&quot;orders_with_shipments&quot;)}<br>WHERE shipment_date &lt; order_date</pre><p>This catches records that violate the date relationship.</p><p>Remember that some systems use different time zones or allow backdated records. Define your business rules accordingly.</p><h3>8. Check #6 — Detect Unexpected Changes in Data Volume</h3><p>This is a particularly useful check in production.</p><p>Imagine your daily sales table usually contains data for approximately 10,000 orders.</p><p>Today, it contains only 12.</p><p>The transformation might have completed successfully, but the result could indicate:</p><ul><li>Incomplete source ingestion</li><li>A broken filter</li><li>A source schema change</li><li>An upstream processing failure</li></ul><p>You can write an assertion that checks whether the table is unexpectedly empty:</p><pre>config {<br>  type: &quot;assertion&quot;<br>}</pre><pre>SELECT<br>  COUNT(*) AS row_count<br>FROM ${ref(&quot;completed_orders&quot;)}<br>HAVING COUNT(*) = 0</pre><p>If the table is empty, the assertion fails.</p><p>But this only catches a completely empty table.</p><p>To detect more subtle drops, you need a baseline or a historical comparison.</p><p>For example, a production monitoring system could compare today’s row count with the previous day’s count and flag a large deviation.</p><p>A simple conceptual rule might be:</p><pre>Today&#39;s rows = 500<br>Yesterday&#39;s rows = 10,000</pre><pre>Change = -95%</pre><pre>Action = Investigate</pre><p>The exact threshold should depend on the business. A 95% drop might be suspicious for daily orders but completely normal for a seasonal product.</p><p>For reliable historical checks, store row-count metrics over time or use a dedicated monitoring process.</p><h3>9. Check #7 — Validate Business Metrics</h3><p>Technical checks aren’t enough.</p><p>Your data might have:</p><ul><li>No NULL order IDs</li><li>No duplicate orders</li><li>No negative amounts</li><li>Valid customer references</li></ul><p>And still produce incorrect business metrics.</p><p>Consider revenue.</p><p>Suppose your business defines completed-order revenue as the sum of amounts for orders with status completed.</p><p>You could calculate the metric independently:</p><pre>SELECT<br>  SUM(amount) AS expected_revenue<br>FROM ${ref(&quot;stg_orders&quot;)}<br>WHERE status = &quot;completed&quot;</pre><p>Then compare it with the value produced by your reporting model.</p><p>Conceptually:</p><pre>Source Data<br>    ↓<br>Expected Revenue<br>    │<br>    ├───────────────┐<br>    │               │<br>    ▼               ▼<br>Independent      Reporting<br>Calculation      Model<br>    │               │<br>    └───────┬───────┘<br>            ▼<br>       Compare Values<br>            ↓<br>       Pass or Fail</pre><p>For example:</p><pre>Expected revenue = ₹5,00,000<br>Reported revenue = ₹4,20,000</pre><pre>Difference = ₹80,000</pre><p>That discrepancy deserves investigation.</p><p>A robust implementation would compare the two calculations in an assertion, using appropriate tolerance rules if rounding is involved.</p><p>The key is to validate important business outcomes, not just individual columns.</p><h3>10. Combine Assertions With a Testing Strategy</h3><p>You now have seven types of checks:</p><p>CheckWhat it catchesNULL validationMissing required valuesUniquenessDuplicate recordsNumeric validationInvalid amounts or quantitiesReferential integrityMissing related recordsDate validationImpossible or unexpected datesVolume checksMissing or abnormal data loadsBusiness metric checksIncorrect business results</p><p>For our e-commerce pipeline, the architecture might look like this:</p><pre>raw_orders<br>    ↓<br>stg_orders<br>    ↓<br>completed_orders<br>    │<br>    ├── NULL checks<br>    ├── Duplicate checks<br>    ├── Amount checks<br>    ├── Customer relationship checks<br>    ├── Date checks<br>    └── Business metric checks<br>    │<br>    ▼<br>daily_sales<br>    │<br>    ▼<br>Dashboard</pre><p>The exact placement of each assertion depends on what you’re validating. For example, checks on raw data may identify ingestion issues, while checks on a final mart may validate business-level expectations.</p><h3>11. Don’t Confuse Successful Execution With Correct Data</h3><p>This is one of the most important lessons in data engineering.</p><p>A query can execute successfully even when its result is wrong.</p><p>For example:</p><pre>SELECT<br>  status,<br>  SUM(amount) AS total_sales<br>FROM ${ref(&quot;stg_orders&quot;)}<br>GROUP BY status</pre><p>This query might execute without any errors.</p><p>But what if the source system unexpectedly starts sending:</p><pre>COMPLETED<br>completed<br>Completed</pre><p>as different status values?</p><p>Your output could contain separate groups instead of one consistent category.</p><p>One way to prevent this is to normalize values during staging:</p><pre>SELECT<br>  order_id,<br>  LOWER(TRIM(status)) AS status,<br>  amount<br>FROM ${ref(&quot;raw_orders&quot;)}</pre><p>Then test that the normalized values belong to the allowed set.</p><p>For example:</p><pre>config {<br>  type: &quot;assertion&quot;<br>}</pre><pre>SELECT<br>  order_id,<br>  status<br>FROM ${ref(&quot;stg_orders&quot;)}<br>WHERE status NOT IN (<br>  &quot;completed&quot;,<br>  &quot;pending&quot;,<br>  &quot;cancelled&quot;<br>)<br>OR status IS NULL</pre><p>This helps catch unexpected values before they affect downstream reporting.</p><h3>12. What Should Happen When an Assertion Fails?</h3><p>Finding a problem is only the first step.</p><p>A production system needs a response strategy.</p><p>For example:</p><pre>Dataform Run<br>     ↓<br>Assertion Fails<br>     ↓<br>Investigate Failure<br>     ↓<br>Identify Root Cause<br>     ↓<br>Correct Source or Logic<br>     ↓<br>Re-run Required Actions<br>     ↓<br>Validate Results</pre><p>Depending on your architecture, you might also:</p><ul><li>Send an alert to the data engineering team.</li><li>Prevent downstream publication.</li><li>Quarantine invalid records.</li><li>Retry after a temporary upstream issue.</li><li>Record the failure for auditing.</li></ul><p>Not every failed assertion requires the same response.</p><p>A duplicate primary key in a financial transaction table may require blocking publication. A small number of late-arriving customer records may be handled through a controlled exception process.</p><p>Design the response around the severity of the issue.</p><h3>13. Best Practices for Dataform Assertions</h3><p>Here are the practices I would follow in a real project.</p><p><strong>1. Test important business rules.</strong> Don’t add assertions just to increase the number of tests.</p><p><strong>2. Keep assertions understandable.</strong> Another engineer should be able to understand what failed and why.</p><p><strong>3. Test the correct level of detail.</strong> A uniqueness rule for an order table may not apply to an order-line table.</p><p><strong>4. Separate detection from correction.</strong> Assertions identify invalid data; they don’t automatically fix it.</p><p><strong>5. Avoid unnecessary expensive checks.</strong> Assertions also consume BigQuery resources, so consider table size and execution frequency.</p><p><strong>6. Validate important outputs.</strong> Don’t stop at checking whether individual columns contain valid values.</p><p><strong>7. Define ownership.</strong> Someone should be responsible for investigating critical failures.</p><p><strong>8. Monitor recurring failures.</strong> A test that fails every day without action isn’t providing much value.</p><h3>14. The Bigger Picture: Data Quality Is a Process</h3><p>A reliable data quality strategy includes more than assertions.</p><pre>Data Quality<br>                    │<br>        ┌───────────┼───────────┐<br>        ▼           ▼           ▼<br>     Prevent      Detect      Respond<br>        │           │           │<br>   Good Design  Assertions   Alerts<br>   Validation   Monitoring   Recovery</pre><ul><li><strong>Prevent:</strong> Design models and ingestion processes to reduce errors.</li><li><strong>Detect:</strong> Use assertions and monitoring to identify unexpected data.</li><li><strong>Respond:</strong> Investigate, correct, recover, and verify.</li></ul><p>This is how you move from simply writing data transformations to operating a reliable data platform.</p><h3>Final Thoughts</h3><p>Dataform assertions help you answer a critical question:</p><p><strong>Can I trust the data produced by my pipeline?</strong></p><p>They can catch missing values, duplicates, invalid relationships, unexpected dates, and other problems before those issues silently affect reporting.</p><p>But assertions are only as good as the rules you define.</p><p>Start with the business-critical checks, measure their effectiveness, and expand your testing strategy as your project grows.</p><p>Because in production data engineering:</p><blockquote><em>A successful query tells you that the computation ran. A successful data quality strategy gives you more confidence that the result is worth trusting.</em></blockquote><h3>What’s Next? — Part 15</h3><p>We’ve now covered 14 parts of the Dataform series:</p><ol><li>Dataform for Beginners</li><li>Understanding ref()</li><li>Incremental Tables</li><li>Assertions and Data Quality</li><li>Dataform + BigQuery Architecture</li><li>Dataform + Git</li><li>Deploying Dataform to Production</li><li>Building a Dataform Project from Scratch</li><li>Dataform Best Practices</li><li>Dataform Tags and Selective Execution</li><li>Dependencies and DAGs</li><li>Performance and BigQuery Cost Optimization</li><li>Workflow Settings and Scheduling</li><li>Advanced Testing and Data Quality</li></ol><p><strong>Next: Part 15 — Build an End-to-End Production Dataform Project</strong></p><p>We’ll bring the concepts together in one practical project, from raw data and staging models to incremental transformations, assertions, Git, scheduling, and production deployment.</p><p>The goal is to connect the individual concepts into one coherent data engineering workflow.</p><p>#Dataform #BigQuery #DataEngineering #GoogleCloud #GCP #SQL #ETL #ELT #AnalyticsEngineering #DataQuality</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39d449bb1605" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dataform Workflow Settings & Scheduling: How to Run Data Pipelines Automatically]]></title>
            <link>https://medium.com/@abhint2603/dataform-workflow-settings-scheduling-how-to-run-data-pipelines-automatically-ccdba07b0a1d?source=rss-fd6e8dab532------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccdba07b0a1d</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[analytics-engineering]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Abhishek Nath Tiwari]]></dc:creator>
            <pubDate>Mon, 05 Oct 2026 09:31:33 GMT</pubDate>
            <atom:updated>2026-10-05T09:31:33.299Z</atom:updated>
            <content:encoded><![CDATA[<p>So far in this series, we’ve focused heavily on building Dataform models.</p><p>We’ve learned about:</p><ul><li>ref()</li><li>Incremental tables</li><li>Assertions</li><li>Tags</li><li>Dependencies</li><li>DAGs</li><li>Git</li><li>Production best practices</li><li>BigQuery performance and cost optimization</li></ul><p>But there’s an important question we haven’t fully answered yet:</p><blockquote><strong><em>How does the pipeline actually run automatically?</em></strong></blockquote><p>Imagine you’ve built a Dataform project that transforms your e-commerce data:</p><pre>Raw Orders<br>    ↓<br>Staging<br>    ↓<br>Completed Orders<br>    ↓<br>Daily Sales<br>    ↓<br>Dashboard</pre><p>You don’t want an engineer manually starting this pipeline every morning.</p><p>You want:</p><pre>Every day<br>    ↓<br>Pipeline starts<br>    ↓<br>Data transformations run<br>    ↓<br>Data quality checks run<br>    ↓<br>Dashboard gets updated</pre><p>That’s where <strong>workflow scheduling and execution settings</strong> become important.</p><h3>1. Building a Pipeline Is Only Half the Job</h3><p>Think about a typical data platform.</p><p>You might have:</p><pre>Source Systems<br>      ↓<br>Data Ingestion<br>      ↓<br>BigQuery<br>      ↓<br>Dataform<br>      ↓<br>Analytics Tables<br>      ↓<br>Dashboard</pre><p>Writing the Dataform SQL handles the transformation part.</p><p>But production also needs:</p><pre>When should it run?<br>What should it run?<br>What happens if it fails?<br>How often should it run?<br>How do we monitor it?</pre><p>A production data pipeline needs both:</p><pre>Transformation Logic<br>        +<br>Workflow Orchestration</pre><h3>2. What Is a Workflow?</h3><p>A workflow is essentially a definition of:</p><blockquote><strong><em>What should happen, and when?</em></strong></blockquote><p>For example:</p><pre>Daily Sales Workflow</pre><pre>1. Start<br>2. Run staging models<br>3. Run order transformations<br>4. Run sales models<br>5. Run assertions<br>6. Finish</pre><p>Conceptually:</p><pre>               Daily Schedule<br>                    ↓<br>                 Dataform<br>                    ↓<br>              Staging Models<br>                    ↓<br>             Business Models<br>                    ↓<br>               Assertions<br>                    ↓<br>                 Success</pre><p>The exact implementation depends on your Dataform and Google Cloud setup, but the important idea is that your transformation code and your execution schedule are separate concerns.</p><h3>3. Why Scheduling Matters</h3><p>Imagine your business dashboard is expected to show yesterday’s sales by:</p><pre>8:00 AM</pre><p>Your pipeline needs to complete before that.</p><p>So you might design:</p><pre>2:00 AM<br>   ↓<br>Data arrives<br>   ↓<br>3:00 AM<br>   ↓<br>Dataform transformation<br>   ↓<br>4:00 AM<br>   ↓<br>Data quality checks<br>   ↓<br>5:00 AM<br>   ↓<br>Dashboard-ready tables<br>   ↓<br>8:00 AM<br>   ↓<br>Business users open dashboard</pre><p>The schedule isn’t just a technical detail.</p><p>It is connected to a <strong>business requirement</strong>.</p><h3>4. Choose the Right Frequency</h3><p>Not every pipeline needs to run every hour.</p><p>You might have:</p><h3>Hourly</h3><pre>Every hour</pre><p>Useful for:</p><ul><li>Operational dashboards</li><li>Near-real-time analytics</li><li>Frequently changing data</li></ul><h3>Daily</h3><pre>Once per day</pre><p>Useful for:</p><ul><li>Daily sales</li><li>Daily customer metrics</li><li>Daily reporting</li></ul><h3>Weekly</h3><pre>Once per week</pre><p>Useful for:</p><ul><li>Weekly business reports</li><li>Aggregated analytics</li><li>Less frequently changing data</li></ul><h3>Monthly</h3><pre>Once per month</pre><p>Useful for:</p><ul><li>Financial reporting</li><li>Monthly business summaries</li><li>Long-term aggregations</li></ul><p>The rule is simple:</p><blockquote><strong><em>Run the pipeline as frequently as the business actually needs it.</em></strong></blockquote><p>Running a pipeline every 15 minutes doesn’t automatically make it better.</p><h3>5. Scheduling Too Frequently Can Be Expensive</h3><p>Consider a pipeline that processes:</p><pre>100 GB</pre><p>every time it runs.</p><p>If you run it once per day:</p><pre>100 GB × 1</pre><p>If you run it every hour:</p><pre>100 GB × 24</pre><p>That’s potentially a very different workload.</p><p>And if the data hasn’t changed between runs, you’re doing unnecessary work.</p><p>This is why scheduling and performance optimization are connected.</p><p>A good schedule should consider:</p><pre>Data freshness<br>      +<br>Business requirement<br>      +<br>Processing cost<br>      +<br>Pipeline duration</pre><h3>6. Scheduling Doesn’t Fix a Bad Pipeline</h3><p>This is an important distinction.</p><p>Suppose your model processes:</p><pre>1 TB</pre><p>every day.</p><p>Changing the schedule from:</p><pre>Daily</pre><p>to:</p><pre>Hourly</pre><p>doesn’t make the transformation more efficient.</p><p>It simply runs the expensive transformation more often.</p><p>Instead, improve the transformation itself.</p><p>For example:</p><pre>Bad approach</pre><pre>1 TB full scan<br>      ↓<br>Every hour</pre><p>Better:</p><pre>Incremental processing<br>      ↓<br>Only changed data<br>      ↓<br>Daily/hourly based on requirement</pre><p>This is why we discussed incremental models in Part 3 and optimization in Part 12.</p><h3>7. Scheduling and Dependencies Work Together</h3><p>Remember the DAG from Part 11?</p><p>For example:</p><pre>raw_orders<br>     ↓<br>stg_orders<br>     ↓<br>completed_orders<br>     ↓<br>daily_sales</pre><p>You don’t want:</p><pre>daily_sales</pre><p>to run before:</p><pre>completed_orders</pre><p>has finished.</p><p>That’s where dependencies matter.</p><p>Your workflow essentially needs to respect:</p><pre>Dependency Graph<br>        ↓<br>Execution Order</pre><p>So:</p><pre>raw_orders<br>     ↓<br>stg_orders<br>     ↓<br>completed_orders<br>     ↓<br>daily_sales</pre><p>The scheduler determines <strong>when the workflow starts</strong>.</p><p>The dependency graph determines <strong>how the transformations relate to one another</strong>.</p><h3>8. Scheduling and Tags Work Together Too</h3><p>We discussed tags in Part 10.</p><p>Suppose you have:</p><pre>daily<br>hourly<br>monthly</pre><p>tags.</p><p>You might conceptually organize workflows like:</p><pre>Daily Workflow<br>     ↓<br>daily models</pre><pre>Hourly Workflow<br>     ↓<br>hourly models</pre><pre>Monthly Workflow<br>     ↓<br>monthly models</pre><p>This becomes especially useful in large projects.</p><p>For example:</p><pre>                   Dataform<br>                       │<br>          ┌────────────┼────────────┐<br>          ↓            ↓            ↓<br>        Hourly        Daily       Monthly<br>          │            │            │<br>          ↓            ↓            ↓<br>       Models        Models       Models</pre><p>Tags help classify the models.</p><p>The workflow determines when those groups should be executed.</p><h3>9. Don’t Make One Giant Workflow</h3><p>Imagine your project has:</p><pre>500 models</pre><p>and you create:</p><pre>One giant workflow</pre><p>that runs everything every day.</p><p>That might be simple initially.</p><p>But eventually you may have:</p><pre>Sales<br>Marketing<br>Finance<br>Customers<br>Inventory<br>Operations</pre><p>with different requirements.</p><p>Instead, you can think in terms of logical workflows:</p><pre>                    Production<br>                        │<br>        ┌───────────────┼────────────────┐<br>        ↓               ↓                ↓<br>      Sales          Customer         Finance<br>        │               │                │<br>      Daily           Daily           Monthly</pre><p>This can make operations easier to understand.</p><p>The exact workflow design should depend on your project’s size and business requirements.</p><h3>10. Use Dependencies Instead of Hardcoded Timing</h3><p>Here’s a common mistake.</p><p>Imagine:</p><pre>Job A<br>runs at 2:00 AM</pre><pre>Job B<br>runs at 3:00 AM</pre><pre>Job C<br>runs at 4:00 AM</pre><p>Someone assumes:</p><pre>A will always finish before B.<br>B will always finish before C.</pre><p>But what happens if Job A takes longer?</p><pre>2:00 AM<br>Job A starts</pre><pre>3:00 AM<br>Job A still running</pre><pre>Job B starts anyway</pre><p>Now you have a race condition.</p><p>Instead of relying only on time, use dependency relationships wherever possible.</p><p>Think:</p><pre>A<br> ↓<br>B<br> ↓<br>C</pre><p>rather than:</p><pre>2 AM → A<br>3 AM → B<br>4 AM → C</pre><p>Time schedules tell you <strong>when to start</strong>.</p><p>Dependencies tell you <strong>what must happen before what</strong>.</p><p>That’s a much stronger design.</p><h3>11. Design for Late Data</h3><p>This is a very common real-world problem.</p><p>Suppose your pipeline normally receives:</p><pre>Yesterday&#39;s orders</pre><p>by:</p><pre>2:00 AM</pre><p>But one day the source system is delayed.</p><p>Your Dataform workflow starts at:</p><pre>3:00 AM</pre><p>and the data isn’t complete.</p><p>The pipeline may successfully execute while producing incomplete results.</p><p>So you need to think about:</p><pre>Source data arrival<br>        ↓<br>Data availability<br>        ↓<br>Transformation<br>        ↓<br>Data quality<br>        ↓<br>Reporting</pre><p>The correct schedule isn’t necessarily:</p><blockquote><em>“Run Dataform at midnight.”</em></blockquote><p>It might be:</p><blockquote><em>“Run Dataform after the source data is expected to be available.”</em></blockquote><h3>12. Add Data Quality Checks After Transformation</h3><p>A production workflow shouldn’t only ask:</p><blockquote><em>Did the SQL execute?</em></blockquote><p>It should also ask:</p><blockquote><em>Is the resulting data valid?</em></blockquote><p>For example:</p><pre>Data arrives<br>    ↓<br>Dataform transformations<br>    ↓<br>Assertions<br>    ↓<br>Quality check<br>    ↓<br>Success / Failure</pre><p>Suppose:</p><pre>daily_sales</pre><p>was expected to contain:</p><pre>1,000 orders</pre><p>but suddenly contains:</p><pre>0 orders</pre><p>The SQL may technically succeed.</p><p>But the business result is probably wrong.</p><p>Assertions and monitoring help catch these situations.</p><h3>13. Think About Failure Handling</h3><p>Every production pipeline will eventually fail.</p><p>It could be:</p><ul><li>Source data missing</li><li>Permission issue</li><li>SQL error</li><li>BigQuery problem</li><li>Invalid data</li><li>Dependency failure</li><li>Infrastructure issue</li></ul><p>So don’t design only for:</p><pre>Success</pre><p>Design for:</p><pre>Success<br>Failure<br>Retry<br>Recovery<br>Alert</pre><p>A simplified production flow might look like:</p><pre>             Scheduled Run<br>                   ↓<br>              Dataform<br>                   ↓<br>              Transform<br>                   ↓<br>             Data Quality<br>                   ↓<br>          ┌────────┴────────┐<br>          ↓                 ↓<br>       SUCCESS            FAILURE<br>          ↓                 ↓<br>      Dashboard           Alert<br>                            ↓<br>                         Investigate</pre><h3>14. Monitor Pipeline Duration</h3><p>Suppose your pipeline normally takes:</p><pre>20 minutes</pre><p>Then suddenly:</p><pre>35 minutes</pre><p>Then:</p><pre>55 minutes</pre><p>Then:</p><pre>90 minutes</pre><p>Something is changing.</p><p>Maybe:</p><ul><li>Data volume increased</li><li>A query became inefficient</li><li>A partition isn’t being used</li><li>A new model was added</li><li>A dependency changed</li></ul><p>Pipeline duration itself can be an important operational metric.</p><p>You should know:</p><pre>Expected runtime<br>Actual runtime<br>Failure rate<br>Data processed</pre><h3>15. Think About the SLA</h3><p>SLA stands for:</p><blockquote><strong><em>Service Level Agreement</em></strong></blockquote><p>In data engineering, you might have a requirement such as:</p><blockquote><em>“Daily sales data must be available by 8:00 AM.”</em></blockquote><p>Now your pipeline has a concrete target.</p><p>For example:</p><pre>Source data available<br>        ↓<br>2:00 AM</pre><pre>Dataform starts<br>        ↓<br>3:00 AM</pre><pre>Transformations finish<br>        ↓<br>4:30 AM</pre><pre>Assertions finish<br>        ↓<br>5:00 AM</pre><pre>Dashboard refreshed<br>        ↓<br>6:00 AM</pre><pre>SLA<br>        ↓<br>8:00 AM</pre><p>Now you have:</p><pre>2-hour buffer</pre><p>That buffer is valuable.</p><p>If your pipeline normally finishes at 7:55 AM, you don’t really have a reliable SLA.</p><h3>16. A Production Workflow Example</h3><p>Let’s build a simple production scenario.</p><p>Our e-commerce company receives order data every day.</p><p>The requirement:</p><blockquote><em>Yesterday’s sales should be available by 7:00 AM.</em></blockquote><p>We could conceptually design:</p><pre>                Source System<br>                      │<br>                      ▼<br>                 Raw Orders<br>                      │<br>                      ▼<br>              Data Availability<br>                      │<br>                      ▼<br>               Dataform Start<br>                      │<br>                      ▼<br>                Staging Models<br>                      │<br>                      ▼<br>             Business Transformations<br>                      │<br>                      ▼<br>                Data Assertions<br>                      │<br>              ┌───────┴───────┐<br>              ↓               ↓<br>           SUCCESS          FAILURE<br>              ↓               ↓<br>         Sales Tables        Alert<br>              │<br>              ▼<br>          Dashboard<br>              │<br>              ▼<br>           7:00 AM</pre><p>This is much closer to how a real production data pipeline should be designed.</p><h3>17. A Simple Scheduling Strategy</h3><p>For our example:</p><pre>Daily</pre><pre>01:00 AM<br>↓<br>Source ingestion</pre><pre>02:30 AM<br>↓<br>Data availability check</pre><pre>03:00 AM<br>↓<br>Dataform transformations</pre><pre>04:30 AM<br>↓<br>Assertions / validation</pre><pre>05:00 AM<br>↓<br>Dashboard refresh</pre><pre>07:00 AM<br>↓<br>Business users</pre><p>Notice something important.</p><p>We aren’t scheduling every individual model manually.</p><p>We’re designing the <strong>workflow</strong> around the dependency graph.</p><p>That makes the system much easier to maintain.</p><h3>18. Dataform Is One Part of the Bigger System</h3><p>This is perhaps the most important lesson.</p><p>Dataform doesn’t exist in isolation.</p><p>A production architecture may look like:</p><pre>                Source Systems<br>                      │<br>                      ▼<br>                 Cloud Storage<br>                      │<br>                      ▼<br>                   BigQuery<br>                      │<br>                      ▼<br>                  Dataform<br>                      │<br>             ┌────────┴────────┐<br>             ↓                 ↓<br>        Transformations    Assertions<br>             │                 │<br>             └────────┬────────┘<br>                      ↓<br>                Analytics Tables<br>                      │<br>                      ▼<br>                   BI Tool</pre><p>And around this:</p><pre>Scheduling<br>Monitoring<br>Alerting<br>Git<br>CI/CD<br>Access Control</pre><p>That’s what turns individual SQL transformations into a production data platform.</p><h3>19. My Production Scheduling Checklist</h3><p>Before scheduling a Dataform workflow, I would ask:</p><pre>☑ When is the source data available?</pre><pre>☑ How fresh does the business need the data to be?</pre><pre>☑ How long does the pipeline normally take?</pre><pre>☑ What is the acceptable SLA?</pre><pre>☑ Are dependencies correctly defined?</pre><pre>☑ Are we running only the required models?</pre><pre>☑ Can the pipeline handle late-arriving data?</pre><pre>☑ Are data quality checks included?</pre><pre>☑ What happens if the pipeline fails?</pre><pre>☑ Who gets notified?</pre><pre>☑ Can the pipeline be safely retried?</pre><pre>☑ Are runtime and failures being monitored?</pre><p>These questions are often more important than simply choosing a cron expression.</p><h3>20. The Biggest Lesson</h3><p>A scheduler answers:</p><blockquote><strong><em>When should I start?</em></strong></blockquote><p>Dependencies answer:</p><blockquote><strong><em>What needs to happen first?</em></strong></blockquote><p>Assertions answer:</p><blockquote><strong><em>Is the result valid?</em></strong></blockquote><p>Monitoring answers:</p><blockquote><strong><em>Did everything behave normally?</em></strong></blockquote><p>Together:</p><pre>            Production Pipeline<br>                      │<br>       ┌──────────────┼──────────────┐<br>       ↓              ↓              ↓<br>   Schedule       Dependencies    Assertions<br>       │              │              │<br>       └──────────────┼──────────────┘<br>                      ↓<br>                  Monitoring<br>                      ↓<br>                   Reliable<br>                   Pipeline</pre><p>That’s the mindset you need when moving from a development project to a production data platform.</p><h3>Final Thoughts</h3><p>Scheduling a pipeline isn’t simply:</p><blockquote><em>“Run this SQL every day at 3 AM.”</em></blockquote><p>A production workflow needs to consider:</p><ul><li>Data availability</li><li>Dependencies</li><li>Frequency</li><li>Runtime</li><li>Cost</li><li>Data quality</li><li>Failures</li><li>Retries</li><li>Monitoring</li><li>Business SLAs</li></ul><p>The best pipelines are designed around the <strong>business requirement</strong>, not just the technical implementation.</p><p>For example:</p><blockquote><em>“The dashboard must be ready by 8 AM.”</em></blockquote><p>is a much better starting point than:</p><blockquote><em>“Let’s run Dataform at 5 AM.”</em></blockquote><p>Once you know the business requirement, you can work backward:</p><pre>Business SLA<br>     ↓<br>Dashboard refresh<br>     ↓<br>Dataform completion<br>     ↓<br>Dataform start<br>     ↓<br>Data availability<br>     ↓<br>Source ingestion</pre><p>That’s how production data engineering should be approached.</p><h3>What’s Next?</h3><p>We’ve now covered:</p><p><strong>Part 1</strong> — Dataform for Beginners<br><strong>Part 2</strong> — Understanding ref()<br><strong>Part 3</strong> — Incremental Tables<br><strong>Part 4</strong> — Assertions &amp; Data Quality<br><strong>Part 5</strong> — Dataform + BigQuery Architecture<br><strong>Part 6</strong> — Dataform + Git<br><strong>Part 7</strong> — Deploying Dataform to Production<br><strong>Part 8</strong> — Building a Dataform Project from Scratch<br><strong>Part 9</strong> — Dataform Best Practices<br><strong>Part 10</strong> — Dataform Tags &amp; Selective Execution<br><strong>Part 11</strong> — Dataform Dependencies &amp; DAGs<br><strong>Part 12</strong> — Dataform Performance &amp; BigQuery Cost Optimization<br><strong>Part 13</strong> — Dataform Workflow Settings &amp; Scheduling</p><p>Only <strong>2 articles remain</strong>.</p><h3>Coming next:</h3><p><strong>Part 14 — Dataform Advanced Testing &amp; Data Quality: Building Pipelines You Can Trust</strong></p><p>We’ll go deeper into data quality, including <strong>uniqueness, null checks, referential integrity, business rules, and how to think about data tests like software tests.</strong></p><h3>Data Engineering | Dataform | BigQuery</h3><p>#Dataform #BigQuery #DataEngineering #GCP #GoogleCloud #SQL #ETL #ELT #AnalyticsEngineering #DataQuality</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccdba07b0a1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>