<?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 Satwiki De on Medium]]></title>
        <description><![CDATA[Stories by Satwiki De on Medium]]></description>
        <link>https://medium.com/@satwikide?source=rss-d4bbc4d61092------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yB4zuwfGhjM1eqmGwRwLOw.jpeg</url>
            <title>Stories by Satwiki De on Medium</title>
            <link>https://medium.com/@satwikide?source=rss-d4bbc4d61092------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:10:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@satwikide/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[Evaluating Agent Skills and Custom Agents: Are they actually making your work easier?]]></title>
            <link>https://medium.com/@satwikide/evaluating-agent-skills-and-custom-agents-are-they-actually-making-your-work-easier-8cfb04bc6325?source=rss-d4bbc4d61092------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cfb04bc6325</guid>
            <category><![CDATA[ai-evaluation]]></category>
            <category><![CDATA[github-copilot]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[agent-skills]]></category>
            <dc:creator><![CDATA[Satwiki De]]></dc:creator>
            <pubDate>Fri, 16 Oct 2026 13:24:45 GMT</pubDate>
            <atom:updated>2026-10-16T13:24:45.164Z</atom:updated>
            <content:encoded><![CDATA[<p>Agentic AI is reshaping the enterprise SDLC (Software Development Lifecycle), with agent skills and custom agent orchestration becoming key components of this transformation.</p><p>Traditionally, SDLC effectiveness was measured through metrics such as development velocity, pull requests created vs merged, features delivered, and bugs resolved. With AI making code/PR generation faster, teams are increasingly adopting AI-native workflows to accelerate software delivery. Tools such as GitHub Copilot (GHCP) and Claude Code are enabling these workflows through providing the option to engineers to create specialized custom agents, reusable agent skills, and automated task execution orchestration.</p><p>As teams keep creating skills and custom agents, questions around their effectiveness, reliability, and continued relevance become increasingly important. Also another question raises that — while a certain skill created by a developer may work as expected in their environment, how to determine if it is ready to be adopted in the broader team or organization?</p><p>Some questions that I found myself asking -</p><ul><li>Are the targeted capabilities being invoked when needed? Especially when the inputs are not always predictable?</li><li>Are they improving code/solution/review quality?</li><li>How much confidence can you put on your Custom agent’s outcome?</li></ul><p>The idea is to move beyond subjective assessments towards repeatable, automated and benchmark-driven evaluation of agent skills and custom agents.</p><h3>Agent Skills and Custom Agents</h3><p>Agent skills package reusable instructions, scripts, domain or business-specific knowledge and resources that help agents perform specific tasks. Custom agents define specialized behavior, tools, and responsibilities for particular workflows.</p><p>In GitHub Copilot, these capabilities coupled with coding agent can help standardize activities such as code reviews, task orchestration, release note creation, security analysis etc. While custom agents can be invoked using Copilot CLI or Chat window directly, skill can be both invoked directly and also be loaded by the model based on its metadata.</p><h3>Capability drift issue</h3><p>In my experience, skill effectiveness can drift as solution structures evolve, new features and architectural complexities are introduced, additional repositories become part of the working context, or business rules and assumptions embedded in skills become outdated. Since agent skills contain instructions and can reference supporting files and scripts, changes to these dependencies can affect whether a skill continues to produce the intended results. GitHub Copilot documentation also notes that skills are selected based on task relevance, meaning that correct invocation is itself an important aspect to evaluate. (<a href="https://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-cloud-agent/add-skills">GitHub Docs: Agent Skills</a>)</p><p>For custom agents, the failure surface can be broader. In GitHub Copilot, agent profiles can include more than just instructions — available tools and MCP server configurations, which workspace folder it should access; as well as sub-agent handoffs for long-running, orchestration tasks. These configurations determine the agent’s capabilities and the boundaries within which it operates. The objective is to verify that the agent reliably completes its intended task and produces outcomes that meet explicit acceptance criteria while adapting to diverse input scenarios, not merely that it executes without errors. (<a href="https://docs.github.com/en/copilot/concepts/agents/cloud-agent/about-custom-agents">GitHub Docs: Custom Agents</a>)</p><p>Agents can also become less effective as the surrounding codebase, repository structure, or dependent workflows evolve. For example, when specs change, CI pipelines change, release procedures are updated, or tag-creation conventions are modified. These changes can invalidate previously correct agent instructions or assumptions.</p><p>The question I came up with is — can we automatically detect drifts as new scenarios/inputs emerge and when skills, agent configurations, models, codebases, or dependent workflows change?</p><p>Rather than relying solely on manual review, can we build repeatable benchmarks that test invocation, task completion, output correctness, and adherence to workflow-specific requirements?</p><h3>Moving towards evaluation-driven automation and benchmarking</h3><p>What I’ve been seeing is a growing need for teams to build their own scenario-specific or business context-specific benchmarking, rather than depending on LLM’s benchmark data. The <a href="https://agentskills.io/skill-creation/evaluating-skills">Agent Skills evaluation guide</a> provides a useful starting point for evaluating skills against representative tasks and expected outcomes.</p><p>Building on this approach, I recommend following approach.</p><p>1. Establish a baseline -</p><ul><li>Define what success looks like before testing.</li><li>Create realistic test cases covering common requests, different phrasings, and edge cases.</li><li>Specify observable pass/fail criteria.</li><li>Keep successful tests as a regression suite to catch future problems.</li></ul><p>The goal is to move beyond human judging from just few responses, and establish a repeatable, structured process.</p><p>2. Measure skill invocation and outcome. Capture execution traces or logs to establish whether the intended skill was selected and used for a diverse set of inputs. Build baseline without skill and then invoke skill to measure the change. Use following evaluation methods:</p><ul><li>Does it improve results? Run identical prompts with and without the skill. Compare correctness, completeness, and usefulness.</li><li>Does it handle variation? Test different phrasings, incomplete inputs, unusual cases, and relevant files.</li><li>Is the improvement worth the cost? Compare output quality alongside execution time and token usage.</li></ul><p>3. Evaluating custom agents — following are some of the parameters to test:</p><ul><li>Role adherence: Does it stay within its intended persona?</li><li>Tool selection: Does it use the appropriate tools and pass the correct inputs?</li><li>Task completion: Does it achieve the requested outcome? Could be a plan document, updated files count + new version in changelog, release notes with correct tag, CI pipeline trigger, invoking another sub-agent etc.</li><li>Boundaries: Does it handle unsupported requests, described constraints in its instructions, missing information, and unsafe prompts appropriately?</li><li>Reliability: Does it behave consistently across scenarios, without unnecessary actions or failures?</li><li>System-level metrics: Metrics such as execution time and token consumption can help assess effectiveness and cost.</li></ul><p>4. Detect regressions. Re-run the benchmark when skill instructions, agent configurations, models, or underlying codebases change.</p><h3>Experimenting With a Benchmark</h3><p>I have been building a benchmark to evaluate custom agents and agent skills that I had published before. V0 is available in my GitHub: <a href="https://github.com/satwiki/custom-agent-and-skills/tree/feat/evals">https://github.com/satwiki/custom-agent-and-skills</a></p><p>My objective was to establish a repeatable way to inspect custom agent behavior, evaluate skill outputs, and build a benchmark from each eval run that will measure the effectiveness. Having benchmarking results from multiple executions will also determine whether the skill or custom agents are improving or degrading over time.</p><p>I’ve used deterministic assertions (or heuristics) for objectively verifiable requirements, along with LLM-as-judge for qualitative aspects. Deterministic checks are easy to trigger in local dev environment or CI pipelines, whereas the other method will require access to language models through a provider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/0*Cl5rxeHa7QB63MRF" /><figcaption>How the benchmark looks like</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*38hVgCQAhLrIXTiX" /><figcaption>Detailed results with Pass/Fail metrics and reasoning</figcaption></figure><p>For enterprise adoption, I recommend the scenarios and rubrics for LLM-as-judge to be customized to reflect the team’s or organization’s actual development workflows. For example, to capture scenarios for code reviewer agent, use the data from your team’s PR history and find out common patterns of engineering standards, mistakes team made before, review comments that actually caught issues.</p><p>Worth exploring next — for GitHub Copilot cloud agents, GitHub documents a private testing workflow. Keep a test agent in .github-private/.github/agents, test it through the Copilot agents interface, inspect session details, iterate, and move the profile to the release location when ready.</p><h3>Final takeaway</h3><p>Building and maintaining evals comes with a cost in engineering effort and token consumption, particularly when model-based grading is required. For smaller teams or early-stage experiments, this may seem like unnecessary overhead, and manual judgment may be sufficient initially.</p><p>However, as agent capabilities are reused across teams, repositories, and workflows, manual validation becomes harder to scale consistently. Without repeatable evaluations, teams risk discovering regressions only after an agent starts producing incorrect or unnecessary output. Automated evals provide a way to track task success, output quality, latency, and cost over time, while keeping human judgment in the loop where it adds the most value.</p><p>I believe that as the agentic SDLC evolves towards multi-agent systems and orchestrated automation, evaluating skills and custom agents with the same discipline as other software components will become increasingly important.</p><p>I have shared my experiment above as a starting point. It is intentionally generic, so adapting the scenarios, benchmark and acceptance criteria to your enterprise workflows is essential. I would welcome feedback, questions, and perspectives on how others are measuring SDLC agent effectiveness in practice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cfb04bc6325" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Text-to-SQL Agentic AI for enterprise analytical tasks]]></title>
            <link>https://medium.com/@satwikide/building-text-to-sql-agentic-ai-for-enterprise-analytical-tasks-af75c19b7792?source=rss-d4bbc4d61092------2</link>
            <guid isPermaLink="false">https://medium.com/p/af75c19b7792</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[multi-agent-systems]]></category>
            <category><![CDATA[enterprise-architecture]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Satwiki De]]></dc:creator>
            <pubDate>Thu, 17 Sep 2026 14:37:01 GMT</pubDate>
            <atom:updated>2026-09-17T15:13:38.230Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lWI34LwQMfESi4j07h1bYA.png" /></figure><p>With the emergence of more capable frontier models, Text-to-SQL (or natural language-to-SQL) performance has gone up significantly. LLMs are now capable of generating complex SQL queries more accurately just from the description text.</p><p>However, <strong>strong benchmark performance does not automatically translate into a reliable enterprise Text-to-SQL system in production</strong>.</p><p>The distinction becomes apparent when moving from a prototype in an controlled environment to a real enterprise data ecosystem. A prototype may operate against a small subset of a database, with a handful of well-defined tables, relatively clean schemas, and questions that are known in advance. In that setting, providing the schema to a frontier model and asking it to generate SQL can produce impressive results.</p><p>Enterprise environments are usually noisy. Data is often distributed across multiple databases and schemas, table and column names may not correspond cleanly to the terminology used by business users, and the relevant information may be buried within thousands of schema elements. Business questions can also require domain-specific interpretation. Research on enterprise-specific benchmarks has found that these factors make Text-to-SQL substantially harder than many traditional benchmarks suggest.</p><p>There is another challenge that comes up in <strong>conversational analytics scenarios</strong>: the system is not merely translating a sentence into SQL. It must determine what the user actually means, identify the relevant data sources, resolve ambiguous terminology, construct the appropriate query, execute it without any side effects, and determine whether the result is consistent with the original intent. <em>An SQL query can be syntactically valid and executable while still being semantically wrong.</em></p><p>Recent studies increasingly treats <strong>schema linking and grounding as first-class problems</strong>, rather than assuming that SQL generation is the only challenge. This leads to an important architectural question:</p><blockquote><strong><em>If frontier models are already capable of generating complex SQL, why do we need a multi-step or multi-agent architecture at all?</em></strong></blockquote><p>As a Senior Consultant in Microsoft, I’ve had first-hand experience that <strong>enterprise Text-to-SQL is not a single SQL-generation problem</strong>. It is <strong><em>a sequence of interconnected, decision-making steps with involving intent understanding, data-source discovery, schema grounding, query planning, SQL generation, execution and self-correction.</em></strong> Treating all of these as a single model call can work for simpler cases, but becomes increasingly fragile as the size, ambiguity, and complexity of the data environment grows.</p><h3>How do we build useful text-to-SQL use cases for enterprise production?</h3><p>I’ve built this prototype to demonstrate Text-to-SQL to answer analytical, exploratory, business intelligence style questions, grounded on a local e-commerce DB. <strong><em>This is built on RAG principle, with reasoning-based, self-correcting loops running in a multi-step Agentic AI orchestration to provide best answer to analytical queries.</em></strong></p><p>First loop component allow the Agentic AI system to correct its own queries, and another loop allows it to generate and run more than one SQL to build output for more exploratory asks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OU0Ni4LmxZBwdBQoBS44zQ.png" /></figure><p>Here’s the source code on GitHub: <a href="https://github.com/satwiki/RAG-orchestration-with-evals">https://github.com/satwiki/RAG-orchestration-with-evals</a></p><h4>Step 1: Set up source of truth</h4><p>The schema in my local SQLite DB includes categories, products, customers, orders, order items, and daily product engagement. Mostly enough structure to support questions about revenue, fulfillment, customer activity, product performance, demand, and conversion proxies. The one-time script to create the DB as below:</p><pre>python src/local_db/ecommerce/populate_db.py</pre><p><strong>Some best practices I recommend for enterprise-level use cases:</strong></p><ol><li>Pre-processing data to remove noise before passing to agent</li><li>Creating materialized views and refreshing on a regular cadence</li><li>Maintaining a centralized catalogue or schema definition</li><li>Caching parsed SQL</li></ol><h4>Step 2: Grounding artifact for SQL generation using Agent skill</h4><p>Text-to-SQL generation needs more than a list of table names. The model needs to know data definitions. Even though the frontier models can identify some of these fields easily by reading the columns, however as per my experience, <strong><em>business context often carries slightly different meaning than generalised text, and certain queries may require additional formulation or related columns to be useful. This is where separation of database knowledge from database orchestration matters.</em></strong></p><p>Skills are loaded in <em>Progressive Disclosure</em> manner — metadata first, and the entire content only when it is needed. I kept that schema in src/skills/ecommerce-db-schema.md file.</p><h4>Step 3: Build a multi-agent flow for analytical questions</h4><p>The next step was to turn a broad user request into a controlled sequence of smaller decisions. The solution is designed for analytical, business intelligence, reporting, exploratory, and metric-driven questions such as:</p><ul><li>Which products generated the most revenue in last month?</li><li>Which categories performed best in each year?</li><li>Most converted products and categories in last quarter?</li></ul><blockquote>I’ve used gpt-5.4-nano from Foundry for this exercise. It is configurable, and can be replaced with OpenAI or other providers with minimal code changes.</blockquote><h4>3.1 intent detector</h4><p>The intent detector is the gatekeeper. It uses structured output to decide whether the question is — 1) safe to proceed with, 2) can be answered with a read-only analytics query. If the request is blocked, the workflow records the reason and ends right there.</p><h4>3.2 query generator</h4><p>The query generator receives the user question, loads the schema skill, and any relevant history from earlier turns. It returns a structured GeneratedQuery object containing SQLite SELECT or WITH ... SELECT statement.</p><p>The structured response is intentional. Returning a typed field for SQL is easier to validate than asking downstream code to extract a query from free form text.</p><h4>3.3 query validator</h4><p>The validator checks the generated statement before it reaches SQLite. It rejects empty input, multiple statements, non-read-only operations, and SQL that fails the syntax checks. When validation fails, the graph sends feedback back to the query generator, up to three times.</p><p>This retry loop keeps correction close to the stage that introduced the problem. If all retries fail, the workflow records the failure and lets the report builder produce an answer that acknowledges the missing data.</p><h4>3.4 Execute through a tool, with guardrails</h4><p>Validated SQL is executed by execute_readonly_query. The executor appends the SQL, rows, and any error to query_history and passes it on to context which is used downstream for reporting.</p><p>I’ve restricted the agent and evaluator to use read-only rules: a single statement, SELECT or WITH, no write or DDL keywords, and a row limit. However I will build a transactional scenario later.</p><h4>3.5 report builder</h4><p>The report builder stepreceives the original question and result of executed query. It produces a Markdown answer and decides whether another query is needed. If more evidence is required, the graph loops back to the query generator with follow-up instructions.</p><p>The loop is bounded by MAX_TURNS. At the limit, the report builder agent is forced to produce the best answer supported by the data already collected and to identify any remaining gaps.</p><h4>Step 4: visualize</h4><p>Once the graph is compiled and can be consumed, I added a Streamlit application in src/main.py so the workflow could be explored in a chatbot format. Below command will start the application in your local:</p><pre>streamlit run src/main.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J3Ej2-Vatw6vUnKnr5LveA.png" /><figcaption>Snapshot of the Final Answer</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iw7o9MSZ934AekqVla_hZQ.png" /><figcaption>The UI also shows the SQL query and the results generated from it</figcaption></figure><h3>Evaluation</h3><p>Evaluation plays a key role to build confidence on AI use cases performance. As a Sr Consultant in Microsoft, I place weightage on an early-built Evaluation strategy, built upon the business success criteria for the overall scenario.</p><p>I usually start thinking how to map evaluators or metrics to the use case. In this particular one, SQL query and execution accuracy matters the most, next comes answer groundedness. I’ve used DeepEvals for this exercise, while some<a href="https://github.com/satwiki/RAG-orchestration-with-evals/blob/main/architecture%20decision%20records/EVALUATION_FRAMEWORK_RESEARCH.md"> alternatives are documented here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQyC5x4p7xB35VrBqRz1-Q.png" /></figure><blockquote>The code for evaluation is available here: <a href="https://github.com/satwiki/RAG-orchestration-with-evals/tree/main/src/evals">https://github.com/satwiki/RAG-orchestration-with-evals/tree/main/src/evals</a></blockquote><p>Evaluation needs a stable contract between the natural-language question, the database, and the answer to measure “success”. Here it starts with building the golden dataset. Each row of the dataset will contain:</p><ul><li>The user question</li><li>Schema context</li><li>Reference SQL</li><li>A stored reference result</li><li>An expected natural-language answer</li><li>Claims (metadata ) that support the answer</li></ul><blockquote>I created a custom agent to help with building golden dataset for any use case. Check it out here: <a href="https://github.com/satwiki/RAG-orchestration-with-evals/blob/main/.github/agents/rag-groundtruth-builder.agent.md">RAG golden dataset builder</a>.</blockquote><h4>Evaluation metrics results as release gate</h4><p>Comparing answer text alone is not enough. Two different SQL queries can produce the same correct result, and a fluent answer can still contain a wrong number. I therefore made SQL execution accuracy the release gate.</p><p>The SqlExecutionAccuracyMetric follows this sequence:</p><ol><li>Execute the reference SQL against the evaluation database. I’m using local DB here hence I can refer to the same DB, but for actual enterprise scenarios, a snapshot or seed DB may be required.</li><li>Fall back to the stored result only if live reference execution fails.</li><li>Extract the last successful SQL statement produced by the agent.</li><li>Execute the generated statement through the same read-only sandbox.</li><li>Normalize values and compare the result sets.</li></ol><p>Normalization lowercases column names, handles NULL values consistently, converts numeric values to a common representation, and applies a 0.01 absolute tolerance to numeric comparisons. Row order matters when the reference SQL contains ORDER BY; otherwise rows are compared as an order-independent collection while preserving duplicate rows.</p><p>This metric tests the behavior that matters: whether the generated query returns the same analytical result as the reference query on the database the agent used.</p><h4>Add answer correctness as a secondary signal</h4><p>The report could execute the right query and still omit an important number, misstate a ranking, or invent an unsupported conclusion.</p><p>For that layer, I added a DeepEval GEval metric named Answer Correctness. It compares the actual answer with the expected answer and supporting claims. The judge checks key facts, numeric values, entities, time windows, and unsupported-answer behavior while ignoring harmless wording and Markdown differences.</p><h4>Additional metrics</h4><ol><li>Schema Adherence: Checks that generated SQL is read-only and valid against the database schema.</li><li>Contextual Relevancy: Scores whether retrieved schema context is relevant to the question.</li></ol><h4>Executing the evaluation workflow</h4><p>Run it from CLI:</p><pre>python src/evals/run_deepeval.py</pre><p>It can also be triggered from the streamlit UI, and past evaluation reuslts (stored in local) can be viewed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WiXEEJREnVnJtsBAlHaXMg.png" /><figcaption>Trigger evaluation from UI</figcaption></figure><p>The design choice I made here is that evaluation uses the same artifacts as the application: the database, the schema grounding, the SQL, the query history, and the final answer. That alignment makes failures easier to catch early and makes improvements measurable.</p><blockquote>In actual scenarios, where database is hosted in Cloud or on-prem, a snapshot of DB may be required to run in the same environment as evals to validate.</blockquote><h3>Conclusion notes: Few points worth remembering</h3><ol><li>With explicit stages in text-to-SQL pipeline, each step can produce an artifact that can be inspected and evaluated independently.</li><li>Integrating Evaluation in CI/CD process or your project management tool and making it the release gate before promoting agents to higher environment.</li><li>A generator’s job is to construct a plausible query; a verifier’s job is to try to falsify it. This separation is useful because LLMs can produce syntactically plausible SQL that is semantically incorrect.</li><li>Recent research has documented cases where LLM-based validation can attempt unsafe database operations while trying to test a query. A read-only execution environment, SQL allowlisting/AST checks, timeouts, row limits, and an explicit validation controller are therefore important parts of the architecture.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af75c19b7792" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practical Guide to Structured Development with GitHub Speckit]]></title>
            <link>https://medium.com/@satwikide/a-practical-guide-to-structured-development-with-github-speckit-83a4510b05f6?source=rss-d4bbc4d61092------2</link>
            <guid isPermaLink="false">https://medium.com/p/83a4510b05f6</guid>
            <category><![CDATA[enterprise-architecture]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[developer-tools]]></category>
            <dc:creator><![CDATA[Satwiki De]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 14:45:47 GMT</pubDate>
            <atom:updated>2026-06-12T15:05:35.333Z</atom:updated>
            <content:encoded><![CDATA[<h3>How is vibe coding working out for you?</h3><p>The speed and possibilities have been intoxicating. Vibe coding has been one of the fastest adoption curves in the history of software with 63% of user base from non-technical background creating full-stack apps, designing UIs and software. Teams reported shipping faster. Demos look polished. Investors were excited.</p><p>But underneath that promise is a different story. <strong><em>Speed without structure produces illusion of software. And the reality is catching up with the illusion.</em></strong> There’s the structural noise inside vibe-coded repos, also known as ‘AI slops’. A prevalence of 10x code duplication, lacking context, increasing technical debts and surge of un-maintainable code diminishes the quality of software sooner than expected. And speed compounds the problem.</p><p><strong>As per Gartner’s 2025 Predicts report, prompt-to-app approaches adopted by citizen developers will increase software defects by 2500%</strong>, triggering a software quality and reliability crisis. “A new class of defect is emerging as AI generates context-deficient code.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*poj_Pbagiznr909Q_cfAzg.png" /></figure><h3><strong>The real problem has never been the model, it’s the missing structure</strong></h3><p>Vibe coding builds in an undisciplined manner— no enforced business rules, no guardrails on what gets committed. The output reflects the chaos of the input.</p><blockquote>Most organizations limit AI to coding tasks, but the biggest gains can be achieved when it’s applied across the software development life cycle, starting from planning to design to implementation. This is precisely the problem spec-driven development and GitHub Speckit solve.</blockquote><blockquote><strong>Specs first. Code later.</strong></blockquote><p>You start with defining the <em>what and </em>the <em>why</em>, then step into the <em>how </em>in a way that’s machine-readable, version-controlled, and grounded in the actual system it’s meant to operate within.</p><h3>Why use spec-driven development when LLM is capable to generate code?</h3><p>LLMs can scan an entire repository, but reading code is not the same as understanding the context of the whole solution. Every repo has its own conventions, business rules, audit rules, security and compliance needs (not often part of the codebase). AI assistants may infer some of these patterns from your code but not the engineering standard fully. Enterprise codebases still carry outdated practices, and the model may multiply those patterns, which will eventually introduce a good number of tech debts and maintenance overhead.</p><p><strong><em>Spec-driven development redefines what autonomous AI can handle. LLM can write features within system boundary, audit and compliance rules and grounded to human-approved requirements, instead of isolated edits.</em></strong> Teams can spend more time upstream — reviewing product specs, finding gaps, defining architecture, weighing trade-offs. Code reviews can be focused on alignment with specs, instead of checking coding styles or cleaning up over-engineered slops. Testability of the product enhances with clear lock-in of functionalities.</p><h3>Introducing GitHub Speckit</h3><p><a href="https://github.com/github/spec-kit">GitHub Speckit</a> is an open-source toolkit that operationalizes this workflow through a specify CLI and a set of commands for your coding agent. Works across 30+ AI agents including Copilot, Claude Code, Cursor, Codex, Gemini, and more. Here are the steps to follow to use Speckit. Each steps produces versioned artifacts in markdown format.</p><p><strong>Step 0 — Install and initialize.</strong> Single command to scaffold your project and the specify commands: specify init my-project --integration copilot.</p><p><strong>Step 1 — Constitution (</strong><strong>/speckit.constitution).</strong> Start by establishing the project&#39;s governing principles around code quality, design patterns, LLD contracts, testing standards, design needs, architectural boundaries. This file lives in .specify/memory/constitution.md and every subsequent agent action references it.</p><p><strong>Step 2 — Specify (</strong><strong>/speckit.specify).</strong> Describe what you&#39;re building and why. Remember this is about the intent — not the technical implementation. Articulate your requirements clearly, describe the goal and functionalities of the product to achieve the goal. &quot;Build an application that helps organize photos into albums, grouped by date, with drag-and-drop reordering.&quot; The agent converts this into user stories and functional requirements, saved in a spec.md .</p><p><strong>Step 3 — Clarify (</strong><strong>/speckit.clarify).</strong> Determine the level of clarity and assumptions in the specs. Speckit runs structured, sequential questioning to catch underspecified requirements and documents each finding.</p><p><strong>Step 4 — Plan (</strong><strong>/speckit.plan).</strong> Now you introduce the tech stack. The agent maps your spec to an architecture, generating an implementation plan, data model, API contracts, and a research document.</p><p><strong>Step 5 — Tasks (</strong><strong>/speckit.tasks).</strong> The plan becomes an ordered, dependency-aware task list, which is the execution manifest for AI.</p><p><strong>Step 6 — Implement (</strong><strong>/speckit.implement).</strong> The agent executes the task list sequentially, validates prerequisites, respects dependencies, and provides progress updates. You&#39;re not crossing your fingers and hoping the output matches a prompt from three hours ago; you&#39;re watching a structured plan execute against a documented spec.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PBBxVWD4RRTlnAA51_2fxA.png" /></figure><p><strong><em>What I like most about using this toolkit is it makes you consolidate and write down the governing rules at one place. </em></strong>When a new collaborator joins, or when you return to a project 3 months later, the governing rules aren’t locked in someone’s head, it sits right in the repo.</p><p><strong><em>The traceability is equally valuable. A requirement stated in </em></strong><strong><em>/speckit.specify flows into a plan, next into a task, and lastly into a commit.</em></strong> You can walk that chain in either direction — look at a piece of code and ask what requirement it serves, or look at a requirement and ask exactly where it was implemented. That&#39;s something most engineering teams struggle to maintain even with dedicated process.</p><h3>Can SpecKit be applied in an enterprise setting?</h3><p>At first glance, above steps are very easy to execute for a solo or 2–3 person team. However, speckit maps naturally onto the roles that already exist in a well-functioning engineering organization. The steps just need to be owned by the right people.</p><h4><strong>Matching Steps to Personas</strong></h4><p><strong>Tech Lead / Architect → Steps 1 &amp; 4 (Constitution + Plan).</strong> The constitution belongs to the person accountable for the long-term health of the system. The software architect oversees functionality, performance, scalability, security, and tradeoffs, and ensures decisions are communicated to all stakeholders. /speckit.plan is exactly that: a technical translation of the spec into architecture decisions, API contracts, and a data model. This is senior engineering territory.</p><p><strong>Product Manager / Business Analyst → Steps 2 &amp; 3 (Specify + Clarify).</strong> The PM owns the <em>what</em> and the <em>why</em>. /speckit.specify produces a requirements document with user stories, functional scope, acceptance criteria with a focus on outcome. The /speckit.clarify pass that follows is a structured requirements review. These artifacts shouldn&#39;t be authored by an engineer who is also going to implement them.</p><p><strong>Engineering Team → Steps 5, 6 &amp; 7 (Tasks + Analyze + Implement).</strong> Once specs are locked and architecture is decided, engineers execute. /speckit.tasks and /speckit.implement operate within the constraints already established upstream.</p><p>This role separation matters for more than process tidiness. Enterprises should treat AI coding agents as first-class identities with scoped roles, human-gated approvals for high-risk changes, and audit-by-default so every action is attributable and reversible. Speckit’s versioned, Markdown-based artifacts maintains that audit trail.</p><p><strong><em>That said, not every enterprise team has cleanly separated roles, or the bandwidth to enforce them. </em></strong>In practice, a tech lead might run all the steps under deadline pressure. In such scenario, thorough reviews of the artifacts, especially <strong>constitution.md</strong> and <strong>spec.md</strong> along with explicit sign-offs from the PM, architect, or equivalent roles can ensure that intent isn’t siloed in one person’s head, that accountability is distributed across roles, and that the downstream steps have a verified foundation to build on.</p><blockquote>You don’t need perfect role separation to get the governance benefits. You need the right people to have read, challenged, debated and approved what was written before the implementation plan gets generated.</blockquote><h3>Can we implement Speckit in an existing enterprise-size codebase?</h3><p>Common misconception is that such process can be only be applied when a project is starting from scratch. <strong><em>However it’s never too late for applying right governance and spec-driven approach in any project. </em></strong>Brownfield adoption can be challenging because existing codebases contain undocumented architecture, legacy decisions, and established development practices. <strong><em>The primary objective is to bring the existing system into the SpecKit workflow without disrupting delivery.</em></strong></p><ol><li><strong>What should be written into the constitution? </strong>Analyze the current architecture, tech stack, coding conventions, design rationales, database interactions, 3rd party plugins, operational constraints and deployment processes. Reverse-engineer key system components into architectural documentation. Create an initial constitution that reflects these and the current engineering standards instead of generic ones. Add onto desired conventions incrementally.</li></ol><p><strong>2. Adopt SpecKit incrementally: </strong>Do not attempt to retrofit the entire codebase at once. Select one new feature to build, refactor, enhancement and run it through the SpecKit lifecycle.</p><p><strong>3. Establish review cycles: </strong>Validate assumptions with code analysis before generating plans or tasks. Review thoroughly at checkpoints or key stages.</p><p>4. <strong>Multi-repo projects: </strong>you don’t need to restructure your project or force a monolithic repo. Initialize Speckit per repo, but keep a shared constitution that governs cross-cutting concerns like API contracts, authentication, data models etc.</p><p><strong>Best practices</strong></p><ul><li>Start with low-risk enhancements or new features before tackling core legacy components.</li><li>Refer to existing design documents, ADRs, and production behavior to generate constitution.</li><li>Keep documentation synchronized with implementation.</li></ul><h3>How change management works in spec-driven development?</h3><p>Changes in functional requirements is not an one-off situation, it is expected.</p><ol><li>Every change request — a new feature, a scope adjustment, a business rule update — starts with amending the spec.md, not the code. This forces the team to articulate <em>what</em> is changing and <em>why</em> before downstream is updated. The diff in spec.md is similar to change log.</li><li>Because requirements trace to tasks and tasks trace to files, you can scope the blast radius of any change before writing a line. “If we change the auth model, what does that touch?” — the plan and task list tell you.</li><li>Architectural principles and coding standards in the constitution shouldn’t change per feature. If a proposed change conflicts with the constitution, that’s a flag — either the change needs rethinking, or the constitution needs a deliberate, reviewed update.</li><li>Just as with initial specs, change requests to spec.md should go through the same review and approval loop — PM signs off on scope updates, tech lead/architect signs off on plan changes, before engineers pick up new tasks.</li></ol><h4>Can spec-driven development slow you down?</h4><p>While adopting speckit in an existing project, the friction is expected to be front-loaded. However <strong><em>traditionally good software engineering has always been about good planning; few hours spent over brainstorming, thinking and shaping up the plan saves a lot of effort and miscommunications downstream.</em></strong></p><p>The teams feeling slowed down by Speckit are usually the ones who were previously skipping the thinking and paying for it later — they just didn’t see the cost because it was spread across debugging sessions, misaligned features, and re-reviews.</p><p><strong>Where the real speed comes from:</strong></p><ul><li><strong>Fewer revision cycles: </strong>agents execute against a verified plan.</li><li><strong>Less context-switching: </strong>engineers aren’t pulled back into “what did we decide about X?” conversations.</li><li><strong>Faster onboarding: </strong>new team members read the spec and constitution instead of reverse-engineering intent from code.</li><li><strong>Changes cost less: </strong>as impact is traceable, scope decisions are faster and more confident.</li></ul><h3>Conclusion</h3><blockquote>Gartner predicts that by 2028, teams that consistently apply an ensemble of AI-powered tools across the SDLC will achieve 25–30% productivity gains, up from the 10% delivered by code-generation-focused approaches in 2024.</blockquote><p>Spec-driven development doesn’t make AI faster — it makes AI <em>trustworthy </em>and <em>product iterations give results instead of guesswork</em>. It makes us think, synthesize and understand about what we’re building before getting into the code. The constitution eliminates rework from misaligned assumptions. The task list eliminates the back-and-forth that kills momentum. The audit trail eliminates the “who approved this?” conversations. Testability is increased as functional requirements are locked into clear acceptance criteria in the specs.</p><p>→ <strong>Start structured at </strong><a href="https://github.com/github/spec-kit"><strong>github.com/github/spec-kit</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83a4510b05f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[8 RAG architectures that AI Engineers must know in 2026]]></title>
            <link>https://medium.com/@satwikide/8-rag-architectures-that-ai-engineers-must-know-in-2026-39efc963604a?source=rss-d4bbc4d61092------2</link>
            <guid isPermaLink="false">https://medium.com/p/39efc963604a</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Satwiki De]]></dc:creator>
            <pubDate>Sat, 28 Mar 2026 20:41:46 GMT</pubDate>
            <atom:updated>2026-03-28T20:41:46.655Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical guide to various RAG patterns for production-level use cases</h4><p>Retrieval Augmented Generation (RAG) is a technique in GenAI apps, that enhances the LLM-generated answers by incorporating real-time and relevant data retrieval from public or private knowledge sources.</p><p>RAG soon became a popular choice for many AI-native application e.g. IT support chatbots, legal research, HR support, custom copilots etc., however it has evolved well past its original form now. As businesses look for ROI from AI-native apps and the level of complexity and need for accuracy also increase, a number of RAG architecture patterns have emerged in recent times to handle the needs.</p><p>There are many documented architectures, each designed to address a specific set of failure modes. The challenge isn’t knowing they exist. It’s knowing when to reach for which one, and understanding what tradeoff you’re accepting when you do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BXfDEf6V470SPepDbC7JZA.png" /><figcaption>RAG architecture principles for AI Engineers</figcaption></figure><h3>The baseline: Simple RAG and Naive RAG</h3><p>Before covering the more complex variants, it’s worth being precise about the baseline. Naive RAG is the simplest form. It converts a query into search terms, pulls the top matching documents, and hands them to the model with no filtering, reranking, or verification. There’s no quality control on what gets retrieved. For predictable, narrow use cases with limited scope like basic FAQ chatbot, it works. For anything else, retrieval quality degrades fast.</p><p>Simple RAG is a step up. It converts the user query into embeddings, searches a vector store for semantically similar content, retrieves the top results, and generates a response. The retrieval is still a single pass, but it’s semantically driven rather than keyword-matched. It’s the appropriate default for straightforward question-answering over a bounded knowledge base.</p><p>The problems both share:</p><ul><li><strong>No feedback loop</strong>. If retrieval is poor, the model generates from poor context, and there’s no mechanism to catch it.</li><li><strong>Shallow query understanding: </strong>Low accuracy for ambiguous queries.</li><li>Struggles with queries requiring<strong> data from multiple sources.</strong></li><li><strong>Does not improve</strong> if initial data retrieval is poor.</li></ul><h3>1. HyDE: When queries are vague or underspecified</h3><p><strong>HyDE (Hypothetical Document Embedding)</strong> inverts the standard retrieval flow. Rather than searching with the raw user query in the knowledge base, it generates a hypothetical document first, then uses that answer as the search vector to retrieve real documents.</p><p>The intuition is sound. User queries are often underspecified. A hypothetical answer is richer, more domain-appropriate, and closer in semantic space to the documents you want to retrieve. The search becomes a document-to-document similarity problem rather than a query-to-document one.</p><h4><strong>Use case:</strong></h4><p>HyDE is particularly effective in technical domains where users rarely phrase queries in the same language as the source material: legal research, medical literature, academic databases. The tradeoff is interpretability and the risk of a bad hypothetical leading retrieval in the wrong direction entirely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aCLzDr-KqZ9PVDMBIpQF1g.png" /></figure><h3>2. Self-RAG: When the model should question its own retrieval</h3><p>Self-RAG introduces a self-evaluation loop. After an initial retrieval and generation pass, the model uses specialized evaluation modules to assess whether the answer is accurate and grounded in the retrieved material. If it isn’t, it rewrites the query, retrieves again, and regenerates.</p><h4>Use case:</h4><p>queries that are incomplete, ambiguous, or where the first retrieval round is likely to miss relevant context. It’s a researcher who checks their own citations before publishing.</p><h4>Watch out for:</h4><p>The cost is latency and compute. The model is doing the work twice, sometimes more. And it can be overly conservative, refusing to answer when uncertain rather than providing a best-effort response. That behavior needs to be calibrated for your use case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A8tvGPYaXFCh9u4fYZ4oQQ.png" /></figure><h3>3. Corrective RAG: Grading context before it reaches the model</h3><p>Corrective RAG (CRAG) adds a grading step between retrieval and generation. Retrieved documents are broken down into smaller knowledge strips and each strip is scored for relevance against the original query. Strips that don’t meet the relevance threshold are filtered out. In case nothing clears the threshold, the system can initiate a secondary retrieval pass before proceeding to generation step. Once a satisfactory set of knowledge strips is obtained, the LLM generates the final response.</p><h4>Use case:</h4><p>This is the architecture for high-stakes domains like legal document generation, medical decision support, stock market analysis. The consequences of a hallucination or a corrupted context window are high enough that the extra latency of a grading loop is worth it.</p><h4>Watch out for:</h4><p>CRAG can get stuck in loops if the relevance threshold is calibrated too aggressively and no retrieval pass satisfies it. It’s necessary to enable observability in each step and assess the consistency of error correction to ensure optimal performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9DH6sKhc5B_MMJ4r46dMgw.png" /></figure><h3>4. Adaptive RAG: Routing by query complexity</h3><p>Adaptive RAG classifies the incoming query before deciding how to retrieve. Simple queries get routed to a single-source retrieval path. Complex ones get multi-source retrieval or employs more sophisticated retrieval techniques like algorithm selection, re-ranker. The routing can also adjust generation style based on query type.</p><p>The value here is cost efficiency by enhancing simple RAG. You stop paying Agentic-level compute for a question Simple RAG can handle in one step.</p><h4>Use case:</h4><p>Systems that handle a wide variance in query complexity such as customer support bots, enterprise search tools, general-purpose research assistants etc. can benefit the most from this pattern.</p><h4>Watch out for:</h4><p>The downside is that classification adds its own latency and can still overuse compute if the input query is too ambiguous and classifier chooses multiple sources which are not all relevant. Early-stage adaptive systems produce inconsistent results until the classifier get refined further to route reliably.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aFVK3rzFTKWvb1ez9_t_OA.png" /></figure><h3>5. Branched RAG: Selecting the right source, not merging all of them</h3><p>Branched RAG evaluates which data source(s) are most relevant before retrieving anything. Instead of consolidating across all available sources, it selects the most appropriate one and retrieves from that.</p><h4>Use case:</h4><p>This is underused in enterprise environments where teams run multiple domain-specific indexes in parallel. Legal, financial, product, and HR knowledge bases don’t need to be queried simultaneously for every request. Branched RAG routes to the right one.</p><h4>Watch out for:</h4><p>The architectural challenge is coordination — when a query genuinely spans multiple sources, you need to decide whether to merge results or handle it as a multi-branch problem. It is possible to be achieved in the Generation step by prompt tuning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1JWaA1dvUzAda84WJiYH4w.png" /></figure><h3>6. Agentic RAG: Multi-step reasoning over complex tasks</h3><p>Agentic RAG introduces a meta-agent that coordinates multiple document-level agents. Each document agent handles a specific source, capable of answering questions and summarizing content from that document independently. The meta-agent orchestrates their interactions and synthesizes a final response.</p><h4><strong>Use case:</strong></h4><p>This architecture is for tasks where the query itself requires a research process: automated multi-source analysis, legal case synthesis, executive decision support. This RAG system is doing more than just retrieving and generating; it’s planning what to investigate, executing that plan, verifies the results and lastly combines the results to generate the most relevant answer.</p><h4>Watch out for:</h4><p>Even though accuracy and coverage on genuinely complex queries improve, latency may go up significantly. The key trade-off is to determine whether Agentic RAG can be useful to the complexity of your use case. Agentic RAG applied to simple queries can be an expensive overhead, not a quality improvement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0kSr7p1biFb9kF4CmHcNOg.png" /></figure><h3>7. Graph RAG: When entity relationships matter more than documents</h3><p>Graph RAG uses a knowledge graph to map how entities in your knowledge base are connected. Rather than searching for semantic similarity to the query, it traverses relationships between concepts to surface relevant information. Particularly even when the relevant document may not contain the query terms at all.</p><h4>Use case:</h4><p>Standard vector search answers “what is semantically close to this query.” Graph RAG answers “what is connected to this entity, and how.” For recommendation systems, fraud detection, medical research, investigative use cases, or any domain where the relationship between pieces of information is the actual answer, this is the right architecture.</p><h4>Watch out for:</h4><p>Building and maintaining a quality knowledge graph is significant work, and the system is only as good as the connections you’ve defined. Graph RAG can also be super slow and not efficient for on-demand conversational scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b0lnNQFi9fO317L-_xkqQw.png" /></figure><h3>8. Modular RAG: Better scaffolding and flexibility</h3><p>Modular RAG decouples the pipeline into independent components: retriever, re-ranker, generator, memory, evaluation. The flexibility of this architecture is that each component can be swapped or upgraded without rebuilding the entire system.</p><h4><strong>Use case:</strong></h4><p>Content research with real-time data, systems with multi-modal data sources, recommendation system etc. can benefit modular RAG. An enterprise-level production platform that aims to handle many AI use cases can also end up using modular RAG architecture, offering the adaptability needed for quick iteration and releases.</p><h4><strong>Watch out for:</strong></h4><p>The system (from coding to deployment) needs to be planned extensively before implementation. It can get complex to orchestrate and select different components in this architecture. Another common challenge is integrating diverse data sources into a single ecosystem.</p><p><em>Thank you for reading and engaging with this content. Follow me if you want to read more such content about new and exciting technology. If you have any feedback, please leave a comment. Thanks :)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39efc963604a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Did I Learn from Building LLM Applications in 2024? — Part 2]]></title>
            <link>https://medium.com/data-science/what-did-i-learn-from-building-llm-applications-in-2024-part-2-86433ef437a7?source=rss-d4bbc4d61092------2</link>
            <guid isPermaLink="false">https://medium.com/p/86433ef437a7</guid>
            <category><![CDATA[notes-from-industry]]></category>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <dc:creator><![CDATA[Satwiki De]]></dc:creator>
            <pubDate>Fri, 17 Jan 2025 11:02:03 GMT</pubDate>
            <atom:updated>2025-01-17T11:02:03.042Z</atom:updated>
            <content:encoded><![CDATA[<h3>What Did I Learn from Building LLM Applications in 2024? — Part 2</h3><h4>An engineer’s journey to building LLM-powered applications</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KvzZOmS6bfhVZRhoPuSrPA.jpeg" /><figcaption>Illustration of building AI application (image by author — generated using DALLE-3)</figcaption></figure><p><a href="https://towardsdatascience.com/what-did-i-learn-from-building-llm-applications-in-2024-part-1-d299b638773b">In part 1 of this series</a>, we discussed use case selection, building a team and the importance of creating a prototype early into your LLM-based product development journey. Let’s pick it up from there — if you are fairly satisfied with your prototype and ready to move forward, start with planning a development approach. It’s also crucial to decide on your productionizing strategy from an early phase.</p><p>With recent advancements with new models and a handful of SDKs in market, it is easy to feel the urge to build <em>cool</em> features such as agents into your LLM-powered application in the early phase. Let’s take a step back and decide the <strong><em>must-have and nice-to-have features </em></strong>as per your use case. Begin by identifying the core functionalities that are essential for your application to fulfill the primary business objectives. For instance, if your application is designed to provide customer support, the ability to understand and respond to user queries accurately would be a must-have feature. On the other hand, features like personalized recommendations might be considered as a nice-to-have feature for future scope.</p><h4>Find your ‘fit’</h4><p>If you want to build your solution from a concept or prototype, a top-down design model can work best. In this approach, you start with a high level conceptual design of the application without going into much details, and then take separate components to develop each further. This design might not yield the best results at very first, but sets you up for an iterative approach, where you can improve and evaluate each component of the app and test the end-to-end solution in subsequent iterations.</p><p>For an example of this design approach, we can consider a RAG (Retrieval Augmented Generation) based application. These applications typically have 2 high-level components —<em> a retrieval component (which searches and retrieves relevant documents for user query)</em> and <em>a generative component (which produces a grounded answer from the retrieved documents)</em>.</p><p><strong>Scenario: </strong>Build a helpful assistant bot to diagnose and resolve technical issues by offering relevant solutions from a technical knowledge base containing troubleshooting guidelines.</p><p><strong>STEP 1 - build the conceptual prototype:</strong> Outline the overall architecture of the bot without going into much details.</p><ul><li><strong>Data Collection:</strong> Gather a sample dataset from the knowledge base, with questions and answers relevant to your domain.</li><li><strong>Retrieval Component:</strong> Implement a basic retrieval system using a simple keyword-based search, which can evolve into a more advanced <strong><em>vector-based search</em></strong> in future iterations.</li><li><strong>Generative Component:</strong> Integrate an LLM in this component and feed the retrieval results through prompt to generate a grounded and contextual answer.</li><li><strong>Integration:</strong> Combine the retrieval and generative components to create a end-to-end flow.</li><li><strong>Execution: </strong>Identify the resources to run each component. For example, retrieval component can be built using Azure AI search, it offers both keyword-based and advanced vector-based retrieval mechanisms. LLMs from Azure AI foundry can be used for generation component. Lastly, create an app to integrate these components.</li></ul><figure><img alt="Experimental approach: iteration 1 (Image by author)" src="https://cdn-images-1.medium.com/max/1024/1*EjBHrT8ysLYLzf2pcY8gpQ.png" /><figcaption>Step 1 (image by author)</figcaption></figure><p><strong>STEP 2 - Improve Retrieval Component: </strong>Start exploring how each component can be improved more. <strong><em>For a RAG-based solution, the quality of retrieval has to be exceptionally good to ensure that the most relevant and accurate information is retrieved, which in turn enables the generation component to produce contextually appropriate response for the end user.</em></strong></p><ul><li><strong>Set up data ingestion:</strong> Set up a data pipeline to ingest the knowledge base into your retrieval component. This step should also consider preprocessing the data to remove noise, extract key information, image processing etc.</li><li><strong>Use vector database: </strong>Upgrade to a vector database to enhance the system for more contextual retrieval. Pre-process the data further by splitting text into chunks and generating embeddings for each chunk using an embedding model. The vector database should have functionalities for adding and deleting data and querying with vectors for easy integration.</li><li><strong>Evaluation:</strong> Selection and rank of documents in retrieval results is crucial, as it impacts the next step of the solution heavily. While precision and recall gives a fairly good idea of the search results’ accuracy, you can also consider using <strong><em>MRR (mean reciprocal rank) or NDCG (normalized discounted cumulative gain)</em></strong> to assess the ranking of the documents in the retrieval results. <strong><em>Contextual relevancy</em></strong> determines whether the document chunks are relevant to producing the ideal answer for a user input.</li></ul><figure><img alt="Iteration 2 (image by author)" src="https://cdn-images-1.medium.com/max/1024/1*-FGsWff5faAV257znXDXOA.png" /><figcaption>Step 2 (image by author)</figcaption></figure><p><strong>STEP 3 — Enhance Generative Component to produce more relevant and better output:</strong></p><ul><li><strong>Intent filter:</strong> Filter out questions that don’t fall into the scope of your knowledge base. This step can also be used to block unwanted and offensive prompts.</li><li><strong>Modify prompt and context: </strong>Improve your prompts e.g. including few shot examples, clear instructions, response structure, etc. to tune the LLM output as per your need. Also feed conversation history to the LLM in each turn to maintain context for a user chat session. If you want the model to invoke tools or functions, then put clear instructions and annotations in the prompt. <strong><em>Apply version control on prompts</em></strong> in each iteration of experiment phase for change tracking. This also helps to roll back in case your system’s behavior degrades after a release.</li><li><strong>Capture the reasoning of the model: </strong>Some applications use an additional step to capture the rationale behind output generated by LLMs. This is useful for inspection when the model produces unpredictable output.</li><li><strong>Evaluation: </strong>For the answers produced by a RAG-based system, it is important to measure a) the <strong><em>factual consistency</em></strong> of the answer against the context provided by retrieval component and b) <strong><em>how relevant the answer is to the query</em></strong>. During the MVP phase, we usually test with few inputs. However while developing for production, we should carry out evaluation against an extensive <strong><em>ground truth or golden </em>dataset</strong> created from the knowledge base in each step of the experiment. It’s better if the ground truth can contain as much as possible real-world examples (frequent questions from the target consumers of the system). If you’re looking to implement evaluation framework, take a look <a href="https://gist.github.com/hshujuan/4ed8e76a3dc082075a4d97a11ed3bf20#file-chapter2_table10-md">here</a>.</li></ul><figure><img alt="Iteration 3 (image by author)" src="https://cdn-images-1.medium.com/max/1024/1*bqC0_D_p8abbh5xRoOOQAQ.png" /><figcaption>Step 3 (image by author)</figcaption></figure><p><strong>On the other hand, </strong>let’s consider another scenario where you’re integrating AI in a business process. <strong>Consider an online retail company’s call center transcripts, for which summarization and sentiment analysis are needed to be generated and added into a weekly report.</strong> To develop this, start with understanding the existing system and the gap AI is trying to fill. Next, start designing low-level components keeping system integration in mind. This can be considered as <strong>bottom-up design </strong>as each component can be developed separately and then be integrated into the final system.</p><ul><li><strong>Data collection and pre-processing: </strong>Considering confidentiality and the presence of personal data in the transcripts, redact or anonymize the data as needed. Use a speech-to-text model to convert audio into text.</li><li><strong>Summarization: </strong>Experiment and choose between extractive summarization (selecting key sentences) and abstractive summarization (new sentences that convey the same meaning) as per the final report’s need. Start with a simple prompt, and take user feedback to improve the accuracy and relevance of generated summary further.</li><li><strong>Sentiment analysis: </strong>Use domain-specific few shots examples and prompt tuning to increase accuracy in detecting sentiment from transcripts. Instructing LLM to provide reasoning can help to enhance the output quality.</li><li><strong>Report generation:</strong> Use report tool like Power BI to integrate the output from previous components together.</li><li><strong>Evaluation: </strong>Use the same concepts of iterative evaluation process with metrics for LLM-dependent components.</li></ul><p>This design also helps to catch issues early on in each component-level which can be addressed without changing the overall design. Also enables AI-driven innovation in existing legacy systems.</p><blockquote>LLM application development doesn’t follow a one-size-fits-all approach. Most of the time it is necessary to gain a quick win to validate whether the current approach is bringing value or shows potential to meet expectations. While building a new AI-native system from scratch sounds more promising for the future, on the other hand integrating AI in existing business processes even in a small capacity can bring a lot of efficiency. Choosing either of these depends upon your organization’s resources, readiness to adopt AI and long-term vision. It is imperative to consider the trade-offs and create a realistic strategy to generate long-term value in this area.</blockquote><h4>Ensuring quality through an automated evaluation process</h4><p>Improving the success factor of LLM-based application lies with iterative process of evaluating the outcome from the application. This process usually starts from choosing relevant metrics for your use case and gathering real-world examples for a <em>ground truth or golden </em>dataset. As your application will grow from MVP to product, it is recommended to come up with a <strong><em>CI/CE/CD (Continuous Integration/Continuous Evaluation/Continuous Deployment)</em></strong> process to standardize and automate the evaluation process and calculating metrics scores. This automation has also been called <strong>LLMOps</strong> in recent times, derived from MLOps. Tools like PromptFlow, Vertex AI Studio, Langsmith, etc. provide the platform and SDKs for automating evaluation process.</p><p><strong>Evaluating LLMs and LLM-based applications is <em>not</em> the same</strong></p><p>Usually an LLM is put through a standard benchmarks evaluation before it is released. However that does not guarantee your LLM-powered application will always perform as expected. Especially a RAG-based system which uses document retrievals and prompt engineering steps to generate output, should be evaluated against a <strong><em>domain-specific, real-world dataset</em></strong> to gauge the performance.</p><p>For in-depth exploration on evaluation metrics for various type of use cases, I recommend this <a href="https://medium.com/data-science-at-microsoft/evaluating-llm-systems-metrics-challenges-and-best-practices-664ac25be7e5">article</a>.</p><h4>How to choose the right LLM?</h4><figure><img alt="Comparing parameters to choose a LLM (image by author — generated using DALLE-3)" src="https://cdn-images-1.medium.com/max/1024/1*Y_Kp6-ahh02txiYJE-pfxQ.jpeg" /><figcaption>Image by author — generated using DALLE-3</figcaption></figure><p>Several factors drive this decision for a product team.</p><ol><li><strong>Model capability:</strong> Determine your model need by the type of problem you’re solving in your LLM product. For example, consider these 2 use cases —</li></ol><p><strong>#1</strong> A chatbot for an online retail shop handles product enquiries through text and images. A model with multi-modal capabilities and lower latency should be able to handle the workload.</p><p><strong>#2</strong> On the other hand, consider a developer productivity solution, which will need a model to generate and debug code snippets, you require a model with advanced reasoning that can produce highly accurate output.</p><p><strong>2. Cost and licensing: </strong>Prices vary based on several factors such as model complexity, input size, input type, and latency requirements. Popular LLMs like OpenAI’s models charge a fixed cost per 1M or 1K tokens, which can scale significantly with usage. Models with advanced logical reasoning capability usually cost more, such as OpenAI’s o1 model $15.00 / 1M input tokens compared to GPT-4o which costs $2.50 / 1M input tokens. Additionally, if you want to sell your LLM product, make sure to check the commercial licensing terms of the LLM. Some models may have restrictions or require specific licenses for commercial use.</p><p><strong>3. Context Window Length:</strong> This becomes crucial for use cases where the model needs to process a large amount of data in prompt at once. The data can be document extracts, conversation history, function call results etc.</p><p><strong>4. Speed: </strong>Use cases like chatbot for online retail shop needs to generate output very fast, hence a model with lower latency is crucial in this scenario. Also, UX improvement e.g. streaming responses renders the output chunk by chunk, thus providing a better experience for the user.</p><p><strong>6. Integration with existing system: </strong>Ensure that the LLM provider can be seamlessly integrated with your existing systems. This includes compatibility with APIs, SDKs, and other tools you are using.</p><blockquote>Choosing a model for production often involves balancing trade-offs. It’s important to experiment with different models early in the development cycle and set not only use-case specific evaluation metrics, also performance and cost as benchmarks for comparison.</blockquote><h4>Responsible AI</h4><p>The ethical use of LLMs is crucial to ensure that these technologies benefit society while minimizing potential harm. A product team must prioritize <strong><em>transparency, fairness, and accountability</em></strong> in their LLM application.</p><p><strong>For example</strong>, consider a LLM-based system being used in healthcare facilities to help doctor diagnose and treat patients more efficiently. The system must not misuse patient’s personal data e.g. medical history, symptoms etc. Also the results from the applications should have transparency and reasoning behind any suggestion it generates. It should not be biased or discriminatory towards any group of people.</p><p>While evaluating the LLM-driven component output quality in each iteration, make sure to look out for any potential risk such as harmful content, biases, hate speech etc.t. <strong>Red teaming</strong>, a concept from cybersecurity, has recently emerged as a best practice to uncover any risk and vulnerabilities. During this exercise, red teamers attempt to ‘trick’ the models generate harmful or unwanted content by means of using various strategies of prompting. This is followed by both automated and manual review of flagged outputs to decide upon a mitigation strategy. As your product evolves, in each stage you can instruct red teamers to test different LLM-driven components of your app and also the entire application as a whole to make sure every aspect is covered.</p><h4><strong>Make it all ready for Production</strong></h4><p>At the end, LLM application is a product and we can use common principles for optimizing it further before deploying to production environment.</p><ol><li><strong>Logging and monitoring</strong> will help you capture token usage, latency, any issue from LLM provider side, application performance etc. You can check for usage trends of your product, which provides insights into the LLM product’s effectiveness, usage spikes and cost management. Additionally, setting up alerts for unusual spikes in usage can prevent budget overruns. By analyzing usage patterns and recurring cost, you can scale your infrastructure and change or update model quota accordingly.</li><li><strong>Caching</strong> can store LLM outputs, reducing the token usage and eventually the cost. Caching also helps with consistency in generative output, and reduces latency for user-facing applications. However, since LLM applications do not have a specific set of inputs, cache storage can increase exponentially in some scenarios, such as chatbots, where each user input might need to be cached, even if the expected answer is same. This can lead to significant storage overhead. To address this, the concept of semantic caching has been introduced. <strong><em>In Semantic caching, similar prompt inputs are grouped together based on their meaning using an embedding model</em></strong>. This approach helps in managing the cache storage more efficiently.</li><li><strong>Collecting user feedback</strong> ensures that the AI-enabled application can serve its purpose in a better way. If possible, try to gather feedback from a set of pilot users in each iteration so that you can gauge if the product is meeting expectations and which areas require further improvements. For example, an LLM-powered chatbot can be updated to support additional languages and as a result attract more diverse users. With new capabilities of LLMs being released very frequently, there’s a lot of potential to improve the capabilities and add new features quickly.</li></ol><h4>Conclusion</h4><p>Good luck with your journey in building LLM-powered apps! There are numerous advancements and endless potentials in this field. Organizations are adopting generative AI with a wide array of use cases. <strong><em>Similar to any other product, develop your AI-enabled application keeping the business objectives in mind. For products like chatbots, end user satisfaction is everything. </em></strong>Embrace the challenges, today if a particular scenario doesn’t work out, don’t give up, tomorrow it can work out with a different approach or a new model. <strong><em>Learning and staying up-to-date with AI advancements are the key to building effective AI-powered products.</em></strong></p><p><em>Follow me if you want to read more such content about new and exciting technology. If you have any feedback, please leave a comment. Thanks :)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86433ef437a7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/what-did-i-learn-from-building-llm-applications-in-2024-part-2-86433ef437a7">What Did I Learn from Building LLM Applications in 2024? — Part 2</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Did I Learn from Building LLM Applications in 2024? — Part 1]]></title>
            <link>https://medium.com/data-science/what-did-i-learn-from-building-llm-applications-in-2024-part-1-d299b638773b?source=rss-d4bbc4d61092------2</link>
            <guid isPermaLink="false">https://medium.com/p/d299b638773b</guid>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[gpt]]></category>
            <dc:creator><![CDATA[Satwiki De]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 17:29:34 GMT</pubDate>
            <atom:updated>2024-11-09T01:05:10.338Z</atom:updated>
            <content:encoded><![CDATA[<h3>What Did I Learn from Building LLM Applications in 2024? — Part 1</h3><h4>An engineer’s journey to building LLM-native applications</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oEXNPL3qOT_XHdJnDUJDcQ.jpeg" /></figure><p>Large Language Models (LLMs) are poised to transform the way we approach AI and it is already being quite noticeable with innovative designs of integrating LLMs with web applications. Since late 2022, multiple frameworks, SDKs and tools have been introduced to demonstrate the integration of LLMs with web applications or business tools in format of simple prototypes. With significant investments flowing into creating Generative AI-based applications and tools for business use, it is becoming essential to bring these prototypes to production stage and derive business value. If you’ve set out to spend your time and money in building an LLM-native tool, how do you make sure that the investment will pay off in long-term?</p><p>In order to achieve this, it is crucial to establish a set of best practices for developing LLM applications. My journey in developing LLM applications in the past year has been incredibly exciting and full of learning. With nearly a decade of experience in designing and building web and cloud-native applications, I’ve realized that traditional product development norms often fall short for LLM-native applications. Instead, a continuous cycle of research, experimentation, and evaluation proves to be far more effective in creating superior AI-driven products.</p><p>In order to help you navigate the challenges of LLM applications development, I will talk about best practices in the following key focus areas — <em>use case selection, team mindset, development approach, responsible AI and cost management</em>.</p><h3>Ideation: Choosing the right use case</h3><p>Does every problem require AI for solution? The answer is a hard ‘no’. Rather ask yourself that which business scenario can benefit most from leveraging LLMs? The businesses need to ask these questions before setting out to build an app. Sometimes, the right use case is right in front of us, other times talking to your co-workers or researching within your organization can point you to the right direction. Here are few aspects that might help you to decide.</p><ol><li><strong>Does the proposed solution has a market need?</strong> Conduct a market research for the proposed use case to understand the current landscape. Identify any existing solution with or without AI integration, their pros and cons, and any flaws that your proposed LLM application could fill. This involves analyzing competitors, industry trends, and customer feedback.</li><li><strong>Does it help the users?</strong> If your proposed solution aims to serve users within your organization, a common measure of user expectations is to check if the solution can enhance their productivity by saving time. A common example is IT or HR support chatbot to help employees with day-to-day queries about their organization. Additionally, conducting a short survey with potential users can also help to understand the pain points that can be addressed with AI.</li><li><strong>Does it accelerate business processes?</strong> Another type of use cases might be addressing business process improvement, indirectly impacting users. Examples include sentiment analysis of call center transcripts, generating personalized recommendations, summarizing legal and financial documents etc. For this type of use cases, implementing automation can become a key factor to integrate LLM in a regular business process.</li><li><strong>Do we have the data available?</strong> Most LLM-native applications use RAG(Retrieval Augmented Generation) principle to generate contextual and grounded answer from specific knowledge documents. The root of any RAG based solution is the availability, type and quality of the data. If you do not have adequate knowledge base, or good quality data, the end result from your solution might not be up to the mark. Accessibility of the data is also important, as confidential or sensitive data might not always be available at your hand.</li><li><strong>Is the proposed solution feasible?</strong> Determining whether to implement the AI solution depends not only on the technical feasibility, but also on the ethical, legal and financial aspects. If sensitive data is involved, then privacy and regulatory compliance should also be taken into consideration before finalizing the use case.</li><li><strong>Does the solution meet your business requirements?</strong> Think about the short-term and long-term business goals that your AI solution can serve. Managing expectations is also crucial here, since being too ambitious with short-term goals might not help with value realization. Reaping the benefits from AI applications is usually a long-term process.</li></ol><h4>Setting right expectations</h4><p>Along with choosing the use case, the product owner should also think about setting the right expectations and short, attainable milestones for the team. Each milestones should have clear goals and timeline defined and agreed upon by the team, so that stakeholders can review the outcome in a periodic manner. This is also crucial to make informed decision on how to move forward with the proposed LLM-based solution, productionizing strategy, onboarding users etc.</p><h3>Experimentation: Adopting the right ‘mindset’</h3><p>Research and experiments are at the heart of any exercise that involves AI. Building LLM applications is no different. Unlike traditional web apps that follow a pre-decided design that has little to no variation, AI-based designs rely heavily on the experiments and can change depending on early outcomes. The success factor is experimenting on clearly defined expectations in iterations, followed by continuously evaluating each iteration. In LLM-native development, the success criteria is usually the quality of the output, which means that the focus is on producing accurate and highly relevant results. This can be either a response from chatbot, text summary, image generation or even an action (Agentic approach) defined by LLM. Generating quality results consistently requires a deep understanding of the underlying language models, constant fine-tuning of the prompts, and rigorous evaluation to ensure that the application meets the desired standards.</p><h4>What kind of tech skill set do you need in the team?</h4><p>You might assume that a team with only a handful of data scientists is sufficient to build you an LLM application. But in reality, engineering skills are equally or more important to actually ‘deliver’ the target product, as LLM applications do not follow the classical ML approach. For both data scientists and software engineers, some mindset shifts are required to get familiar with the development approach. I have seen both roles making this journey, such as data scientists getting familiar with cloud infrastructure and application deployment and on the other hand, engineers familiarizing themselves with the intricacies of model usage and evaluation of LLM outputs. Ultimately, you need <em>AI practitioners</em> in team who are not there just to ‘code’, rather research, collaborate and improve on the AI applicability.</p><h4>Do I really need to ‘experiment’ since we are going to use pre-trained language models?</h4><p>Popular LLMs like GPT-4o are already trained on large set of data and capable of recognizing and generating texts, images etc., hence you do not need to ‘train’ these types of model. Very few scenarios might require to fine-tune the model but that is also achievable easily without needing classical ML approach. However, let’s not confuse the term ‘experiment’ with ‘model training’ methodology used in predictive ML. As I’ve mentioned above that quality of the application output matters. setting up iterations of experiments can help us to reach the target quality of result. For example — if you’re building a chatbot and you want to control how the bot output should look like to end user, an iterative and experimental approach on prompt improvement and fine-tuning hyper parameters will help you find the right way to generate most accurate and consistent output.</p><h4>Build a prototype early in your journey</h4><p>Build a prototype (also referred to as MVP — minimum viable product) with only the core functionalities as early as possible, ideally within 2–4 weeks. If you’re using a knowledge base for RAG approach, use a subset of data to avoid extensive data pre-processing.</p><ul><li>Gaining quick feedback from a subset of target users helps you to understand whether the solution is meeting their expectations.</li><li>Review with stakeholders to not only show the good results, also discuss the limitations and constraints your team found out during prototype building. This is crucial to mitigate risks early, and also to make informed decision regarding delivery.</li><li>The team can finalize the tech stack, security and scalability requirements to move the prototype to fully functional product and delivery timeline.</li></ul><h4>Determine if your prototype is ready for building into the ‘product’</h4><p>Availability of multiple AI-focused samples have made it super easy to create a prototype, and initial testing of such prototypes usually delivers promising results. By the time the prototype is ready, the team might have more understanding on success criteria, market research, target user base, platform requirements etc. At this point, considering following questions can help to decide the direction to which the product can move:</p><ol><li>Does the functionalities developed in the prototype serve the primary need of the end users or business process?</li><li>What are the challenges that team faced during prototype development that might come up in production journey? Are there any methods to mitigate these risks?</li><li>Does the prototype pose any risk with regards to responsible AI principles? If so, then what guardrails can be implemented to avoid these risks? (<em>We’ll discuss more on this point in part 2</em>)</li><li>If the solution is to be integrated into an existing product, what might be a show-stopper for that?</li><li>If the solution handles sensitive data, are effective measures been taken to handle the data privacy and security?</li><li>Do you need to define any performance requirement for the product? Is the prototype results promising in this aspect or can be improved further?</li><li>What are the security requirements does your product need?</li><li>Does your product need any UI? (A common LLM-based use case is chatbot, hence UI requirements are necessary to be defined as early as possible)</li><li>Do you have a cost estimate for the LLM usage from your MVP? How does it look like considering the estimated scale of usage in production and your budget?</li></ol><p>If you can gain satisfactory answers to most of the questions after initial review, coupled with good results from your prototype, then you can move forward with the product development.</p><p>Stay tuned for part 2 where I will talk about <strong><em>what should be your approach to product development, how you can implement responsible AI early into the product and cost management techniques.</em></strong></p><p><em>Please follow me if you want to read more such content about new and exciting technology. If you have any feedback, please leave a comment. Thanks :)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d299b638773b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/what-did-i-learn-from-building-llm-applications-in-2024-part-1-d299b638773b">What Did I Learn from Building LLM Applications in 2024? — Part 1</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Chatbot in minutes with Chainlit, GPT-4 and LangChain]]></title>
            <link>https://medium.com/@satwikide/build-a-chatbot-in-minutes-with-chainlit-gpt-4-and-langchain-7690968578f0?source=rss-d4bbc4d61092------2</link>
            <guid isPermaLink="false">https://medium.com/p/7690968578f0</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[chainlit]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Satwiki De]]></dc:creator>
            <pubDate>Thu, 30 Nov 2023 18:06:24 GMT</pubDate>
            <atom:updated>2023-11-30T18:06:24.630Z</atom:updated>
            <content:encoded><![CDATA[<h4>Code-based samples of Chainlit apps powered by GPT-4 and LangChain</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pJgjXjr0SInGkt97j-WD7w.jpeg" /><figcaption>Image by author (generated using DALL-E 3)</figcaption></figure><p>With the Generative AI storm taking over the world, the requirements for AI-infused applications have increased exponentially. Chatbots being most common of these type of apps, are now expected to be able to handle more complex and diverse tasks. Apart from answering questions, chatbots are moving towards more intelligent, user-centric tasks like engaging in meaningful conversations, using user’s own data to create more nuanced content etc. To meet these demands, chatbots need to be equipped with advanced natural language processing and generation capabilities which can be provided by language models like GPT-4, as well as a rich and up-to-date knowledge base. And not to forget, a slick and easily-navigable UI too!</p><p>If you’re a python developer and wondering if you need to learn another technology to create your own chatbot UI, then <a href="https://docs.chainlit.io/get-started/overview"><em>Chainlit</em></a> comes to your rescue. It’s an open-source python library which also comes with built-in integrations with popular frameworks like LangChain.</p><p>In this article, I will show you how to create the quickest Chatbot app using Chainlit. For the LLM, I use <a href="https://azure.microsoft.com/en-us/blog/introducing-gpt4-in-azure-openai-service/">GPT-4 from Azure OpenAI</a>, which is capable for understanding user’s ask and frame the answer using user’s provided knowledge base. GPT-4 is a large multi-modal model developed by OpenAI, which can generate coherent, high-quality text output from a text or image input.</p><blockquote>Note: There’s no specific need to use GPT-4 to build a Chatbot app using Chainlit. You can use any other LLM as per your need. Choosing the right LLM depends on multiple factors e.g. use case complexity, which data the model was trained with, context length etc. and definitely cost of usage. Since we’re building a chatbot, the basic need is to choose an LLM with conversational capability.</blockquote><h3>Requirements</h3><ol><li>Python ≥ 3.8</li><li>Azure subscription with access to an Azure OpenAI instance</li><li>Create a deployment for GPT-4, or other chat model</li><li>Create a deployment for text-embedding-ada-002 (this will be needed for creating embeddings)</li><li>What else? An IDE maybe!</li></ol><h3>Setup</h3><p>Open your local folder and install following libraries from requirements.txt</p><pre>langchain==0.0.312<br>chainlit==0.7.2<br>python-dotenv==1.0.0</pre><pre>pip install -r requirements.txt</pre><p>Create a .env file in your root directory</p><pre>OPENAI_API_TYPE=&quot;azure&quot;<br>OPENAI_API_VERSION=&quot;2023-10-01-preview&quot;<br>OPENAI_API_BASE=<br>OPENAI_API_KEY=<br>OPENAI_CHAT_MODEL=<br>OPENAI_EMBEDDING_MODEL=</pre><h4>Demo 1: Basic chatbot</h4><p>Let’s create a simple chatbot which answers questions on astronomy.</p><p>Create a app_basic.py script which will have our <em>chainlit</em> and <em>langchain</em> code to build up the Chatbot UI. We use the following functionalities from LangChain —</p><ul><li>Prompt template: A prompt can be more than your input to the LLM, it can also contain instructions and specific constraints for the LLM to set the tone of the output. LangChain’s Prompt template functionality lets you craft structured prompts specific to your use case and chat format.</li><li>LLM chain: Chain acts as a wrapper around your LLM instance.</li></ul><pre>import os<br>from langchain.prompts import ChatPromptTemplate<br>from langchain.chains import LLMChain<br>from langchain.chat_models import AzureChatOpenAI<br>import chainlit as cl<br>from dotenv import load_dotenv<br><br># Load environment variables<br>load_dotenv(&#39;.env&#39;)<br><br>prompt_template = ChatPromptTemplate.from_messages(<br>    [<br>    (&quot;system&quot;, <br>    &quot;&quot;&quot;<br>    You are a friendly assistant that answers user&#39;s question about astronomy.<br>    If the user&#39;s question is not about these topics, <br>    respond with &quot;Uh-oh! I do not have the information to answer your question. Ask me about Space, Planets and Stars!&quot;.<br>    &quot;&quot;&quot;<br>    ),<br>    (&quot;user&quot;, &quot;{question}\n&quot;),<br>    ]<br>)<br><br>@cl.on_chat_start<br>def main():<br>    # Instantiate required classes for the user session<br>    llm_chat = AzureChatOpenAI(<br>            deployment_name=os.getenv(&quot;OPENAI_CHAT_MODEL&quot;),<br>            temperature=0.0,<br>            max_tokens=100<br>    )<br>    llm_chain = LLMChain(prompt=prompt_template, llm=llm_chat, verbose=True)<br><br>    # Store the chain in the user session for reusability<br>    cl.user_session.set(&quot;llm_chain&quot;, llm_chain)<br><br><br>@cl.on_message<br>async def main(message: str):<br>    # Retrieve the chain from the user session<br>    llm_chain = cl.user_session.get(&quot;llm_chain&quot;)<br>    # Call the chain asynchronously<br>    res = await llm_chain.acall(message, callbacks=[cl.AsyncLangchainCallbackHandler()])<br>    await cl.Message(content=res[&quot;text&quot;]).send()</pre><p>Run the script now. -w flag indicates auto-reloading, which makes it easy to update and debug the app without restarting the server.</p><pre>chainlit run app_basic.py -w </pre><blockquote>You will notice a chainlit.md file auto-created in your root folder, this can be edited to update the welcome screen message.</blockquote><p>Welcome screen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iZKX7ly2Y6TrwK2qF3Tjaw.png" /><figcaption>Image by author — chatbot welcome screen</figcaption></figure><p>Send your first message</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wELO06uoVQ-iMcfD61BNGg.png" /><figcaption>Image by author — chat message</figcaption></figure><h4>Demo 2: Q&amp;A on your own data</h4><p>LLMs are trained on a huge number of parameters, but it doesn’t have access to most recent data, or your private data. However to increase usability of LLMs, we can use our own data as context and augment the chatbot to answer only from the context. A simple use case for this will be enabling a user to upload their own documents and ask questions on it. Retrieval Augmentation Generation (RAG) is a design pattern that augments the capabilities of LLMs by providing an information retrieval layer that uses your own data for grounding.</p><p>In order to use RAG pattern effectively with unstructured data e.g. document, images, video etc. (in reality, &gt;90% of the data is unstructured in nature), we need to create <em>embeddings</em> or <em>vector encodings </em>for the data. Vectors are floating point numbers which represent information (text, audio, image, video) as co-ordinates in multi-dimensional space, where related content exist together irrespective of their format and source. Using vectors in your information retrieval layer gives the extra boost for relevance in search results, as well as faster querying.</p><p>High-level workflow -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MwuaVFLa3ucsuR6j_3QxZQ.png" /><figcaption>Image by author — design</figcaption></figure><ul><li><a href="https://www.trychroma.com/">Chroma</a>: It is an open-source vector database. Integrated with LangChain, it offers in-memory storage for your embeddings.</li><li><a href="https://api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ConversationalRetrievalChain.html">ConversationalRetrievalChain</a>: Retrieves relevant information from vector store and also acts as a conversational agent.</li></ul><p>Create a script app_rag.py. The chatbot will only accept PDFs from the end user.</p><pre>import os<br>from typing import List<br><br>from langchain.embeddings.openai import OpenAIEmbeddings<br>from langchain.document_loaders.pdf import PyPDFLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.vectorstores.chroma import Chroma<br>from langchain.chains import (<br>    ConversationalRetrievalChain,<br>)<br>from langchain.chat_models import AzureChatOpenAI<br>from langchain.prompts.chat import (<br>    ChatPromptTemplate,<br>    SystemMessagePromptTemplate,<br>    HumanMessagePromptTemplate,<br>)<br>from langchain.docstore.document import Document<br>from langchain.memory import ChatMessageHistory, ConversationBufferMemory<br>import chainlit as cl<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br>text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)<br>chat_model_deployment = os.getenv(&quot;OPENAI_CHAT_MODEL&quot;)<br><br>@cl.on_chat_start<br>async def on_chat_start():<br>    files = None<br><br>    # Wait for the user to upload a file<br>    while files == None:<br>        files = await cl.AskFileMessage(<br>            content=&quot;Please upload a text file to begin!&quot;,<br>            accept=[&quot;application/pdf&quot;],<br>            max_size_mb=20,<br>            timeout=180,<br>        ).send()<br><br>    file = files[0]<br><br>    msg = cl.Message(<br>        content=f&quot;Creating chunks for `{file.name}`...&quot;, disable_human_feedback=True<br>    )<br>    await msg.send()<br><br>    # Write the file to local file system<br>    if not os.path.exists(&quot;tmp&quot;):<br>        os.makedirs(&quot;tmp&quot;)<br>    with open(f&quot;tmp/{file.name}&quot;, &quot;wb&quot;) as f:<br>        f.write(file.content)<br><br>    pdf_loader = PyPDFLoader(file_path=f&quot;tmp/{file.name}&quot;)<br><br>    # Split the text into chunks<br>    documents = pdf_loader.load_and_split(text_splitter=text_splitter)<br><br>    # Create a metadata for each chunk<br>    metadatas = [{&quot;source&quot;: f&quot;{i}-pl&quot;} for i in range(len(documents))]<br><br>    msg.content = f&quot;Creating embeddings for `{file.name}`. . .&quot;<br>    await msg.update()<br><br>    # Create a Chroma vector store<br>    embeddings = OpenAIEmbeddings(<br>        openai_api_type=&quot;azure&quot;,<br>        openai_api_version=os.getenv(&quot;OPENAI_API_VERSION&quot;),<br>        openai_api_base=os.getenv(&quot;OPENAI_API_BASE&quot;),<br>        openai_api_key=os.getenv(&quot;OPENAI_API_KEY&quot;),<br>        deployment=os.getenv(&quot;OPENAI_EMBEDDING_MODEL&quot;),<br>    )<br>    docsearch = await cl.make_async(Chroma.from_documents)(<br>        documents,<br>        embeddings<br>    )<br><br>    message_history = ChatMessageHistory()<br><br>    memory = ConversationBufferMemory(<br>        memory_key=&quot;chat_history&quot;,<br>        output_key=&quot;answer&quot;,<br>        chat_memory=message_history,<br>        return_messages=True,<br>    )<br><br>    # Create a chain that uses the Chroma vector store<br>    chain = ConversationalRetrievalChain.from_llm(<br>        AzureChatOpenAI(deployment_name=chat_model_deployment,<br>                        temperature=0,<br>                        streaming=True),<br>        chain_type=&quot;stuff&quot;,<br>        retriever=docsearch.as_retriever(),<br>        memory=memory,<br>        return_source_documents=True,<br>    )<br><br>    # Let the user know that the system is ready<br>    msg.content = f&quot;Processing `{file.name}` done. You can now ask questions!&quot;<br>    await msg.update()<br><br>    cl.user_session.set(&quot;chain&quot;, chain)<br><br><br>@cl.on_message<br>async def main(message: cl.Message):<br>    chain = cl.user_session.get(&quot;chain&quot;)<br>    cb = cl.AsyncLangchainCallbackHandler()<br>    res = await chain.acall(message, callbacks=[cb])<br>    answer = res[&quot;answer&quot;]<br>    source_documents = res[&quot;source_documents&quot;]<br><br>    text_elements = []<br><br>    if source_documents:<br>        for source_idx, source_doc in enumerate(source_documents):<br>            source_name = f&quot;source_{source_idx}&quot;<br>            text_elements.append(<br>                cl.Text(content=source_doc.page_content, name=source_name)<br>            )<br>        source_names = [text_el.name for text_el in text_elements]<br><br>        if source_names:<br>            answer += f&quot;\nSources: {&#39;, &#39;.join(source_names)}&quot;<br>        else:<br>            answer += &quot;\nNo sources found&quot;<br><br>    await cl.Message(content=answer, elements=text_elements).send()</pre><p>Now test the functionality. I use a PDF copy of <a href="https://www.apple.com/newsroom/2023/11/apple-reports-fourth-quarter-results/">Apple’s recent quarter results</a> as the source data.</p><pre>chainlit run app_rag.py -w</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hh-nmPxmHfEH6heSNjPVRw.png" /><figcaption>Image by author — chatbot welcome screen 2</figcaption></figure><p>See the progress</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wm3kBrjXR4n02PC7BlfDsw.png" /><figcaption>Image by author — chatbot processing embeddings</figcaption></figure><p>Once it’s ready, ask your question</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d5jwC_SWZ9ng_QfVWhkYJA.png" /><figcaption>Image by author — chatbot sample answer from document search</figcaption></figure><p>The sources (chunks created from original doc) are also available for grounding truth to the source data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eCQLooN8wtJ2Su38C15ZzQ.png" /><figcaption>Image by author — source data chunks from documents</figcaption></figure><h4>Observability</h4><p><strong><em>Observability </em></strong>is a very useful feature in Chainlit UI, especially for data scientists and engineers who are building the app. For complex use cases, we need the LLM to act as a reasoning and acting tool (for example, getting relevant data from knowledge base, performing computations etc). The app can perform multiple steps before generating the final output for the end user.</p><p>For example, LangChain provides built-in components like <em>Agents</em> which has access to a set of tools, and based on the initial ask from user, it can decide itself which tools to use in what order in to take to generate the final output. When working these types of functionalities, it is helpful to visualize the steps happening behind the scenes, basically the reasoning process of how the agent is performing.</p><h4>Code sample</h4><p><a href="https://github.com/satwikide/Generative-AI-explorer">GitHub - satwikide/Generative-AI-explorer</a></p><h4>Resources</h4><ul><li><a href="https://python.langchain.com/docs/modules/data_connection/vectorstores/">Vector stores | 🦜️🔗 Langchain</a></li><li><a href="https://docs.chainlit.io/get-started/overview">Overview - Chainlit</a></li></ul><p><em>If you have any feedback for me, please leave your comment. Follow me for more such content. Thank you! :)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7690968578f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[‘Talk’ to Your SQL Database Using LangChain and Azure OpenAI]]></title>
            <link>https://medium.com/data-science/talk-to-your-sql-database-using-langchain-and-azure-openai-bb79ad22c5e2?source=rss-d4bbc4d61092------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb79ad22c5e2</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[gpt-3]]></category>
            <dc:creator><![CDATA[Satwiki De]]></dc:creator>
            <pubDate>Thu, 28 Sep 2023 13:53:49 GMT</pubDate>
            <atom:updated>2023-09-29T19:01:23.681Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explore the power of natural language processing using LLMs for your database queries</h4><p>Langchain is an open source framework for developing applications which can process natural language using LLMs (Large Language Models).</p><p>The <strong><em>Agent </em></strong>component of LangChain is a wrapper around LLM, which decides the best steps or actions to take to solve a problem. The Agent typically has access to a set of functions called <strong><em>Tools</em></strong> (or Toolkit) and it can decide which Tool to use based on the user input. Each agent can perform various NLP tasks, such as parsing, calculations, translation etc.</p><p>An <strong><em>Agent Executor</em></strong> is a runnable interface of the Agent and its set of Tools. The agent executor is responsible for calling the agent, getting the action and action input, calling the tool that the action references with the corresponding input, getting the output of the tool, and then passing all that information back into the Agent to get the next action it should take. Usually it is an iterative process until the Agent reaches the Final Answer or output.</p><p>In this article, I will show you how we can use <strong><em>LangChain Agent</em></strong> and <strong><em>Azure OpenAI gpt-35-turbo model</em></strong> to query your SQL database using natural language (without writing any SQL at all!) and get useful data insights. We will use <a href="https://python.langchain.com/docs/integrations/toolkits/sql_database">SQL Database Toolkit and Agent</a> which can convert user input into appropriate SQL query and run it in Database to get an answer.</p><blockquote>This is an exploratory article. It aims to provide an overview of the currently available tools and identify any challenge during the process.</blockquote><figure><img alt="image generated using Bing image creator" src="https://cdn-images-1.medium.com/max/1024/1*ndGnILAlOyxkYlplNYw06g.jpeg" /><figcaption>Image by author (created using Bing Image creator)</figcaption></figure><h3>Scope of Requirement</h3><p>For this exploration, we will only read data from the DB and avoid any insert, update or delete operations. This is to preserve the data integrity in the DB. We will focus on how we can answer questions using the data available in the DB.</p><p><em>However the SQL Agent does not guarantee that it will not perform any DML operations on your database based on specific questions. One way to ensure that any accidental DML operation does not happen is to create a database user with only </em><em>read access and use it in following code.</em></p><p>Let’s take an e-retail company’s order and inventory system database for example. The inventory keeps track of products across multiple categories e.g. kitchen, gardening, stationary, bath etc. The order system records purchase history including order status, delivery date etc. for each product.</p><p>Following can be some of the questions from the end users of this application:</p><ol><li>Quantity of kitchen products were sold last month.</li><li>How many orders have not been shipped yet?</li><li>How many orders were delivered late last month?</li><li>What are the top 3 products sold last month?</li></ol><h3>Set up</h3><ol><li><strong>Python&gt;=3.8 </strong>and an IDE for our exploration. I use VS Code.</li><li>I use <a href="https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models#gpt-35">Azure OpenAI gpt-35-turbo</a> as LLM here. This model is part of GPT-3.5 family, which can understand and generate natural language and code. To follow along, you need an Azure subscription with OpenAI service enabled. Know more <a href="https://azure.microsoft.com/en-in/products/cognitive-services/openai-service">here</a>.</li><li>I use an Azure SQL database here. However you can use an on-prem SQL DB too.</li></ol><h4>Database</h4><p>I created a database named as retailshopdb with following Tables and relationships:</p><ol><li>Category</li><li>Product</li><li>Orders</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*735BMQ5AdMQ7ytp3c-VEvw.png" /><figcaption>Image by author</figcaption></figure><p>Along with ‘Id’ columns being the primary keys for each table, the tables have foreign key relationships with each other e.g. CategoryId is a foreign key in Product table, and ProductId is a foreign key in Orders table. These relationships are crucial for the LangChain agent to construct the SQL query as per end user’s question.</p><h4>Azure OpenAI</h4><p>If you have an Azure OpenAI resource created in your subscription, navigate to Azure OpenAI studio. Create a deployment for gpt-35-turbo model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KeCrMAMaSyya5dykzsXzmw.png" /><figcaption>Image by author</figcaption></figure><h3>Code &amp; Output Analysis</h3><p>Let’s start with some base code to access the LLM from in VS code python notebook.</p><ol><li>Initialize the notebook by installing required libraries and setting required environment variables.</li></ol><pre>%pip install langchain openai sqlalchemy</pre><pre>import os<br>from dotenv import load_dotenv<br><br>os.environ[&quot;OPENAI_API_TYPE&quot;]=&quot;azure&quot;<br>os.environ[&quot;OPENAI_API_VERSION&quot;]=&quot;2023-07-01-preview&quot;<br>os.environ[&quot;OPENAI_API_BASE&quot;]=&quot;&quot; # Your Azure OpenAI resource endpoint<br>os.environ[&quot;OPENAI_API_KEY&quot;]=&quot;&quot; # Your Azure OpenAI resource key<br>os.environ[&quot;OPENAI_CHAT_MODEL&quot;]=&quot;gpt-35-turbo-16k&quot; # Use name of deployment<br><br>os.environ[&quot;SQL_SERVER&quot;]=&quot;&quot; # Your az SQL server name<br>os.environ[&quot;SQL_DB&quot;]=&quot;retailshop&quot;<br>os.environ[&quot;SQL_USERNAME&quot;]=&quot;&quot; # SQL server username <br>os.environ[&quot;SQL_PWD&quot;]=&quot;{&lt;password&gt;}&quot; # SQL server password </pre><p>2. Connect to the DB.</p><pre>from sqlalchemy import create_engine<br><br>driver = &#39;{ODBC Driver 17 for SQL Server}&#39;<br>odbc_str = &#39;mssql+pyodbc:///?odbc_connect=&#39; \<br>                &#39;Driver=&#39;+driver+ \<br>                &#39;;Server=tcp:&#39; + os.getenv(&quot;SQL_SERVER&quot;)+&#39;.database.windows.net;PORT=1433&#39; + \<br>                &#39;;DATABASE=&#39; + os.getenv(&quot;SQL_DB&quot;) + \<br>                &#39;;Uid=&#39; + os.getenv(&quot;SQL_USERNAME&quot;)+ \<br>                &#39;;Pwd=&#39; + os.getenv(&quot;SQL_PWD&quot;) + \<br>                &#39;;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;&#39;<br><br>db_engine = create_engine(odbc_str)</pre><p>3. Initialize LangChain chat_model instance which provides an interface to invoke a LLM provider using chat API. The reason to select chat model is the gpt-35-turbo model is optimized for chat, hence we use AzureChatOpenAI class here to initialize the instance.</p><pre>from langchain.chat_models import AzureChatOpenAI<br><br>llm = AzureChatOpenAI(model=os.getenv(&quot;OPENAI_CHAT_MODEL&quot;),<br>                      deployment_name=os.getenv(&quot;OPENAI_CHAT_MODEL&quot;),<br>                      temperature=0)</pre><blockquote>Note that temperature is set as 0. Temperature is a parameter that controls the “creativity” or randomness of the text generated. A lower temperature (0 being the lowest) makes the output more “focused” or deterministic. Since we’re dealing with Database here, it’s important that LLM generates factual response.</blockquote><p>4. Create a Prompt Template.</p><p><strong><em>Prompt </em></strong>is the input that we send to the LLM to generate an output. <strong><em>Prompt can also be designed to contain instructions, context, examples (one shot or few shot)</em></strong> which can be crucial for generating accurate output, as well as setting the tone and formatting your output data.</p><p>Using Prompt Template is a good way to structure these properties including the end user’s input to be provided to the LLM. We use LangChain’s ChatPromptTemplate module here, which is based on ChatML (Chat Markup Language).</p><p>This is a base prompt template to start with. Over time, we will update this template as needed —</p><pre>from langchain.prompts.chat import ChatPromptTemplate<br><br>final_prompt = ChatPromptTemplate.from_messages(<br>    [<br>        (&quot;system&quot;, <br>         &quot;&quot;&quot;<br>          You are a helpful AI assistant expert in querying SQL Database to find answers to user&#39;s question about Categories, Products and Orders.<br>         &quot;&quot;&quot;<br>         ),<br>        (&quot;user&quot;, &quot;{question}\n ai: &quot;),<br>    ]<br>)</pre><p>Now initialize the create_sql_agent which is designed to interact with SQL Database as below. The agent is equipped with toolkit to connect to your SQL database and read both the metadata and content of the tables.</p><pre>from langchain.agents import AgentType, create_sql_agent<br>from langchain.sql_database import SQLDatabase<br>from langchain.agents.agent_toolkits.sql.toolkit import SQLDatabaseToolkit<br><br>db = SQLDatabase(db_engine)<br><br>sql_toolkit = SQLDatabaseToolkit(db=db, llm=llm)<br>sql_toolkit.get_tools()<br><br>sqldb_agent = create_sql_agent(<br>    llm=llm,<br>    toolkit=sql_toolkit,<br>    agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION,<br>    verbose=True<br>)</pre><p>Note that we use ZERO_SHOT_REACT_DESCRIPTION here as the value of agent_type parameter, which instructs that the agent <em>does not use memory.</em></p><p>All set to run our testing —</p><pre>sqldb_agent.run(final_prompt.format(<br>        question=&quot;Quantity of kitchen products sold last month?&quot;<br>  ))</pre><blockquote>Notice in the following cell output how the LangChain Agent Executor is using the flow of Action , Observation and Thought in an iterative manner, until it reaches a Final Answer.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QSdplJFXxbItY7tgRquUWg.png" /><figcaption>Image by author</figcaption></figure><p><em>Output: 10</em></p><p>This is a correct answer.</p><p>Let’s have some fun, shall we? Replace ‘Quantity’ with ‘how many’ in the same question, which should produce the same answer.</p><pre>sqldb_agent.run(final_prompt.format(<br>        question=&quot;How many kitchen products were sold last month?&quot;<br>  ))</pre><p>But this is what we get —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K1_9AXAMJ3bjQHhHZi4xcA.png" /><figcaption>Image by author</figcaption></figure><p><em>Output: ‘2 kitchen products were sold in the current month.’</em></p><p><strong><em>This output is not correct!</em></strong><em> </em>The Agent makes a mistake in the SQL query creation. Instead of doing SUM(ProductOrderedQuantity) to get the output, it does a COUNT(*) on the JOIN result which gives the wrong output.</p><blockquote><strong>Why changing the prompt input slightly produces different outputs?</strong></blockquote><blockquote>OpenAI models are non-deterministic, meaning that identical inputs can yield different outputs. Setting temperature to 0 will make the outputs mostly deterministic, but a small amount of variability may remain due to GPU floating point math.</blockquote><p>Running another test with a different input—</p><pre>sqldb_agent.run(final_prompt.format(<br>        question=&quot;How many orders have not been shipped yet?&quot;<br>  ))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pd-7qSa5QEdVsodtvvx_7g.png" /><figcaption>Image by author</figcaption></figure><p><em>Output: ‘There are 15 orders that have not been shipped yet.’</em></p><p><strong><em>This is again incorrect result.</em></strong><em> The agent takes into account ‘Completed’ orders as well, when our question implies only the orders which have not been shipped.</em></p><p>Let’s see what modifications we can make to produce accurate outputs.</p><h4>Play with Prompt Engineering</h4><p>The LangChain agent can read table metadata from SQL Database using its Toolkit, and to some extent it can interpret the column names as well. But there are still some gap in reasoning, which we can try to mitigate using Prompt Engineering technique.</p><p>We started with a base prompt template having a single line of instruction. Let’s include some additional information to provide more context about our use case to the LLM in order to form better SQL query. Here are the information I added in the System message on a high-level:</p><ol><li>Information about Table columns</li><li>‘Meaning’ of Order Status values</li><li>Most specific information at the end</li></ol><pre>from langchain.prompts.chat import ChatPromptTemplate<br><br><br>final_prompt = ChatPromptTemplate.from_messages(<br>    [<br>        (&quot;system&quot;, <br>         &quot;&quot;&quot;<br>         You are a helpful AI assistant expert in identifying the relevant topic from user&#39;s question about Categories, Products and Orders and then querying SQL Database to find answer.<br>         Use following context to create the SQL query. Context:<br>         Product table contains information about products including product name, description, product price and product category.<br>         Category table contains information about categories including category name and description. Each Product is mapped to a Category.<br>         Orders table contains information about orders placed by customers including <br>         quantity or number of products ordered,<br>         expected delivery date and actual delivery date of the Order in the location and the status of the order. <br>         Order status = &#39;Processing&#39; means the order is being processed by seller and not yet shipped,<br>         Order status = &#39;Shipped&#39; means the order is shipped by the seller and is on the way to the customer,<br>         Order status = &#39;Completed&#39; means the order is delivered to the customer, and <br>         Order status = &#39;Cancelled&#39; means the order is cancelled by the customer.<br><br>         If the question is about number of products in an order, then look for column names with &#39;quantity&#39; in the tables and use &#39;sum&#39; function to find the total number of products.<br>        &quot;&quot;&quot;<br>         ),<br>        (&quot;user&quot;, &quot;{question}\n ai: &quot;),<br>    ]<br>)</pre><p>Now run the first input again—</p><pre>sqldb_agent.run(final_prompt.format(<br>        question =&quot;How many Kitchen products were sold in current month?&quot;<br>  ))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v8wuzFsdRoGIILRtXt3vBg.png" /><figcaption>Image by author</figcaption></figure><p><em>Output: 10</em></p><p>The reasoning has improved! By providing additional context to the LLM, we were able to get an accurate output.</p><p>Now test all user inputs —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*83DWWkDGU5ejdVCKcUXITA.png" /></figure><h3>After-thoughts . . .</h3><p>All this looks good for play, but what if we want to actually build a solution and release it for end users consumption? This is a great idea for use cases like chatbot on your own database, however any like any typical software development, we also need to think and decide about some crucial design aspects before building LLM-based systems.</p><h4>Scalability</h4><p>In this example, I have used 3 tables with total ~30 rows. The avg. latency to produce an output which involves joining all 3 tables is ~5 secs. As of today, I didn’t find any information in official docs on the maximum size of database we can use with this Agent. However there are few parameters we can think of to determine our requirements:</p><ol><li>What is the Latency required by your application? If you’re building a chatbot, then your expected latency might not go beyond a certain number.</li><li>What is your Database size? Also take into account the size of individual tables which you want to use for query.</li></ol><blockquote>Note that you don’t need to pass entire Database to the Agent Toolkit. There is option to select specific tables to work with the Toolkit. A good option is to identify subsets of tables for separate use cases, and create multiple Agents pointing to different subset of tables.</blockquote><p>3. Rate and quota limit of your Azure OpenAI resource. If you’re using another LLM provider, then look for limitations/restrictions there too.</p><h4>Reliability</h4><p>How can we ensure that we get accurate response consistently? How do we make sure the system does not hallucinate or produce completely unexpected content?</p><p>There is ongoing research on improving reliability and robustness of LLMs. Using use case specific prompts we can help improve the reasoning for our use case, which is also sometimes termed as ‘temporary or in-context learning’.</p><blockquote>Remember that we are not training LLMs here. From a perspective of building products using the pre-trained LLMs, we can only tweak our code, model parameters and prompts that are built on top of these LLMs, but tweak them in a targeted way.</blockquote><p>Development in an iterative manner and also evaluation along the way can take us to the right direction to develop an overall working system.</p><h4>Logging and Monitoring</h4><p>Like any other typical software development, enabling logging and continuous monitoring of the LLM-based applications is a good practice. Monitoring can not only capture system-related metrics like performance, latency, request-response rates, but also the inputs and outputs from our system, which can help us determining the consistency of the system. Some useful information we can gather from Monitoring and use to improve our system:</p><ol><li>Frequent, similar questions from end user, and outputs generated for these questions</li><li>Hallucination rate of LLM</li></ol><h4>Conclusion</h4><p>The Software Engineering world is changing rapidly with LLMs’ immense generative capability, and there are many solutions coming up in this space. We have an opportunity to adopt this technology, and harness its power to create products while also keeping a check on reliability of LLM-backed systems. It is always a good idea to start small, build a proof-of-concept app and see if it fits your requirement.</p><h3>References:</h3><p><a href="https://community.openai.com/t/run-same-query-many-times-different-results/140588">https://community.openai.com/t/run-same-query-many-times-different-results/140588</a></p><p><a href="https://help.openai.com/en/articles/6654000-best-practices-for-prompt-engineering-with-openai-api">https://help.openai.com/en/articles/6654000-best-practices-for-prompt-engineering-with-openai-api</a></p><p><a href="https://mlops.community/concepts-for-reliability-of-llms-in-production/">https://mlops.community/concepts-for-reliability-of-llms-in-production/</a></p><p><em>Please follow me if you want to read more such content about new and exciting technology. Please leave your feedback in the comment section.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb79ad22c5e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/talk-to-your-sql-database-using-langchain-and-azure-openai-bb79ad22c5e2">‘Talk’ to Your SQL Database Using LangChain and Azure OpenAI</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy a Containerized Python App to Azure (Part 2)]]></title>
            <link>https://python.plainenglish.io/deploy-a-containerized-python-app-to-azure-part-2-6442fbed2dba?source=rss-d4bbc4d61092------2</link>
            <guid isPermaLink="false">https://medium.com/p/6442fbed2dba</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Satwiki De]]></dc:creator>
            <pubDate>Tue, 19 Sep 2023 14:59:53 GMT</pubDate>
            <atom:updated>2023-09-26T14:07:45.679Z</atom:updated>
            <content:encoded><![CDATA[<p>Check out part 1 article of this series here, where I had set up the python FastAPI app with Azure SQL database.</p><p><a href="https://medium.com/@cleancoder/deploy-a-containerized-python-app-to-azure-part-1-7670b687e3e7">Deploy a containerized python app to Azure (Part 1)</a></p><p>In following steps, we upload the docker container to Azure container registry and configure Continuous Deployment to Azure App Service.</p><p>Following is the overall architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*we2DZNW_bMbFpjeIFDq5Tg.png" /></figure><h3>Pre-requisites</h3><ol><li>We will use GitHub Action to set up the Continuous Deployment for our Python application. To follow along, sign in to GitHub and create a repo.</li><li>Install <a href="https://learn.microsoft.com/en-us/cli/azure/install-azure-cli">Azure CLI</a>.</li><li>An Azure subscription. Assuming that you already created the Azure SQL database in previous article, we will continue in the same subscription to create the Azure Container Registry (ACR) and App Service.</li></ol><h3>Set up</h3><h4>#1 Update Dockerfile</h4><p>We use the same Dockerfile from part 1 here with minor modifications. Update CMD and expose port 8000.</p><p>By default, App Service assumes your container is listening on either port 80 or 8080. The default port number varies for different frameworks. For example — since our app is built with FastAPI, we need to expose port 8000 from the container. [<a href="https://learn.microsoft.com/en-us/azure/developer/python/containers-in-azure-overview-python?tabs=vscode-ide#container-settings-for-web-frameworks">Reference</a>]</p><pre># parent image<br>FROM python:3.10.9-slim-buster<br><br>EXPOSE 8000<br><br>WORKDIR /app<br><br>ADD /src/requirements.txt .<br>ADD /src/repository.py .<br>ADD /src/main.py .<br># Uncomment the following line to use a local copy of the .env file<br># ADD .env . <br><br>RUN apt-get update -y &amp;&amp; apt-get install -y curl gnupg g++ unixodbc-dev<br>RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -<br>RUN curl https://packages.microsoft.com/config/debian/10/prod.list &gt; /etc/apt/sources.list.d/mssql-release.list <br><br>RUN exit<br>RUN apt-get update<br>RUN ACCEPT_EULA=Y apt-get install -y msodbcsql17<br><br>COPY /odbc.ini / <br>RUN odbcinst -i -s -f /odbc.ini -l<br>RUN cat /etc/odbc.ini <br><br>RUN pip install --upgrade -r requirements.txt<br><br># For running the container locally <br># CMD [&quot;uvicorn&quot;, &quot;main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]<br><br>CMD [&quot;gunicorn&quot;, &quot;--bind&quot;, &quot;0.0.0.0:8000&quot;, &quot;main:app&quot;, &quot;--worker-class&quot;, &quot;uvicorn.workers.UvicornWorker&quot;]</pre><blockquote>Note: App service uses the gunicorn WSGI web server by default, but FastAPI app runs in an ASGI server. Hence these two are not compatible. We can make it work using worker classes of uvicorn along with the gunicorn command. uvicorn is an ASGI web server implementation.</blockquote><p>Repeating the solution files structure from <a href="https://medium.com/@cleancoder/deploy-a-containerized-python-app-to-azure-part-1-7670b687e3e7">part 1</a> for reference:</p><pre>mypythonwebapp (root folder)<br>  |--src<br>      |--main.py<br>      |--repository.py<br>      |--requirements.txt<br>  |--.env<br>  |--Dockerfile<br>  |--README.MD<br>  |--odbc.ini</pre><h4>#2 Azure Container Registry</h4><p>Set up Azure Container Registry to manage our Container images and artifacts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*k5bAK2kOg4sUN7yFXdHe_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gwNp6yU-yvs77itAbaYiyg.png" /></figure><p>Enable Access Keys under Settings. This is required to push the initial image to App service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lsvSWSJDU6vDQeIcU9gkkg.png" /></figure><p>Now let’s push the container image we created in previous article to this registry. Follow these steps to do so using Az CLI in terminal:</p><pre>az login<br>az acr login --name &lt;your-acr-name&gt;</pre><p>Push the latest image for todolist-app to ACR</p><pre>docker tag todolist-app:latest &lt;your-acr-name&gt;.azurecr.io/samples/todolist-app<br>docker push &lt;your-acr-name&gt;.azurecr.io/samples/todolist-app</pre><h4>#3 Azure App Service</h4><p>In Azure portal, search for App Service and create an Azure Web App with Docker Container</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*MDbYJsRqp82oi1ybsCfvrg.png" /></figure><p>In next step, select the docker image from ACR</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*rK9YF-GLAj606pngWhSBAw.png" /></figure><p>(Optional) Enable App insights. If you create a new App Insights resource at this stage, then keep the connection string handy for using in the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*9bQ2JXdUui4X7v8TFmgSFg.png" /></figure><p>Create the app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G1SlXAU7k50sMD5i9IWLqA.png" /></figure><p>Go to Configuration section and add the required application settings —</p><pre>SQL_DB=<br>SQL_PWD=<br>SQL_SERVER=<br>SQL_USERNAME=<br>APPLICATIONINSIGHTS_CONNECTION_STRING=</pre><p>We also add another app setting to specify the port for web traffic, this should be same as the port exposed in Dockerfile.</p><pre>WEBSITES_PORT=8000</pre><p>Once these settings are done, navigate to the App Service url {app-service-name}.azurewebsites.net/docs and verify the APIs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AN6xbsrE2LC8SPGJ2GrAFA.png" /></figure><p>Test a API to see if data is being pulled from Azure SQL DB</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7OB3KrNV4NLOCKE2oO4JYg.png" /></figure><p>This is it! :)</p><h3>Set up Continuous Deployment</h3><p>Now that our app service is all set and running, let’s configure the <em>Continuous Integration and Continuous Deployment</em> using GitHub Action.</p><p>Push your code to an empty GitHub repo if you haven’t done it yet.</p><p>Before we go into the workflow setup, let’s think about <strong><em>the mode of authentication</em></strong> between GitHub and Container registry, and also App service and Container Registry.</p><h4>Step #1 Set up Managed Identity</h4><p>There are few options to access Container Registry, one being Access Keys where you can set up Admin username and password for the registry. Another option is to use managed identity, which is a RBAC (role-based-access-control), password-less way to access the registry from other Azure services. We will use the 2nd option here, to minimize number of secrets to manage in the system.</p><blockquote>If you don’t want to use managed identity, then skip the following steps and go to step #3. As container registry access key will be used for authentication, make sure you have enabled Admin user in your ACR.</blockquote><p>Let’s create a user assigned managed identity named msi-poc in your resource group</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*N5Pz7zaIOIp0_MGNgFkcwQ.png" /></figure><p>Now, open the container registry and go to Identity section and set up user assigned managed identity. This is required by the App service to pull the container images from this registry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2pKxTURTm7THW7fLDvxUMg.png" /></figure><p>Repeat the same step for the <strong>App Service </strong>too.</p><p>Once the managed identity is set up in both services, it should have the following role AcrPull auto-assigned. If not present, then add this role manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MgVOrLX5B1y__wnFfmpUxw.png" /></figure><h4>Step #2: Set up service principal</h4><p>Let’s think about GitHub to Azure Container registry authentication. We need to authenticate to Azure in order to push the docker image generated in GitHub workflow to our Container Registry. The secure way to do this is by using a service principal and GitHub secrets [<a href="https://learn.microsoft.com/en-us/azure/container-registry/container-registry-auth-service-principal#create-a-service-principal">Reference</a>].</p><p>Open an Azure cloud shell terminal and paste the following script. The service principal should have acrpush role assigned.</p><pre>ACR_NAME=&lt;your-container-registry&gt;<br>SERVICE_PRINCIPAL_NAME=&lt;unique-sp-name&gt;<br>ACR_REGISTRY_ID=$(az acr show --name $ACR_NAME --query &quot;id&quot; --output tsv)<br>PASSWORD=$(az ad sp create-for-rbac --name $SERVICE_PRINCIPAL_NAME --scopes $ACR_REGISTRY_ID --role acrpush --query &quot;password&quot; --output tsv)<br>USER_NAME=$(az ad sp list --display-name $SERVICE_PRINCIPAL_NAME --query &quot;[].appId&quot; --output tsv)<br>echo &quot;Service principal ID: $USER_NAME&quot;<br>echo &quot;Service principal password: $PASSWORD&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PLUhATmhQ_vKt5XWR9NhIQ.png" /></figure><p>Copy the username and password from terminal, we will add these as secrets in GitHub —</p><ol><li>AZURE_CONTAINER_CLIENT_ID</li><li>AZURE_CONTAINER_CLIENT_SECRET</li></ol><blockquote>If you don’t want to set up service principal, then use admin user credentials instead. Create the secrets in Github for admin username and password.</blockquote><h4>Step #3: GitHub Action</h4><p>Download the publish profile from the app service, and create a secret {app-service-name}-publish-profile in GitHub to store it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7yHcuQyWa0l4h70yEILUxg.png" /></figure><p>Open your project folder and create followingdeploy_workflow.yml file under .github/workflows folder in your repo.</p><p>The workflow will have 2 stages: build and deploy. build stage will create the container image based on the Dockerfile and push it to ACR. deploy stage will update the latest container image in App Service.</p><pre>name: Build and deploy python container app to Azure Web App<br><br>on:<br>  push:<br>    branches:<br>      - master<br>  workflow_dispatch:<br><br>jobs:<br>  build:<br>    runs-on: &#39;ubuntu-latest&#39;<br><br>    steps:<br>    - uses: actions/checkout@v2<br><br>    - name: Set up Docker Buildx<br>      uses: docker/setup-buildx-action@v2<br><br>    - name: Log in to registry<br>      uses: docker/login-action@v2<br>      with:<br>        registry: https://pythonappsregistry.azurecr.io/<br>        username: ${{ secrets.AZURE_CONTAINER_CLIENT_ID }}<br>        password: ${{ secrets.AZURE_CONTAINER_CLIENT_SECRET }}<br><br>    - name: Build and push container image to registry<br>      uses: docker/build-push-action@v3<br>      with:<br>        push: true<br>        tags: pythonappsregistry.azurecr.io/builds/todolist-app:${{ github.sha }}<br>        file: ./Dockerfile<br>  <br>  deploy:<br>    runs-on: ubuntu-latest<br>    needs: build<br>    environment:<br>      name: &#39;production&#39;<br>      url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}<br><br>    steps:<br>    - name: Azure Login<br>      uses: azure/login@v1<br>      with:<br>        creds: ${{ secrets.AZURE_CREDENTIAL }}<br><br>    - name: &#39;Allow basic publishing credentials access&#39;<br>      uses: azure/CLI@v1<br>      with:<br>        inlineScript: |<br>          az resource update --resource-group article --name scm --namespace Microsoft.Web \<br>          --resource-type basicPublishingCredentialsPolicies --parent sites/mycontainersampleapp \<br>          --set properties.allow=true<br><br>    - name: Deploy to Azure Web App<br>      id: deploy-to-webapp<br>      uses: azure/webapps-deploy@v2<br>      with:<br>        app-name: &#39;mycontainersampleapp&#39;<br>        slot-name: &#39;production&#39;<br>        publish-profile: ${{ secrets.MYCONTAINERSAMPLEAPP_PUBLISH_PROFILE }}<br>        images: &#39;pythonappsregistry.azurecr.io/builds/todolist-app:${{ github.sha }}&#39;</pre><p>Run the Github Action</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BD8tPTbmYnoS9yZmW6sHoA.png" /></figure><p>Once deployment is successful, open the app service url in browser to verify</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qPf-HaIRFjIFXjGlwPRqZw.png" /></figure><p>Test Azure SQL connectivity by triggering all endpoint</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1AAIz0CwZMpVUvKLuAZrWw.png" /></figure><p>All set! :)</p><p>Check out the code <a href="https://github.com/satwikide/mypythonwebapp">here</a>.</p><h4>Possible Issues and Solutions</h4><p>If your FastAPI app throws <strong>Internal Server Error</strong> after deployment to App Service, check your logs under Monitoring -&gt; Log stream. Check if the log contains below error: <em>FastAPI.__call__() missing 1 required positional argument: ‘send’</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b6jCb-juMDsY5cFmF3pwpw.png" /></figure><p>This is due to web server incompatibility between App service and FastAPI. App service uses the <em>gunicorn</em> <em>WSGI</em> web server by default, but FastAPI app runs in an ASGI server. Hence these two are not compatible. We can make it work using worker classes of <em>uvicorn</em> along with the <em>gunicorn</em> command. <em>uvicorn</em> is an ASGI web server implementation.</p><p><strong>Solution: </strong>Update your docker file CMD with following to use uvicorn worker class.</p><pre>CMD [&quot;gunicorn&quot;, &quot;--bind&quot;, &quot;0.0.0.0:8000&quot;, &quot;main:app&quot;, &quot;--worker-class&quot;, &quot;uvicorn.workers.UvicornWorker&quot;]</pre><p>Hope this article helped you. Don’t forget to leave a comment and follow my page for upcoming articles on new and exciting topics!</p><p>If you want to check how to use <strong><em>WebDeploy </em></strong>method to deploy your python app to Azure App Service using Github Action, check my step-by-step guide here —</p><p><a href="https://python.plainenglish.io/deploy-python-api-in-azure-web-app-using-github-action-86ade78c1d9e">Deploy Python API in Azure Web App Using GitHub Action</a></p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, and <a href="https://discord.gg/XxRS92b2"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6442fbed2dba" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/deploy-a-containerized-python-app-to-azure-part-2-6442fbed2dba">Deploy a Containerized Python App to Azure (Part 2)</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy a containerized python app to Azure (Part 1)]]></title>
            <link>https://medium.com/@satwikide/deploy-a-containerized-python-app-to-azure-part-1-7670b687e3e7?source=rss-d4bbc4d61092------2</link>
            <guid isPermaLink="false">https://medium.com/p/7670b687e3e7</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Satwiki De]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 12:09:09 GMT</pubDate>
            <atom:updated>2023-09-28T18:23:16.481Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Image of Python App inside Docker Container generated by Bing image creator" src="https://cdn-images-1.medium.com/max/1024/1*upnQA-2akgrowl-bSqkF4w.jpeg" /></figure><p><a href="https://www.docker.com/resources/what-container/">A <strong>container </strong>is a standard unit of software that packages up code and all its dependencies so the application runs quickly and reliably from one computing environment to another</a>. Using Containers for application deployment ensures efficiency, scalability and cross-platform support.</p><p><strong>Python </strong>is growing as a popular choice for backend services these days and containerization provides several benefits for Python applications, including portability, scalability, and consistency across different environments. By using containers, developers can ensure that their applications run the same way regardless of the infrastructure or third-party library updates.</p><p>This is a two-part series to explore creating docker container for python app in your local machine first, and then setting up continuous deployment for the same in Azure app service.</p><p>We assume that you already have some basic idea on Containers, Docker, Python, GitHub etc.</p><p>Considering real-world scenarios, I have created a <strong><em>Python FastAPI app which interacts with an Azure SQL database</em></strong> and exposes <strong><em>APIs</em></strong> which can be consumed in other services. We will then create a Linux container for this app along with its dependencies, and test the container locally.</p><blockquote>If you want to skip to the continuous deployment configuration, head over to part 2 of this series.</blockquote><p><a href="https://python.plainenglish.io/deploy-a-containerized-python-app-to-azure-part-2-6442fbed2dba">Deploy a Containerized Python App to Azure (Part 2)</a></p><h3><strong>Pre-requisites</strong></h3><p><strong>Local system</strong></p><ol><li>Python ≥ 3.10</li><li>Docker desktop</li><li>Postman (Optional, for testing APIs)</li><li>VS code &amp; Docker extension in VS code (Optional)</li></ol><p><strong>Azure</strong></p><ol><li>An Azure subscription</li><li>Set up an Azure SQL Server and Database.</li></ol><blockquote><em>Create SQL username and password while creating the Server</em>, <em>we will use this to access the DB from our app.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SoeqXpM5i1GDTa1QsVa4rQ.png" /></figure><p>In the networking section, make sure following option is checked Allow Azure Services and resources to access this server. This is required for our app service to access the database. You can add your own IP address too if you want to access this DB from your local machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-WXvmMuqkP4EA84TFUeg2Q.png" /></figure><p>We create a todolist database in this server for our app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XMB3YYRqeIfm0NYEnPiZWg.png" /></figure><p>(Optional) Use this script to initialize the DB schema</p><pre>CREATE TABLE [dbo].[todolist](<br> Id int not null identity(1,1) primary key,<br> Task nvarchar(max) not null,<br> CreatedOn DateTime not null,<br> ModifiedOn DateTime,<br> CreatedBy nvarchar(255),<br> Category nvarchar(255),<br> IsCompleted bit not null<br>)</pre><h3>Code</h3><p>Now we start with the Python application. We’ll use <a href="https://fastapi.tiangolo.com/">FastAPI</a> framework to develop our APIs which will read and write data in Azure SQL database using pyodbc library.</p><p>Following is the structure of the solution</p><pre>mypythonwebapp (root folder)<br>  |--src<br>      |--main.py<br>      |--repository.py<br>      |--requirements.txt<br>  |--.env<br>  |--README.MD</pre><ol><li>Populate .env with following information</li></ol><pre>SQL_SERVER=&quot;&lt;your sql server name&gt;&quot;<br>SQL_DB=&quot;&lt;DB name&gt;&quot;<br>SQL_USERNAME=&quot;&lt;sql username&gt;&quot;<br>SQL_PWD=&quot;{sql password}&quot;<br>APPLICATIONINSIGHTS_CONNECTION_STRING=&quot;&lt;App insights connection string&gt;&quot;</pre><p>2. Add following in the requirements.txt file and install using pip</p><pre>python-dotenv==1.0.0<br>uvicorn==0.23.2<br>fastapi==0.101.0<br>azure-monitor-opentelemetry==1.0.0b16<br>azure-identity==1.14.0<br>pyodbc==4.0.39</pre><pre>pip install -r requirements.txt</pre><p>3. Start with our repository.py script to initialize the CRUD operations</p><p>Creating functions for 4 operations, which will be utilized by our Python APIs.</p><ol><li>Get all tasks in ToDo list</li><li>Create a new task in ToDo list</li><li>Get tasks created by a user in ToDo list</li><li>Mark a Task as ‘Completed’ in ToDo list</li></ol><pre>import pyodbc<br>import logging<br>import os<br>import datetime<br>from dotenv import load_dotenv<br><br>class Repository():<br>    def __init__(self, logger):<br>        print(&#39;Repository created&#39;)<br>        self.logger = logger<br><br>    # Initialize connection<br>    async def get_conn(self):<br>        try:<br>            load_dotenv()<br>            driver=&#39;{ODBC Driver 17 for SQL Server}&#39;<br>            connection = pyodbc.connect(f&#39;DRIVER={driver};SERVER=tcp:&#39;+os.getenv(&quot;SQL_SERVER&quot;)+\<br>                                        &#39;.database.windows.net;PORT=1433;DATABASE=&#39;+os.getenv(&quot;SQL_DB&quot;)+\<br>                                        &#39;;UID=&#39;+os.getenv(&quot;SQL_USERNAME&quot;)+&#39;;PWD=&#39;+ os.getenv(&quot;SQL_PWD&quot;))<br>            return connection<br>        except Exception as e:<br>            self.logger.error(e)<br>            raise e<br><br>    async def get_all(self) -&gt; list|None:<br>        print(&#39;get_all called&#39;)<br>        try:<br>            # Get all items from the database<br>            connection = await self.get_conn()<br>            cursor = connection.cursor()<br>            cursor.execute(&quot;SELECT Id, Task, CreatedOn, CreatedBy, Category, IsCompleted, ModifiedOn FROM todolist&quot;)<br>            rows = cursor.fetchall()<br>            items = []<br>            for row in rows:<br>                items.append({<br>                    &quot;id&quot;: row.Id,<br>                    &quot;task&quot;: row.Task,<br>                    &quot;createdOn&quot;: row.CreatedOn,<br>                    &quot;createdBy&quot;: row.CreatedBy,<br>                    &quot;category&quot;: row.Category,<br>                    &quot;isCompleted&quot;: row.IsCompleted,<br>                    &quot;modifiedOn&quot;: row.ModifiedOn<br>                })<br>            self.logger.info(&quot;All tasks retrieved successfully&quot;)<br>            return items<br>        except Exception as e:<br>            self.logger.error(e)<br>            raise e<br>        finally:<br>            cursor.close()<br>            connection.close()<br><br>    async def get_by_user(self, created_by_user: str) -&gt; list|None:<br>        try:<br>        # Get all items from the database<br>            connection = await self.get_conn()<br>            cursor = connection.cursor()<br>            cursor.execute(f&quot;SELECT Id, Task, CreatedOn, CreatedBy, Category, IsCompleted, ModifiedOn FROM todolist WHERE CreatedBy = {created_by_user}&quot;, created_by_user)<br>            rows = cursor.fetchall()<br>            items = []<br>            for row in rows:<br>                items.append({<br>                    &quot;id&quot;: row.Id,<br>                    &quot;task&quot;: row.Task,<br>                    &quot;createdOn&quot;: row.CreatedOn,<br>                    &quot;createdBy&quot;: row.CreatedBy,<br>                    &quot;category&quot;: row.Category,<br>                    &quot;isCompleted&quot;: row.IsCompleted,<br>                    &quot;modifiedOn&quot;: row.ModifiedOn<br>                })<br>            self.logger.info(f&quot;Tasks for user {created_by_user} retrieved successfully&quot;)<br>            return items<br>        except Exception as e:<br>            self.logger.error(e)<br>            raise e<br>        finally:<br>            cursor.close()<br>            connection.close()<br><br>    async def add_task(self, description: str, user: str, category: str) -&gt; int:<br>        # Add a new item to the database<br>        try:<br>            INSERT_STATEMENT = &quot;INSERT INTO todolist (Task, CreatedBy, CreatedOn, Category, IsCompleted) OUTPUT INSERTED.Id VALUES (?, ?, ?, ?, 0)&quot;<br>            connection = await self.get_conn()<br>            cursor = connection.cursor()<br>            cursor.execute(INSERT_STATEMENT,<br>                            description,<br>                            user,<br>                            datetime.datetime.now(),<br>                            category)<br>            taskId = cursor.fetchval()<br>            connection.commit()<br>            self.logger.info(f&quot;Task with {taskId} for user {user} added successfully&quot;)<br>            return taskId<br>        except Exception as e:<br>            self.logger.error(e)<br>            raise e<br>        finally:<br>            cursor.close()<br>            connection.close()<br><br>    async def update_task_status(self, task_id: int) -&gt; None:<br>        # Update an item in the database<br>        try:<br>            UPDATE_STATEMENT = &quot;UPDATE todolist SET IsCompleted = 1, ModifiedOn = ? WHERE Id = ?&quot;<br>            connection = await self.get_conn()<br>            cursor = connection.cursor()<br>            cursor.execute(UPDATE_STATEMENT, datetime.datetime.now(), task_id)<br>            connection.commit()<br>            self.logger.info(f&quot;Task with {task_id} updated successfully&quot;)<br>        except Exception as e:<br>            self.logger.error(e)<br>            raise e<br>        finally:<br>            cursor.close()<br>            connection.close()</pre><p>4. Next, initialize APIs in main.py and call services defined in repository.py</p><pre>from dotenv import load_dotenv<br>import os<br>from fastapi import FastAPI<br>from fastapi import Request, Response<br>from pydantic import BaseModel<br>from repository import Repository<br>from azure.monitor.opentelemetry import configure_azure_monitor<br>from opentelemetry import trace<br>from opentelemetry.trace import (<br>    SpanKind,<br>    get_tracer_provider,<br>)<br>from opentelemetry.propagate import extract<br>from logging import getLogger, INFO<br><br>load_dotenv()<br><br># Initialize OpenTelemetry with Azure Monitor<br>configure_azure_monitor(<br>    connection_string=os.getenv(&quot;APPLICATIONINSIGHTS_CONNECTION_STRING&quot;)<br>)<br>tracer = trace.get_tracer(__name__, tracer_provider=get_tracer_provider())<br>logger = getLogger(__name__)<br>logger.setLevel(INFO)<br><br># This schema is needed for POST request - /create endpoint<br>class Task(BaseModel):<br>    description: str<br>    user: str<br>    category: str<br><br># Define the app<br>app = FastAPI(<br>    title=&quot;MyApp&quot;,<br>    description=&quot;Hello API developer!&quot;,<br>    version=&quot;0.1.0&quot;<br>)<br><br># Initialize repository<br>repository = Repository(logger)<br><br># API for health check of App<br>@app.get(&quot;/&quot;)<br>async def main(request: Request):<br>    with tracer.start_as_current_span(<br>        &quot;main_request&quot;,<br>        context=extract(request.headers),<br>        kind=SpanKind.SERVER<br>    ):<br>        logger.info(&quot;Hello World endpoint was reached. . .&quot;)<br>        return {&quot;message&quot;: &quot;Hello World&quot;}<br><br># API to get all the data from ToDo list<br>@app.get(&quot;/all&quot;)<br>async def main(request: Request):<br>    with tracer.start_as_current_span(&quot;get_all_tasks&quot;,<br>                                      context=extract(request.headers),<br>                                      kind=SpanKind.SERVER):<br>        logger.info(&quot;Get all tasks endpoint was reached. . . validating the scope of request. . .&quot;)<br>        try:<br>            print(&#39;get_all_tasks endpoint was reached. . .&#39;)<br>            return repository.get_all()<br>        except Exception as ex:<br>            logger.error(ex)<br>            return Response(content=str(ex), status_code=500)<br><br><br># API to submit data to ToDo list<br>@app.post(&quot;/create&quot;)<br>async def submit(task: Task, request: Request):<br>    with tracer.start_as_current_span(&quot;create_task&quot;,<br>                                      context=extract(request.headers),<br>                                      kind=SpanKind.SERVER):<br>        logger.info(&quot;/create endpoint was reached. . .&quot;)<br>        try:<br>            repository.add_task(task.description, task.user, task.category)<br>            return {&quot;message&quot;: f&quot;Data submitted successfully&quot;}<br>        except Exception as ex:<br>            logger.error(ex)<br>            return Response(content=str(ex), status_code=500)<br><br><br># API to mark a task as &#39;Completed&#39;<br>@app.post(&quot;/done&quot;)<br>async def complete(task_id: int, request: Request):<br>    with tracer.start_as_current_span(&quot;mark_task_as_completed&quot;,<br>                                      context=extract(request.headers),<br>                                      kind=SpanKind.SERVER):<br>        logger.info(&quot;/done endpoint was reached. . .&quot;)<br>        try:<br>            await repository.update_task_status(task_id)<br>            return {&quot;message&quot;: f&quot;Task marked as completed successfully&quot;}<br>        except Exception as ex:<br>            logger.error(ex)<br>            return Response(content=str(ex), status_code=500)</pre><p>Now we do a quick test by running this app locally. Open terminal in src folder and run the following command:</p><pre>uvicorn main:app --reload</pre><p>The output in terminal should be like this</p><p><em>INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)<br>INFO: Started reloader process [24392] using WatchFiles<br>Repository created<br>INFO: Started server process [24416]<br>INFO: Waiting for application startup.<br>INFO: Application startup complete.</em></p><blockquote><em>Note: Your IP address should be added to Azure SQL Server in order to test the APIs. Azure SQL server disables public access by default.</em></blockquote><ol><li>Test /create endpoint</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pu4F0rXOy0VBV22ciW9MbQ.png" /></figure><p>2. Test /all endpoint</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xxjdu-tPRtgHzTCswLs48A.png" /></figure><p>3. Test /done endpoint</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uBTU2wjKZUdvzHsO4gkjJA.png" /></figure><p>Now moving on to the most-awaited part — <strong>CREATING THE CONTAINER!</strong> :)</p><h4><strong>#STEP 1 — Set up Dockerfile</strong></h4><p>Start by creating a Dockerfile in the root folder with following code snippet</p><pre># parent image<br>FROM python:3.10.9-slim-buster<br><br>WORKDIR /app<br><br>ADD /src/requirements.txt .<br>ADD /src/repository.py .<br>ADD /src/main.py .<br>ADD .env .<br><br>RUN apt-get update -y &amp;&amp; apt-get install -y curl gnupg g++ unixodbc-dev<br>RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -<br>RUN curl https://packages.microsoft.com/config/debian/10/prod.list &gt; /etc/apt/sources.list.d/mssql-release.list <br><br>RUN exit<br>RUN apt-get update<br>RUN ACCEPT_EULA=Y apt-get install -y msodbcsql17<br><br>COPY /odbc.ini / <br>RUN odbcinst -i -s -f /odbc.ini -l<br>RUN cat /etc/odbc.ini <br><br>RUN pip install --upgrade -r requirements.txt<br><br>CMD [&quot;uvicorn&quot;, &quot;main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><p>Notice that there are new installations which we didn’t need when developing the app. Let’s walk through these updates.</p><p>We’re targeting this container to be running in Linux platform. pyodbc connects our app to Database using ODBC driver. unixODBC is a driver manager for Linux/Unix-based platform and it is required by pyodbc. Since pyodbc does not contain copy of unixODBC , hence it needs to be installed separately through Dockerfile. [<a href="https://github.com/mkleehammer/pyodbc/wiki/Install#installing-on-linux">Reference</a>]</p><p>Next, create odbc.ini file which in your same directory as Dockerfile (root directory in this solution) and add following code. This is where Microsoft’s installer for the ODBC driver registers itself. [<a href="https://github.com/mkleehammer/pyodbc/wiki/Connecting-to-SQL-Server-from-Linux">Reference</a>]</p><pre>[ODBC Driver 17 for SQL Server]<br>Description=Microsoft ODBC Driver 17 for SQL Server<br>Driver=/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.4.so.1.1<br>UsageCount=1</pre><p>Notice that we use the first line as our driver in code.</p><p>Next is to create a “System DSN”, which happens using following commands in Dockerfile</p><pre>RUN odbcinst -i -s -f /odbc.ini -l<br>RUN cat /etc/odbc.ini</pre><p>The final solution structure now looks like</p><pre>mypythonwebapp (root folder)<br>  |--src<br>      |--main.py<br>      |--repository.py<br>      |--requirements.txt<br>  |--.env<br>  |--Dockerfile<br>  |--README.MD<br>  |--odbc.ini</pre><p><strong>Note: </strong>If you use Ubuntu platform, you can use FreeTDS ODBC driver. Dockerfile needs to be updated for the same.</p><h4>#STEP 2 — Create image and container</h4><p>Start the docker desktop in background. Open a terminal in the root folder where Dockerfile is located and run this command to build the image for our app</p><pre>docker build -t todolist-app .</pre><p>Once image builds successfully, you can see it in VS code extension. Alternatively, it will show up in Docker desktop too.</p><p>Create and run the container. Since container runs in isolation and our uvicorn worker is running inside the container, we need to publish a port from the container, in order to test the APIs.</p><pre>docker run -d --name mycontainer -p 8000:8000 todolist-app</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*cgfRmWq-jcW-vZXa0rts9Q.png" /></figure><p>Open <a href="https://localhost:8000/all">https://localhost:8000/all</a> in browser and verify if the tasks are getting populated. Alternatively, test the APIs from Postman by updating the base address to localhost:8000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*izvcUPI0dsezQ2_EczVOgQ.png" /></figure><p>If you face any issue in running the container or with the APIs, see the logs by doing this —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cETY87O4s_lkTxabTGOy2Q.png" /></figure><p>This concludes our development and testing for Python app and docker container. In part 2 article, we will configure continuous deployment to Azure app service.</p><p>References:</p><ol><li><a href="https://stackoverflow.com/questions/76296702/what-is-the-correct-dockerfile-to-install-pyodbc-on-python3-10-9-slim-buster-im">https://stackoverflow.com/questions/76296702/what-is-the-correct-dockerfile-to-install-pyodbc-on-python3-10-9-slim-buster-im</a></li><li><a href="https://fastapi.tiangolo.com/deployment/docker/">https://fastapi.tiangolo.com/deployment/docker/</a></li></ol><p>Out now! Check out part 2 here</p><p><a href="https://python.plainenglish.io/deploy-a-containerized-python-app-to-azure-part-2-6442fbed2dba">Deploy a Containerized Python App to Azure (Part 2)</a></p><p><strong><em>Hope this article helped in your Python &amp; Azure journey. Please leave a comment if you have any feedback for me.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7670b687e3e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>