<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Gate of AI</title>
    <description>The latest articles on DEV Community by Gate of AI (@gateofai).</description>
    <link>https://dev.to/gateofai</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3946864%2F560259ba-40d9-4827-a857-1e8741867c9d.jpeg</url>
      <title>DEV Community: Gate of AI</title>
      <link>https://dev.to/gateofai</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/gateofai"/>
    <language>en</language>
    <item>
      <title>LLM Cost &amp;amp; API Pricing Comparison (2026 Guide)</title>
      <dc:creator>Gate of AI</dc:creator>
      <pubDate>Tue, 01 Dec 2026 18:02:12 +0000</pubDate>
      <link>https://dev.to/gateofai/llm-cost-amp-api-pricing-comparison-2026-guide-43hm</link>
      <guid>https://dev.to/gateofai/llm-cost-amp-api-pricing-comparison-2026-guide-43hm</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;🚀 Technical Briefing:&lt;/strong&gt; This tutorial is part of our deep-dive series on Agentic Workflows at &lt;a href="https://gateofai.com" rel="noopener noreferrer"&gt;Gate of AI&lt;/a&gt;. For the full technical breakdown, interactive code sandbox, and the native Arabic translation, visit the &lt;a href="https://gateofai.com/tutorial/llm-cost-comparison-api-pricing-2026/" rel="noopener noreferrer"&gt;original article here&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    🤖 AI Search Citation Summary

&amp;lt;p&amp;gt;
    &amp;lt;strong&amp;gt;Quick Answer (2026 LLM API Rates):&amp;lt;/strong&amp;gt; Frontier model API costs have diverged into two clear tiers in 2026: Ultra-efficient fast models (e.g., Gemini 2.0 Flash at $0.10/1M input tokens and DeepSeek R1 at $0.55/1M) versus flagship hybrid reasoning models (Claude 3.7 Sonnet at $3.00/1M input / $15.00/1M output, and OpenAI GPT-4o at $2.50/1M input / $10.00/1M output). Using a direct &amp;lt;strong&amp;gt;0% BYOK API Proxy &amp;amp;amp; Enterprise Vault&amp;lt;/strong&amp;gt; cuts gross SaaS markup by 40% to 65% for production agentic workloads.
&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;2026 Frontier LLM Token Pricing &amp;amp; Throughput Matrix&lt;/h2&gt;

&lt;p&gt;In modern enterprise application engineering, API cost is strictly tied to token velocity, context caching, and reasoning effort. Below is the verified live pricing comparison per 1 million tokens across top foundation models:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
    &lt;thead&gt;
        &lt;tr&gt;
            &lt;th&gt;Model &amp;amp; Provider&lt;/th&gt;
            &lt;th&gt;Input Cost / 1M&lt;/th&gt;
            &lt;th&gt;Output Cost / 1M&lt;/th&gt;
            &lt;th&gt;Context Window&lt;/th&gt;
            &lt;th&gt;Inference Speed&lt;/th&gt;
            &lt;th&gt;Ideal Enterprise Workload&lt;/th&gt;
        &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;
        &lt;tr&gt;
            &lt;td&gt;
&lt;strong&gt;Claude 3.7 Sonnet&lt;/strong&gt; (Anthropic)&lt;/td&gt;
            &lt;td&gt;$3.00&lt;/td&gt;
            &lt;td&gt;$15.00&lt;/td&gt;
            &lt;td&gt;200K Tokens&lt;/td&gt;
            &lt;td&gt;98 tok/s&lt;/td&gt;
            &lt;td&gt;Hybrid continuous reasoning &amp;amp; complex multi-file engineering&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
&lt;strong&gt;OpenAI GPT-4o&lt;/strong&gt; (OpenAI)&lt;/td&gt;
            &lt;td&gt;$2.50&lt;/td&gt;
            &lt;td&gt;$10.00&lt;/td&gt;
            &lt;td&gt;128K Tokens&lt;/td&gt;
            &lt;td&gt;115 tok/s&lt;/td&gt;
            &lt;td&gt;Multimodal document extraction, omni workflows &amp;amp; customer routing&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
&lt;strong&gt;DeepSeek R1&lt;/strong&gt; (Open Weights)&lt;/td&gt;
            &lt;td&gt;$0.55&lt;/td&gt;
            &lt;td&gt;$2.19&lt;/td&gt;
            &lt;td&gt;128K Tokens&lt;/td&gt;
            &lt;td&gt;75 tok/s&lt;/td&gt;
            &lt;td&gt;Math theorem proving, verifiable code audit &amp;amp; private cloud&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
&lt;strong&gt;Gemini 2.0 Flash&lt;/strong&gt; (Google)&lt;/td&gt;
            &lt;td&gt;$0.10&lt;/td&gt;
            &lt;td&gt;$0.40&lt;/td&gt;
            &lt;td&gt;1,000K (1M)&lt;/td&gt;
            &lt;td&gt;210 tok/s&lt;/td&gt;
            &lt;td&gt;Massive 1M RAG ingestion, continuous audio/video &amp;amp; high-volume bots&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
&lt;strong&gt;Meta Llama 3.3 70B&lt;/strong&gt; (via Groq LPUs)&lt;/td&gt;
            &lt;td&gt;$0.59&lt;/td&gt;
            &lt;td&gt;$0.79&lt;/td&gt;
            &lt;td&gt;128K Tokens&lt;/td&gt;
            &lt;td&gt;380 tok/s&lt;/td&gt;
            &lt;td&gt;Ultra-low latency conversational agents &amp;amp; classification&lt;/td&gt;
        &lt;/tr&gt;
    &lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;h3&amp;gt;Deploy Models with Zero Markup via GateOfAI BYOK Vault&amp;lt;/h3&amp;gt;
&amp;lt;p&amp;gt;Stop paying 200% enterprise SaaS wrapper margins. Connect your own Anthropic, OpenAI, or Groq API keys directly into GateOfAI Studio for autonomous pipelines.&amp;lt;/p&amp;gt;
&amp;lt;a href="/automations/"&amp;gt;Explore Autonomous Studio →&amp;lt;/a&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;Direct Head-to-Head Comparison Benchmarks&lt;/h2&gt;

&lt;p&gt;To view deep technical tradeoffs between specific model pairs, explore our verified head-to-head match-ups:&lt;/p&gt;

&lt;ul&gt;
    &lt;li&gt;&lt;a href="/compare/claude-3-7-sonnet-vs-gpt-4o/"&gt;Claude 3.7 Sonnet vs OpenAI GPT-4o Breakdown&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href="/compare/deepseek-r1-vs-o3-mini/"&gt;DeepSeek R1 vs OpenAI o3-mini Reasoning Comparison&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href="/compare/gemini-2-0-flash-vs-gpt-4o/"&gt;Gemini 2.0 Flash vs GPT-4o Token Cost Analysis&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href="/compare/deepseek-r1-vs-llama-3-3-70b/"&gt;DeepSeek R1 vs Meta Llama 3.3 70B Benchmark&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>webdev</category>
      <category>ai</category>
      <category>tutorial</category>
      <category>discuss</category>
    </item>
    <item>
      <title>Build a Durable Python AI Workflow</title>
      <dc:creator>Gate of AI</dc:creator>
      <pubDate>Sat, 21 Nov 2026 20:35:27 +0000</pubDate>
      <link>https://dev.to/gateofai/build-a-durable-python-ai-workflow-ao</link>
      <guid>https://dev.to/gateofai/build-a-durable-python-ai-workflow-ao</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;🚀 Technical Briefing:&lt;/strong&gt; This tutorial is part of our deep-dive series on Agentic Workflows at &lt;a href="https://gateofai.com" rel="noopener noreferrer"&gt;Gate of AI&lt;/a&gt;. For the full technical breakdown, interactive code sandbox, and the native Arabic translation, visit the &lt;a href="https://gateofai.com/tutorial/durable-python-ai-workflow/" rel="noopener noreferrer"&gt;original article here&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Tutorial · Python AI workflow design&lt;/strong&gt;&lt;/p&gt;

&lt;h1&gt;Build a Durable Python AI Workflow&lt;/h1&gt;

&lt;p&gt;Learn how to separate AI intent interpretation from deterministic workflow execution, persist workflow history, add human approval gates, and reason about retries and idempotency. This guide presents an implementation blueprint rather than a claim that a short SQLite example provides production-grade distributed execution.&lt;/p&gt;

&lt;h2&gt;What This Tutorial Covers&lt;/h2&gt;

&lt;p&gt;Long-running AI workflows have failure modes that a basic prompt-and-response application does not. A process can stop between steps. A request can be delivered again. A tool may succeed even though the caller never receives its response. An action may partly complete before a later action fails. For actions such as sending a message or changing a business record, blindly retrying can create duplicate side effects.&lt;/p&gt;

&lt;p&gt;The verified material identifies durable checkpoints, persisted workflow state, structured action history, approval gates, and idempotency as relevant design concerns for long-running agents. It also describes an architecture that keeps natural-language interpretation separate from deterministic workflow generation: an LLM interprets an intent, validated logic produces a reproducible DAG, and domain-authored Skills provide vocabulary mappings, constraints, and optimization knowledge.&lt;/p&gt;

&lt;p&gt;This tutorial translates those ideas into a small Python design. It uses SQLite as a simple local persistence example and an OpenAI client as an optional planning boundary. The example is not a distributed workflow engine. For workflows that must survive worker crashes, coordinate multiple workers, or reliably retry external actions, evaluate a durable execution system. Temporal and Azure Durable Functions are examples named in the verified context.&lt;/p&gt;

&lt;h2&gt;Architecture: Keep Interpretation Separate from Execution&lt;/h2&gt;

&lt;p&gt;Use three conceptual layers:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Semantic layer:&lt;/strong&gt; interpret a user's request and extract a structured intent. An LLM can assist with this step, but its output is a proposal, not authorization.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Deterministic layer:&lt;/strong&gt; validate the structured intent against application rules, produce a known workflow DAG, and control state transitions. Identical validated intents should produce identical DAGs when the rules and workflow version are unchanged.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Knowledge layer:&lt;/strong&gt; maintain domain-authored Skills containing vocabulary mappings, parameter constraints, and planning guidance. These documents inform interpretation; they do not replace validation.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Before execution, show a human-readable plan to a responsible person and allow approval or refinement. After approval, provision or prepare the required resources, record the resulting measurements or resolved estimates, and request execution approval when the workflow calls for it. This resembles the staged interaction described in the verified science-automation architecture: intent interpretation, planning, user validation, preparation, final workflow generation, and execution approval.&lt;/p&gt;

&lt;p&gt;The distinction between a DAG and an agent's free-form plan matters. A DAG is an application-controlled representation of known steps and dependencies. Do not let model-generated text become executable code, arbitrary shell commands, or unrestricted tool calls.&lt;/p&gt;

&lt;h2&gt;Step 1: Define Explicit Workflow States&lt;/h2&gt;

&lt;p&gt;Begin with a small state vocabulary. The exact statuses depend on the application, but separating planning, approval, and execution makes it easier to reason about which actions are allowed.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;from enum import StrEnum

class Status(StrEnum):
    RECEIVED = "received"
    PLANNED = "planned"
    AWAITING_APPROVAL = "awaiting_approval"
    APPROVED = "approved"
    RUNNING = "running"
    COMPLETED = "completed"
    FAILED = "failed"
    REJECTED = "rejected"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Model a workflow run as a durable record containing a stable run identifier, an idempotency key, the validated intent, the workflow definition or version, the current status, and timestamps. Keep action attempts and action outcomes in a structured history rather than relying on console output. A history should help answer what ran, when it ran, and what result was recorded.&lt;/p&gt;

&lt;p&gt;Do not infer that a status field alone makes a workflow durable. State updates must be persisted at meaningful boundaries, and the executor must be designed for interruption and repeat delivery. In a production system, define and test the permitted transitions. For example, a rejected run must not proceed to execution, and a completed run must not silently start over.&lt;/p&gt;

&lt;h2&gt;Step 2: Persist Runs and Events in SQLite for a Local Prototype&lt;/h2&gt;

&lt;p&gt;SQLite can demonstrate persistence in a single-process prototype. Keep the run record separate from its event history so a developer can inspect state changes. Use parameterized SQL and a unique constraint on the idempotency key. The following schema is a minimal starting point, not a replacement for a production migration or concurrency strategy.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import sqlite3

SCHEMA = """
CREATE TABLE IF NOT EXISTS runs (
    run_id TEXT PRIMARY KEY,
    idempotency_key TEXT NOT NULL UNIQUE,
    status TEXT NOT NULL,
    workflow_json TEXT NOT NULL,
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS events (
    event_id INTEGER PRIMARY KEY AUTOINCREMENT,
    run_id TEXT NOT NULL REFERENCES runs(run_id),
    event_type TEXT NOT NULL,
    event_json TEXT NOT NULL,
    created_at TEXT NOT NULL
);
"""

def initialize_database(path: str) -&amp;gt; None:
    with sqlite3.connect(path) as db:
        db.execute("PRAGMA foreign_keys = ON")
        db.executescript(SCHEMA)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When accepting a request, create the run and its initial event in one database transaction. If the same idempotency key is submitted again, return the existing run rather than creating a second logical workflow. A unique constraint is important because checking for a key and inserting later, without a constraint, can allow concurrent submissions to race.&lt;/p&gt;

&lt;p&gt;For a production service with multiple workers, a local SQLite database may not be the right coordination mechanism. Choose storage and transaction behavior based on the deployment, then test concurrent updates and recovery. The verified context discusses durable checkpoints and workflow state but does not establish that this particular SQLite schema is sufficient for distributed execution.&lt;/p&gt;

&lt;h2&gt;Step 3: Treat the LLM Response as Untrusted Intent&lt;/h2&gt;

&lt;p&gt;Ask the model for a structured intent, not an executable workflow. Validate its output in application code against a finite schema: recognized intent types, bounded parameter values, and a known set of action names. Reject missing required fields and unsupported actions. Keep authorization and policy decisions outside the model response.&lt;/p&gt;

&lt;p&gt;If using the OpenAI Python SDK, use the current client-based interface and consult the SDK documentation for the installed version. Do not assume a specific model name or response capability without checking current provider documentation and account access. The verified context does not identify a model, model availability, pricing, or API response format.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;from pydantic import BaseModel, Field

class Intent(BaseModel):
    category: str = Field(min_length=1, max_length=80)
    summary: str = Field(min_length=1, max_length=500)
    parameters: dict[str, str | int | bool] = Field(default_factory=dict)

ALLOWED_CATEGORIES = {
    "reporting",
    "customer_communication",
    "access_change",
    "data_change",
}

def validate_intent(candidate: dict) -&amp;gt; Intent:
    intent = Intent.model_validate(candidate)
    if intent.category not in ALLOWED_CATEGORIES:
        raise ValueError("unsupported intent category")
    return intent
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is only a structural example. Production validation should be specific to the domain and should reject unknown parameters where appropriate. A model's statement that an action is safe is not a policy decision. The deterministic layer should decide which workflow template applies and whether human review is required.&lt;/p&gt;

&lt;h2&gt;Step 4: Generate a Deterministic Workflow and Add Approval&lt;/h2&gt;

&lt;p&gt;Map validated intent to application-owned steps. For example, a reporting intent might map to prepare-inputs, generate-report, and record-result. A customer communication intent could map to draft-message, request-review, and send-after-approval. The example names are illustrative; they do not establish integration with any particular provider.&lt;/p&gt;

&lt;p&gt;Store the workflow version along with the run. If a workflow definition changes later, a resumed run should not accidentally reinterpret an old plan using new rules. Generate a human-readable plan from the same validated representation that drives the DAG, then pause before sensitive or externally visible actions. Record the approver's decision and the point in the workflow at which it applies.&lt;/p&gt;

&lt;p&gt;An approval gate is meaningful only if the execution path enforces it. Check the persisted state immediately before carrying out the gated action. Do not rely on a user interface to hide an execute button, or on the LLM to respect an approval instruction. For higher-risk actions, use approval rules appropriate to the action and organization; the verified context supports the general concept of approval gates but does not prescribe a particular policy.&lt;/p&gt;

&lt;h2&gt;Step 5: Make Retries and Side Effects Idempotent&lt;/h2&gt;

&lt;p&gt;Retries are necessary when transient failures occur, but a retry is not automatically safe. Suppose a remote service accepts a request and the workflow process stops before recording success. On recovery, the system may not know whether the action happened. Sending the same request again can duplicate a side effect.&lt;/p&gt;

&lt;p&gt;Assign a stable idempotency key to each logical action, derived from the workflow run and action identity. Pass it to the external service when that service supports idempotency. Otherwise, maintain a durable action record and use a provider lookup or reconciliation procedure before repeating an uncertain operation. Record attempts, responses, and errors as structured events. Treat partial completion as its own recovery case rather than retrying every step indiscriminately.&lt;/p&gt;

&lt;p&gt;A local append-only JSONL file is useful for a demonstration, but it cannot by itself guarantee exactly-once behavior across a crash and an external service. Nor does recording a workflow checkpoint atomically with a third-party action become possible merely by using SQLite. Design for duplicate delivery and uncertain outcomes. The verified context specifically highlights retries, partial failures, duplicate side effects, durable checkpoints, and action history as reliability concerns.&lt;/p&gt;

&lt;h2&gt;Step 6: Recover Runs and Inspect Their History&lt;/h2&gt;

&lt;p&gt;On startup, identify runs left in an in-progress state and apply an explicit recovery policy. Depending on the step, recovery may resume from a durable checkpoint, reconcile an external action, wait for a person, or mark the run for manual investigation. Do not convert every interrupted run into an automatic retry.&lt;/p&gt;

&lt;p&gt;Expose an event history with clear event types such as request received, intent validated, plan presented, approval granted, action started, action outcome recorded, and run completed. Avoid logging secrets or unrestricted personal data. Add tracing and guardrails appropriate to the application; the verified context specifically points to tracing and guardrails as useful concerns and names the OpenAI Agents SDK as one possible tool. That mention should not be read as a requirement or as proof that it supplies a particular durability guarantee.&lt;/p&gt;

&lt;p&gt;For longer-running, multi-step agents, consider a durable workflow engine instead of expanding a custom state machine indefinitely. The verified context names Temporal and Azure Durable Functions as examples. Compare their documented execution, persistence, retry, and operational behavior against your requirements before selecting one.&lt;/p&gt;

&lt;h2&gt;Step 7: Test Failure Paths, Not Just the Happy Path&lt;/h2&gt;

&lt;p&gt;Write tests for the properties your workflow must preserve. At minimum, verify that duplicate submission with the same key returns the same logical run; a rejected run cannot execute; a gated action waits for approval; and repeating a completed action does not create a duplicate result where the executor can enforce that behavior.&lt;/p&gt;

&lt;p&gt;Also simulate a worker stopping after an external action but before its outcome is recorded. Verify that recovery reconciles the uncertain result rather than blindly repeating it. Test partial completion, transient provider errors, invalid model output, duplicate event delivery, and an approval decision arriving after the run has changed state. These are design checks, not claims that the illustrative schema above already handles every case.&lt;/p&gt;

&lt;h2&gt;Practical Checklist&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Use an LLM to interpret requests, not to grant permission.&lt;/li&gt;
&lt;li&gt;Validate intent and generate known workflow steps deterministically.&lt;/li&gt;
&lt;li&gt;Use domain-authored Skills to encode vocabulary and constraints where appropriate.&lt;/li&gt;
&lt;li&gt;Persist run state, checkpoints, and structured action history.&lt;/li&gt;
&lt;li&gt;Insert human validation and approval before actions that require it.&lt;/li&gt;
&lt;li&gt;Use stable idempotency keys and reconcile uncertain outcomes before retrying.&lt;/li&gt;
&lt;li&gt;Choose a durable execution system when the workflow's concurrency and recovery needs exceed a local prototype.&lt;/li&gt;
&lt;li&gt;Test crashes, duplicate deliveries, and partial failures before connecting real external actions.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;A dependable AI workflow is not just a prompt followed by a tool call. It separates semantic interpretation from deterministic execution, stores enough state to understand and resume work, and treats human approval and idempotency as explicit workflow concerns. A small Python and SQLite prototype can make those boundaries visible, but it should not be mistaken for a distributed exactly-once system.&lt;/p&gt;

&lt;p&gt;For long-running automation, build around durable checkpoints, structured action history, careful recovery, and controls that prevent a model from directly authorizing side effects. Select an execution engine and storage design only after defining the failure modes and guarantees the application actually requires.&lt;/p&gt;

&lt;h2&gt;Sources and Scope&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;arXiv: “Leveraging Agentic AI for Science Automation” — semantic, deterministic, and knowledge layers; Skills; human validation; and reproducible DAG generation.&lt;/li&gt;
&lt;li&gt;Verified agent-workflow context — durable checkpoints, persisted state, action history, retries, approval gates, and idempotency concerns; Temporal and Azure Durable Functions examples.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>webdev</category>
      <category>ai</category>
      <category>tutorial</category>
      <category>discuss</category>
    </item>
    <item>
      <title>Next.js App Router and OpenAI Chat Guide</title>
      <dc:creator>Gate of AI</dc:creator>
      <pubDate>Fri, 20 Nov 2026 18:11:54 +0000</pubDate>
      <link>https://dev.to/gateofai/nextjs-app-router-and-openai-chat-guide-4h9m</link>
      <guid>https://dev.to/gateofai/nextjs-app-router-and-openai-chat-guide-4h9m</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;🚀 Technical Briefing:&lt;/strong&gt; This tutorial is part of our deep-dive series on Agentic Workflows at &lt;a href="https://gateofai.com" rel="noopener noreferrer"&gt;Gate of AI&lt;/a&gt;. For the full technical breakdown, interactive code sandbox, and the native Arabic translation, visit the &lt;a href="https://gateofai.com/tutorial/nextjs-app-router-openai-chat-guide/" rel="noopener noreferrer"&gt;original article here&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;p&amp;gt;Technical guide&amp;lt;/p&amp;gt;
&amp;lt;h1&amp;gt;Next.js App Router and OpenAI: What the Verified Sources Support&amp;lt;/h1&amp;gt;
&amp;lt;p&amp;gt;This article reviews the verified building blocks relevant to a Next.js and OpenAI chat application. The available sources support basic App Router structure, the distinction between Server and Client Components, and a current OpenAI Python client example. They do not verify a complete streaming implementation, an OpenAI JavaScript integration, SSE behavior, or deployment-specific production guarantees. Those gaps matter: code should not be described as production-ready when its critical behavior has not been checked against authoritative documentation.&amp;lt;/p&amp;gt;



&amp;lt;h2&amp;gt;Scope and verification notes&amp;lt;/h2&amp;gt;
&amp;lt;p&amp;gt;A chat application that connects a browser interface to a model provider has several separate concerns: routing, user interaction, provider requests, response delivery, error handling, and deployment. The sources supplied for this review cover only a subset of those concerns. They explain the general Next.js App Router model and show that an OpenAI-compatible chat-completions request can be made using the modern Python client. They do not document the specific Next.js streaming route, JavaScript SDK call, SSE protocol, proxy behavior, cancellation flow, rate limiter, or hosting duration used in the draft.&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;Consequently, this is a source-bounded guide rather than a runnable, production-ready streaming application. It distinguishes verified framework concepts from details that still require primary-source checking. That boundary is essential for technical publishing: familiar patterns are not proof that a particular code sample compiles, behaves correctly under disconnects, or is supported by a deployment platform.&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;The verified beginner guide says that folders inside &amp;lt;code&amp;gt;src/app/&amp;lt;/code&amp;gt; represent routes, that &amp;lt;code&amp;gt;page.tsx&amp;lt;/code&amp;gt; supplies a page, and that layout files can hold shared UI. It also states that App Router components are Server Components by default, and that browser interaction such as event handlers, state, or effects requires a Client Component marked with &amp;lt;code&amp;gt;"use client"&amp;lt;/code&amp;gt;. These are the framework facts used below.&amp;lt;/p&amp;gt;



&amp;lt;h2&amp;gt;Step 1: Understand the App Router structure&amp;lt;/h2&amp;gt;
&amp;lt;p&amp;gt;In the App Router, the directory tree under &amp;lt;code&amp;gt;src/app/&amp;lt;/code&amp;gt; expresses the application’s routes. A route’s &amp;lt;code&amp;gt;page.tsx&amp;lt;/code&amp;gt; file provides its page, while layout files can provide UI shared across pages. This gives a new project a predictable place to organize its interface and route-specific code.&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;The source describes creating a project with the Next.js project generator and configuring TypeScript, Tailwind CSS, and the App Router. It lists Node.js 18 or newer among its prerequisites. These are facts about the supplied beginner guide, not a guarantee that every later dependency or deployment target will support the same minimum runtime. Check the current requirements for the exact Next.js release and hosting environment selected for a real application.&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;A useful initial exercise is to create a small page and identify which files define the route and which components are shared. Keep the initial scope simple. Before adding an AI provider or a streaming transport, make sure the framework structure is clear and the app builds with the versions you intend to use.&amp;lt;/p&amp;gt;
&amp;lt;pre&amp;gt;&amp;lt;code&amp;gt;npx create-next-app@latest streaming-ai-chat&amp;lt;/code&amp;gt;&amp;lt;/pre&amp;gt;
&amp;lt;p&amp;gt;The supplied source confirms use of the Next.js project generator, but it does not prescribe every command-line option for a current release. Follow the prompts for the configuration you want, including the App Router and TypeScript if they are offered. Because setup options may change, do not rely on an old command line without checking the generator’s current help or documentation.&amp;lt;/p&amp;gt;



&amp;lt;h2&amp;gt;Step 2: Separate server and browser responsibilities&amp;lt;/h2&amp;gt;
&amp;lt;p&amp;gt;App Router components are Server Components by default, according to the verified Next.js guide. A component that needs browser interaction—for example, event handlers, state, or effects—should be a Client Component and include the &amp;lt;code&amp;gt;"use client"&amp;lt;/code&amp;gt; directive. This distinction helps determine where interface interaction belongs.&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;For a chat interface, the text field and submit interaction are browser-facing behaviors. The verified context supports the general rule that components requiring those interactions need the client directive. It does not, however, establish how a particular application should protect provider credentials, authenticate visitors, validate requests, or connect the client to a server route. Those are important design questions, but the supplied sources do not provide enough evidence to prescribe an implementation here.&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;Do not confuse the framework’s component boundary with a complete security design. A Server Component is not, by itself, proof that every secret is handled safely; nor does the verified source define a full credential-management policy. Before shipping a provider-backed application, consult current official documentation for the framework, provider SDK, hosting service, and any authentication system in use.&amp;lt;/p&amp;gt;



&amp;lt;h2&amp;gt;Step 3: Know what the OpenAI example demonstrates&amp;lt;/h2&amp;gt;
&amp;lt;p&amp;gt;The verified context includes an OpenAI-compatible chat-completions example written in Python. It imports the modern client, creates an instance, and calls &amp;lt;code&amp;gt;client.chat.completions.create()&amp;lt;/code&amp;gt;. The example demonstrates the general shape of a current client call using a model name, a messages list, and a user message. It does not establish the exact model availability, price, account permissions, or JavaScript SDK behavior for a particular project.&amp;lt;/p&amp;gt;
&amp;lt;pre&amp;gt;&amp;lt;code&amp;gt;import os
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;from openai import OpenAI&lt;/p&gt;

&lt;p&gt;client = OpenAI(&lt;br&gt;
    base_url="&lt;a href="https://router.huggingface.co/v1" rel="noopener noreferrer"&gt;https://router.huggingface.co/v1&lt;/a&gt;",&lt;br&gt;
    api_key=os.environ["HF_TOKEN"],&lt;br&gt;
)&lt;/p&gt;

&lt;p&gt;completion = client.chat.completions.create(&lt;br&gt;
    model="openai/gpt-oss-120b:cerebras",&lt;br&gt;
    messages=[&lt;br&gt;
        {&lt;br&gt;
            "role": "user",&lt;br&gt;
            "content": "How many rs are in the word 'strawberry'?",&lt;br&gt;
        }&lt;br&gt;
    ],&lt;br&gt;
)&lt;/p&gt;

&lt;p&gt;print(completion.choices[0].message)&lt;br&gt;
    &lt;/p&gt;
&lt;p&gt;This example is specifically described in the supplied context as a request through Hugging Face Inference Providers using an OpenAI-compatible interface and a Cerebras provider route. It uses &lt;code&gt;HF_TOKEN&lt;/code&gt;; it is not an example of an OpenAI API key, Next.js, browser-side code, or streaming output. Keep that distinction explicit when adapting it. An OpenAI-compatible interface does not mean that every provider, model, parameter, or response behavior is identical.&lt;/p&gt;
&lt;br&gt;
    &lt;p&gt;The example is useful as a reference for the modern Python client style, but it is not a substitute for the JavaScript SDK documentation needed by a Next.js implementation. This verified context does not contain a JavaScript SDK example. Therefore, a tutorial based only on these sources should not invent a JavaScript import, model identifier, streaming iterator, or error-handling pattern.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;h2&amp;gt;Step 4: Treat streaming as an unverified requirement&amp;lt;/h2&amp;gt;
&amp;lt;p&amp;gt;The draft describes Server-Sent Events, incremental token delivery, heartbeat messages, cancellation, and response buffering. None of the supplied sources verifies those details for a Next.js Route Handler or an OpenAI JavaScript client. The source set also does not establish that a particular host supports the proposed maximum duration or that a proxy will pass events through without buffering.&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;For that reason, this article does not provide a replacement SSE implementation. A plausible-looking stream loop is not enough to demonstrate correctness. A publishable implementation needs current primary documentation for the response format, stream iteration, client disconnect behavior, error handling, and the exact runtime and host configuration. It should then be tested with the actual dependency versions and deployment target.&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;The draft’s code also has formatting problems that would need correction before testing. In several places the intended newline separators appear as literal letter “n” characters, including the SSE frame construction and the client-side line splitting. The curl examples are split across lines without shell continuation characters. As written, those snippets should not be represented as verified, runnable examples. Correcting their syntax alone would still not verify the architecture or its behavior.&amp;lt;/p&amp;gt;



&amp;lt;h2&amp;gt;Step 5: Verify the complete implementation before calling it production-ready&amp;lt;/h2&amp;gt;
&amp;lt;p&amp;gt;A responsible review should check the exact framework and SDK versions, run the application, inspect the generated and returned data, and test the intended deployment environment. For a streaming feature, testing only a local page is insufficient evidence for hosting behavior. The supplied sources do not specify a test suite or production checklist, so the following are verification questions—not claims that the draft’s implementation already passes them:&amp;lt;/p&amp;gt;
&amp;lt;ul&amp;gt;
  &amp;lt;li&amp;gt;Does the selected Next.js version support the route and runtime APIs used by the code?&amp;lt;/li&amp;gt;
  &amp;lt;li&amp;gt;Does the installed JavaScript SDK document the exact request and streaming pattern?&amp;lt;/li&amp;gt;
  &amp;lt;li&amp;gt;Do provider credentials remain outside browser-delivered code?&amp;lt;/li&amp;gt;
  &amp;lt;li&amp;gt;Does the client handle partial network reads and a connection that ends unexpectedly?&amp;lt;/li&amp;gt;
  &amp;lt;li&amp;gt;Does cancellation stop the work that the application intends to stop?&amp;lt;/li&amp;gt;
  &amp;lt;li&amp;gt;Do the chosen hosting service and any proxy support the required response duration and progressive delivery?&amp;lt;/li&amp;gt;
  &amp;lt;li&amp;gt;Have malformed requests, provider errors, and deployment configuration failures been tested?&amp;lt;/li&amp;gt;
&amp;lt;/ul&amp;gt;
&amp;lt;p&amp;gt;These questions identify work that must be completed with suitable primary sources and project-specific tests. They are deliberately not presented as verified capabilities of the draft. In particular, details about rate limiting, trusted proxy headers, distributed storage, budgets, observability products, retention, or regional compliance require separate evidence and an implementation review.&amp;lt;/p&amp;gt;



&amp;lt;h2&amp;gt;What the sources establish—and what they do not&amp;lt;/h2&amp;gt;
&amp;lt;p&amp;gt;The verified material establishes three limited points relevant to this topic. First, Next.js App Router routes are organized through folders under &amp;lt;code&amp;gt;src/app/&amp;lt;/code&amp;gt;, with &amp;lt;code&amp;gt;page.tsx&amp;lt;/code&amp;gt; supplying a page and layout files supporting shared UI. Second, App Router components are Server Components by default, while browser-interactive components use &amp;lt;code&amp;gt;"use client"&amp;lt;/code&amp;gt;. Third, a supplied Python example uses the modern OpenAI client interface to make an OpenAI-compatible chat-completions request through Hugging Face Inference Providers.&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;The material does not establish that the draft’s proposed application compiles, that its SSE framing is valid as printed, that its abort flow propagates as claimed, or that its limits and deployment settings are supported. It also does not establish current model access or pricing. Those claims should be removed or verified against authoritative, current sources before publication.&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;A useful next step is to obtain official documentation for the precise versions of Next.js and the OpenAI JavaScript SDK, then build and test a minimal implementation from those sources. Only after validating the request contract, stream format, failure cases, cancellation behavior, and deployment target should the tutorial describe itself as a production-ready streaming chat. Until then, the accurate editorial position is narrower: the verified context provides introductory App Router concepts and an OpenAI-compatible Python request example, not a complete Next.js streaming system.&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

</description>
      <category>webdev</category>
      <category>ai</category>
      <category>tutorial</category>
      <category>discuss</category>
    </item>
    <item>
      <title>Qwen LoRA Fine-Tuning with Hugging Face PEFT</title>
      <dc:creator>Gate of AI</dc:creator>
      <pubDate>Fri, 20 Nov 2026 18:11:34 +0000</pubDate>
      <link>https://dev.to/gateofai/qwen-lora-fine-tuning-with-hugging-face-peft-5fd1</link>
      <guid>https://dev.to/gateofai/qwen-lora-fine-tuning-with-hugging-face-peft-5fd1</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;🚀 Technical Briefing:&lt;/strong&gt; This tutorial is part of our deep-dive series on Agentic Workflows at &lt;a href="https://gateofai.com" rel="noopener noreferrer"&gt;Gate of AI&lt;/a&gt;. For the full technical breakdown, interactive code sandbox, and the native Arabic translation, visit the &lt;a href="https://gateofai.com/tutorial/qwen-lora-fine-tuning-hugging-face-peft/" rel="noopener noreferrer"&gt;original article here&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Advanced tutorial&lt;/p&gt;

&lt;h1&gt;Qwen LoRA Fine-Tuning with Hugging Face PEFT&lt;/h1&gt;

&lt;p&gt;This guide explains the verified core workflow for parameter-efficient fine-tuning with Hugging Face PEFT: define a LoRA configuration, attach it to a base model, and train the adapter parameters rather than updating every base-model parameter. It also clarifies which implementation details are examples and which require validation for a particular model, dataset, and training environment.&lt;/p&gt;

&lt;h2&gt;What This Tutorial Covers&lt;/h2&gt;

&lt;p&gt;Low-Rank Adaptation, or LoRA, is a parameter-efficient fine-tuning method. Instead of updating all parameters of a pretrained model, LoRA introduces trainable adapter parameters into selected model components. Hugging Face PEFT provides a configuration-driven workflow for applying this adaptation. In the basic flow, you create a PEFT configuration, pass the base model and configuration to &lt;code&gt;get_peft_model&lt;/code&gt;, and train the resulting PEFT model.&lt;/p&gt;

&lt;p&gt;The key practical distinction is between the base model and the parameters introduced for adaptation. The PEFT workflow described in the verified Hugging Face material freezes the original linear-layer parameters for training and makes the LoRA-specific parameters trainable. This can reduce the number of parameters that need to be updated compared with full fine-tuning. The exact memory use, training speed, and quality depend on the model, configuration, data, and runtime; the available source material does not establish universal performance figures.&lt;/p&gt;

&lt;p&gt;This article focuses on the PEFT and LoRA configuration path, not a complete production deployment. The available verified context does not validate a particular dataset validator, GPU requirement, complete training script, evaluation threshold, or deployment architecture. Treat those as project-specific work that must be designed and tested for your environment, rather than as guaranteed properties of PEFT.&lt;/p&gt;

&lt;h2&gt;Step 1: Understand the PEFT LoRA Workflow&lt;/h2&gt;

&lt;p&gt;PEFT separates the adaptation method’s settings from the model itself. For LoRA, a &lt;code&gt;LoraConfig&lt;/code&gt; records how the adapter should be applied. The verified workflow example includes settings such as rank, alpha, dropout, target modules, and the PEFT method. You then use &lt;code&gt;get_peft_model&lt;/code&gt; to create a PEFT model from the base model and that configuration.&lt;/p&gt;

&lt;p&gt;Conceptually, the sequence is:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Load or define a base model using the appropriate model library.&lt;/li&gt;
&lt;li&gt;Choose a PEFT configuration for the desired adaptation method.&lt;/li&gt;
&lt;li&gt;Wrap the base model with &lt;code&gt;get_peft_model&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Train the trainable adapter parameters with a training process appropriate to the task.&lt;/li&gt;
&lt;li&gt;Save and evaluate the resulting adapter using a workflow verified for your model and software versions.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The verified PEFT workflow source directly supports the configuration and model-wrapping steps. The choice of model loader, dataset format, trainer, optimizer, checkpoint policy, and evaluation criteria must be determined for the specific project. Do not assume that a configuration example alone constitutes a production pipeline.&lt;/p&gt;

&lt;h2&gt;Step 2: Choose LoRA Configuration Values&lt;/h2&gt;

&lt;p&gt;LoRA configuration values control aspects of the adapter. The rank, commonly represented by &lt;code&gt;r&lt;/code&gt;, is one such setting. The verified Hugging Face fine-tuning example uses &lt;code&gt;r=8&lt;/code&gt;, &lt;code&gt;lora_alpha=16&lt;/code&gt;, and &lt;code&gt;lora_dropout=0.05&lt;/code&gt;. A separate verified research appendix reports LoRA settings with a dropout of 0.05, alpha of 16, and target modules &lt;code&gt;q_proj&lt;/code&gt; and &lt;code&gt;v_proj&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;These are examples from their respective sources, not a universal recipe. In particular, a configuration used in one model or experiment should not automatically be copied to another. Verify that your model exposes the selected module names, and evaluate candidate settings with a representative dataset. The available context does not establish that one rank, alpha, dropout, or target-module combination is best for every Qwen model or task.&lt;/p&gt;

&lt;p&gt;A basic configuration pattern, drawn from the verified PEFT workflow, looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;from peft import LoraConfig, PeftType

config = LoraConfig(
    inference_mode=False,
    r=1,
    lora_alpha=4,
    lora_dropout=0.1,
    target_modules=["linear"],
    peft_type=PeftType.LORA,
)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This small example uses a generic module name and illustrative values from a PEFT workflow article. It is a demonstration of the configuration structure, not a Qwen-specific configuration. For an actual transformer, the target module names must match modules in that model. The verified research appendix provides &lt;code&gt;q_proj&lt;/code&gt; and &lt;code&gt;v_proj&lt;/code&gt; as example targets; confirm model compatibility before using them.&lt;/p&gt;

&lt;p&gt;The fine-tuning example in the verified Hugging Face source shows another configuration pattern:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;from peft import LoraConfig

config = LoraConfig(
    r=8,
    lora_alpha=16,
    bias="none",
    lora_dropout=0.05,
    task_type="CAUSAL_LM",
    target_modules=["q_proj", "v_proj"],
)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That example demonstrates a causal-language-model configuration and those target modules in the source’s own context. Before adapting it, check your model’s module names and task requirements. The context does not verify that this exact configuration is suitable for every Qwen release.&lt;/p&gt;

&lt;h2&gt;Step 3: Attach the Adapter to a Base Model&lt;/h2&gt;

&lt;p&gt;Once you have a base model and a suitable configuration, PEFT’s &lt;code&gt;get_peft_model&lt;/code&gt; function creates the PEFT model. The verified workflow describes this as the point at which LoRA-specific parameters are introduced and the original base linear-layer parameters cease to be trainable in that example.&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;from peft import get_peft_model

&lt;p&gt;peft_model = get_peft_model(base_model, config)&lt;/p&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;code&gt;

&lt;p&gt;The first two lines illustrate the verified model-wrapping API. The parameter-reporting call is shown in the verified fine-tuning material as a way to inspect the trainable parameter count. Use it to confirm that your model has trainable adapter parameters after wrapping. The count and percentage are model- and configuration-dependent; do not assume a particular percentage without measuring it.&lt;/p&gt;

&lt;p&gt;Before training, inspect the wrapped model and confirm that the intended modules received adapters. This is particularly important when adapting a model family whose layer names differ from another family. If the configured target names do not match the model architecture, the intended adaptation may not be applied. The supplied sources provide configuration examples, but they do not supply a complete inventory of Qwen module names for every version.&lt;/p&gt;

&lt;/code&gt;&lt;code&gt;

&lt;h2&gt;Step 4: Select a Training Stack Deliberately&lt;/h2&gt;

&lt;p&gt;The verified research appendix identifies components of the Hugging Face ecosystem used in fine-tuning workflows: Transformers for model loading, tokenization, and generation; PEFT for LoRA adapters and adapter save/load; TRL’s &lt;code&gt;SFTTrainer&lt;/code&gt; and &lt;code&gt;SFTConfig&lt;/code&gt; in one workflow; and Datasets for data handling. Another reported experiment used the Hugging Face Trainer API directly rather than TRL’s SFT trainer. These examples show that the ecosystem supports more than one training path; they do not establish that one trainer is required for every project.&lt;/p&gt;

&lt;p&gt;Choose a trainer based on the task and the version-compatible documentation for the model and libraries you use. Keep the distinction between a library being present in a reported software stack and a specific training recipe being validated for your use case. In particular, the available sources do not provide a complete, tested Qwen training script with a prescribed dataset schema, batching strategy, precision mode, hardware minimum, or checkpoint policy.&lt;/p&gt;

&lt;p&gt;If you use supervised fine-tuning, define the training examples and expected response behavior before running training. Review example quality and ensure that the data represents the task you want to teach. The supplied context confirms relevant libraries and PEFT mechanics, but it does not specify data-governance requirements or a universal data-validation procedure. Those controls should be developed for the project’s data and applicable requirements.&lt;/p&gt;

&lt;h2&gt;Step 5: Treat Qwen Results and Research Settings Carefully&lt;/h2&gt;

&lt;p&gt;The verified research context names &lt;code&gt;Qwen/Qwen2.5-7B-Instruct&lt;/code&gt; as an evaluation base in a study that separates the training base from the instruct model used for evaluation. It also describes a LoRA experimental configuration in an appendix. This is evidence that Qwen2.5-7B-Instruct appears in that research setup; it is not a validated, general-purpose Qwen fine-tuning recipe.&lt;/p&gt;

&lt;p&gt;The study describes using Transformers and PEFT, and reports other components and procedures for its own experiments. Its model selection, corpus, hyperparameters, and evaluation design belong to that study. Do not transfer its results to a different dataset, model checkpoint, prompt format, or business task without independent evaluation.&lt;/p&gt;

&lt;p&gt;When planning a Qwen experiment, record the exact model identifier and revision, PEFT configuration, target modules, training data version, trainer, and evaluation method. The supplied context does not prescribe a run-manifest format, but recording these choices helps make experiments understandable and repeatable. Verify model access, tokenizer behavior, and installed library compatibility against the authoritative documentation for the exact versions you select.&lt;/p&gt;

&lt;h2&gt;Step 6: Evaluate the Adapter, Not Just the Training Run&lt;/h2&gt;

&lt;p&gt;A successful call to &lt;code&gt;get_peft_model&lt;/code&gt; proves that the adapter was attached; it does not prove that the resulting model is useful. Evaluate the adapted model on data that reflects the intended task. Compare its outputs with the base model and review representative examples. The verified context identifies evaluation practices in a research setting, including evaluation with a Qwen instruct model, but it does not provide a universal benchmark or release threshold for a production application.&lt;/p&gt;

&lt;p&gt;Choose evaluation criteria that match the application. For example, an application with a strict output format should check whether that format is followed. A task involving domain-specific answers should assess correctness against trusted references. The appropriate checks depend on the task and cannot be inferred from LoRA configuration values alone.&lt;/p&gt;

&lt;p&gt;Do not treat training loss or a single aggregate score as proof of quality. Inspect individual failures, compare the adapted and base model, and determine whether the adapter improved the target behavior without creating unacceptable regressions. The available verified context does not establish a particular metric, target score, or safety evaluation suite, so define and document those for your own application.&lt;/p&gt;

&lt;h2&gt;Common Mistakes to Avoid&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Copying a configuration without checking module names.&lt;/strong&gt; The sources show example targets, including &lt;code&gt;q_proj&lt;/code&gt; and &lt;code&gt;v_proj&lt;/code&gt;, but do not establish that every model uses those names.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Treating example hyperparameters as universal defaults.&lt;/strong&gt; The cited rank, alpha, and dropout values are examples from particular workflows and experiments.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Assuming that attaching an adapter completes a production pipeline.&lt;/strong&gt; PEFT configuration and wrapping are only parts of an end-to-end training and release process.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Confusing an evaluation model with a training prescription.&lt;/strong&gt; A Qwen instruct model used for evaluation in a study does not by itself validate a separate training recipe.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Reporting unmeasured savings or quality improvements.&lt;/strong&gt; The context supports parameter-efficient adaptation as a method, but does not substantiate a specific memory reduction, speedup, or task-quality guarantee for your run.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Practical Checklist&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Select the exact base model and verify its architecture and module names.&lt;/li&gt;
&lt;li&gt;Choose a LoRA configuration appropriate to that model and task.&lt;/li&gt;
&lt;li&gt;Apply the configuration with &lt;code&gt;get_peft_model&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Inspect the resulting model and confirm that adapter parameters are trainable.&lt;/li&gt;
&lt;li&gt;Select a compatible training stack, such as a Transformers-based workflow with PEFT and, where appropriate, TRL or Datasets.&lt;/li&gt;
&lt;li&gt;Train with reviewed task data and an explicitly chosen evaluation process.&lt;/li&gt;
&lt;li&gt;Assess generated outputs against task-specific requirements before considering deployment.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This checklist is a concise summary of the workflow and ecosystem supported by the verified context. It is not a substitute for model-specific documentation or a validated deployment plan.&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Hugging Face PEFT provides a straightforward core pattern for LoRA adaptation: define a &lt;code&gt;LoraConfig&lt;/code&gt;, attach it to a base model with &lt;code&gt;get_peft_model&lt;/code&gt;, and train the adapter parameters. Verified examples demonstrate different configuration values and show Transformers, PEFT, TRL, and Datasets in fine-tuning workflows. The correct settings depend on the model and task, and a research configuration should not be presented as a universal Qwen recipe.&lt;/p&gt;

&lt;p&gt;For Qwen, the supplied research context identifies Qwen2.5-7B-Instruct in an evaluation setup. Use that fact narrowly. Confirm model-specific module names, select compatible training tools, and evaluate your own adapter on representative data. A reliable fine-tuning effort depends on those project-specific choices as much as on the LoRA configuration itself.&lt;/p&gt;

&lt;p&gt;Editorial attribution: Gate of AI Editorial &amp;amp; Engineering Teams, GateOfAI, LLC.&lt;/p&gt;

&lt;/code&gt;

</description>
      <category>webdev</category>
      <category>ai</category>
      <category>tutorial</category>
      <category>discuss</category>
    </item>
    <item>
      <title>Build a FastAPI Prompt Contract Service</title>
      <dc:creator>Gate of AI</dc:creator>
      <pubDate>Tue, 17 Nov 2026 17:55:35 +0000</pubDate>
      <link>https://dev.to/gateofai/build-a-fastapi-prompt-contract-service-2e03</link>
      <guid>https://dev.to/gateofai/build-a-fastapi-prompt-contract-service-2e03</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;🚀 Technical Briefing:&lt;/strong&gt; This tutorial is part of our deep-dive series on Agentic Workflows at &lt;a href="https://gateofai.com" rel="noopener noreferrer"&gt;Gate of AI&lt;/a&gt;. For the full technical breakdown, interactive code sandbox, and the native Arabic translation, visit the &lt;a href="https://gateofai.com/tutorial/fastapi-prompt-contract-service/" rel="noopener noreferrer"&gt;original article here&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Tutorial&lt;/strong&gt; · Intermediate&lt;/p&gt;

&lt;h1&gt;Build a Prompt Contract Service with FastAPI&lt;/h1&gt;

&lt;p&gt;Learn how to design a FastAPI service around a versioned prompt contract and OpenAI Structured Outputs. The key principle is that a schema constrains an answer’s shape; your application must still check its meaning, handle refusals and incomplete responses, and authorize any requested action.&lt;/p&gt;

&lt;h2&gt;What Is a Prompt Contract Service?&lt;/h2&gt;

&lt;p&gt;A conventional API contract describes the inputs and outputs that an application accepts. A prompt contract applies a similar idea to an AI model’s runtime behavior: it describes the task, relevant context, permitted response shape, and boundaries the model should follow. Instead of treating a system prompt as documentation alone, this approach treats it as one component of an AI-facing interface.&lt;/p&gt;

&lt;p&gt;That is an architectural experiment, not a claim that a prompt can replace a backend. A real service still needs application code to receive requests, validate inputs, connect to databases and external services, and decide what operations are allowed. A useful mental model is a layer above existing systems: a user request arrives at an API, an LLM runtime interprets it, and application code decides whether any resulting structured operation may proceed.&lt;/p&gt;

&lt;p&gt;This tutorial uses support-ticket routing as a running example. A service might ask a model to classify a ticket into a set of permitted labels and return a structured result. The model’s result can inform a workflow, but it is not itself proof that the selected label is correct. Nor is a structured result authorization to issue a refund, change an account, or carry out another consequential operation.&lt;/p&gt;

&lt;h2&gt;Prerequisites and Scope&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Familiarity with Python, HTTP APIs, JSON, and FastAPI concepts.&lt;/li&gt;
&lt;li&gt;An OpenAI API account if you intend to connect the service to OpenAI.&lt;/li&gt;
&lt;li&gt;A defined use case, a limited set of allowed labels, and a plan for reviewing errors.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The available source material establishes the architecture and safety distinctions described here, but does not verify a particular SDK version, model name, pricing, or copy-and-run integration. For those details, consult the current official API and framework documentation before deployment. The steps below focus on building the service boundary and defining its responsibilities without presenting unverified provider-specific code as tested.&lt;/p&gt;

&lt;h2&gt;Step 1: Define the Application Contract&lt;/h2&gt;

&lt;p&gt;Start with the application’s actual need. Avoid vague objectives such as “understand the customer.” Write a bounded task such as “select one label from this approved set and provide a short explanation grounded in the supplied ticket.” Decide which input fields are necessary and which output fields a downstream application can safely consume.&lt;/p&gt;

&lt;p&gt;For a routing service, the request contract could include a ticket identifier and the customer’s message. Its response contract could contain a route label, a brief rationale, and a review indicator. The approved labels should be defined by the application rather than invented by the model. If there are only a few valid destinations, represent them as an explicit enumeration in the output schema.&lt;/p&gt;

&lt;p&gt;Document the purpose of every field. A rationale is an explanation for an operator, not a guarantee that the selected route is correct. A review indicator is a recommendation unless application logic gives it a separately defined effect. Avoid fields that imply authority the model does not have, such as an instruction to execute a payment or alter an account.&lt;/p&gt;

&lt;p&gt;Keep the backend authoritative. It should decide which services are reachable, which operations are permitted, and whether a human or another approval process is required. The prompt can describe the task and the desired result, but it cannot independently establish permissions or make an operation legitimate.&lt;/p&gt;

&lt;h2&gt;Step 2: Write a Versioned Prompt Contract&lt;/h2&gt;

&lt;p&gt;Write the system prompt as a maintained application artifact. State the task, provide only the context needed to complete it, list the allowed labels, and describe the output expectations. Give the prompt a version identifier in your application’s configuration or records so that teams can associate a decision with the prompt version used to produce it.&lt;/p&gt;

&lt;p&gt;Keep policy instructions distinct from user-provided content. A ticket is input data, not a source of authority to change the service’s contract. Tell the model how to treat the ticket for the task, but do not rely on that instruction alone to neutralize malicious or irrelevant content. The surrounding application must still validate the response and restrict what can happen next.&lt;/p&gt;

&lt;p&gt;Write instructions that can be evaluated. For example, specify that the model must choose one item from the documented label set and return the fields required by the schema. Avoid promising that a prompt will prevent every error or prompt-injection attempt. Prompts guide model behavior; they do not remove the need for application controls.&lt;/p&gt;

&lt;p&gt;Maintain changes deliberately. When the task, labels, or output fields change, update the contract and assess the impact on consumers. A prompt change can alter the meaning of a field even when the JSON structure remains unchanged. Versioning makes that behavioral change easier to identify in investigations and evaluations.&lt;/p&gt;

&lt;h2&gt;Step 3: Define a Structured Output Schema&lt;/h2&gt;

&lt;p&gt;Use Structured Outputs when a caller needs a response conforming to a specified schema. A schema can constrain field names, types, and, where configured, the permitted values of an enumeration. This is useful for a routing interface because it can prevent the response from inventing an undocumented label or adding arbitrary fields.&lt;/p&gt;

&lt;p&gt;Do not confuse this guarantee with correctness. If a schema allows four route labels, the model can return a structurally valid label that is still wrong for the ticket. Schema adherence answers a question about form; it does not establish that the selected value is factually or operationally appropriate.&lt;/p&gt;

&lt;p&gt;Design the schema around the downstream application, not around everything the model could say. Make fields explicit and keep free-form text bounded where appropriate. Decide how the service will respond when it cannot accept the model’s result. In particular, handle refusals and incomplete responses as distinct outcomes rather than treating them as successful classifications.&lt;/p&gt;

&lt;p&gt;On the FastAPI side, validate incoming requests at the HTTP boundary and validate accepted model results before passing them to other application components. The exact code for connecting a current OpenAI SDK to FastAPI depends on the supported API and library versions; verify it against current official documentation. Do not silently parse arbitrary text as a successful structured response.&lt;/p&gt;

&lt;h2&gt;Step 4: Separate Model Requests from Application Execution&lt;/h2&gt;

&lt;p&gt;Organize the service into responsibilities. The HTTP layer accepts a request and returns a response. A model-integration layer sends the task and schema to the provider and reports whether it received a usable result. A policy layer checks the result against application rules. An execution layer, if needed, calls authorized backend services only after those checks.&lt;/p&gt;

&lt;p&gt;This separation matters especially when using function calling. A model-generated function call is a proposed request for the application to perform work. It is not evidence that the caller is authorized, that the requested action is safe, or that the operation should run. Application code must validate the arguments and apply authorization before executing a function.&lt;/p&gt;

&lt;p&gt;For example, a model might propose an operation associated with a customer account. The backend should independently establish whether the account exists, whether the caller may act on it, whether the operation is allowed under current rules, and whether additional approval is needed. A prompt that says “only perform authorized actions” cannot substitute for those checks.&lt;/p&gt;

&lt;p&gt;Keep permissions and deterministic requirements in code and authoritative data. Exact access rules, approval requirements, and other non-negotiable conditions should not be delegated to a model’s interpretation of a prompt. The model may help extract or classify information; the application remains responsible for deciding what that information permits.&lt;/p&gt;

&lt;h2&gt;Step 5: Handle Refusals, Incomplete Results, and Errors&lt;/h2&gt;

&lt;p&gt;A service should distinguish a complete, usable structured result from a refusal, an incomplete response, a provider error, or a response that fails application validation. The verified guidance specifically calls out refusals and incomplete responses as cases an implementation must handle. Treating all of them as ordinary JSON results creates ambiguous behavior for callers.&lt;/p&gt;

&lt;p&gt;Define an explicit failure policy before connecting the endpoint to a workflow. Depending on the use case, the service might return a controlled error, request another review, or send the item to a human. Do not silently map every failure to a default route: that can make an unavailable or unresponsive model appear to have made a valid decision.&lt;/p&gt;

&lt;p&gt;Keep error messages suitable for API consumers and avoid exposing secrets or internal implementation details. Record enough operational information to investigate failures, while avoiding unnecessary collection of customer content. A failure path should be visible to operators and predictable to clients.&lt;/p&gt;

&lt;p&gt;When a response is available, validate its structure and then evaluate its meaning against application rules. These are separate checks: a response may pass schema validation and still violate a business rule. The application should reject, escalate, or otherwise handle that case according to the product’s defined policy.&lt;/p&gt;

&lt;h2&gt;Step 6: Expose the Contract Through FastAPI&lt;/h2&gt;

&lt;p&gt;Create a FastAPI endpoint that accepts the request model and returns a documented response model. Keep the HTTP route thin: it should validate the incoming shape, call the service layer, handle its defined outcomes, and return an appropriate result. Avoid putting policy, provider integration, and execution logic into one large route handler.&lt;/p&gt;

&lt;p&gt;Document what the endpoint does and, just as importantly, what it does not do. If it returns a recommended route, call it a recommendation. Do not describe it as an authorized action unless the application actually performed the required authorization and execution steps. Do not accept a user-supplied prompt or policy as if it were trusted service configuration.&lt;/p&gt;

&lt;p&gt;Before publishing the endpoint, decide who may call it and which backend capabilities it can reach. Authentication, authorization, request limits, and operational controls are application responsibilities; they are not supplied by a structured output schema. The provided sources do not prescribe a specific FastAPI deployment configuration, so verify those details against the environment in which you will run the service.&lt;/p&gt;

&lt;p&gt;Document the service contract in terms clients can rely on: accepted input, possible successful outputs, and behavior for refusal, incomplete output, validation failure, or unavailable upstream service. Keep the public contract stable when possible, and version intentional changes that affect consumers.&lt;/p&gt;

&lt;h2&gt;Step 7: Evaluate Decisions, Not Just JSON&lt;/h2&gt;

&lt;p&gt;Build a representative evaluation set before using the service in a consequential workflow. Include ordinary examples, ambiguous cases, and cases where a wrong classification would matter. For each case, define the expected behavior in terms of the labels and safety decisions your application cares about.&lt;/p&gt;

&lt;p&gt;Test the schema and the decision separately. Schema tests check that required fields and allowed values are respected. Decision tests check whether the selected label and any escalation recommendation are appropriate for the example. Passing the first category of tests does not mean the second has passed.&lt;/p&gt;

&lt;p&gt;Review model behavior whenever you change the prompt, schema, supported labels, or model configuration. Compare results against the same test cases, investigate regressions, and decide in advance what failures block a release. The context supports this core distinction between schema adherence and correctness; it does not establish a particular accuracy threshold or benchmark, so set thresholds from your own use case and evaluation data.&lt;/p&gt;

&lt;p&gt;Include human review where the consequences of an incorrect decision warrant it. Record corrections in a way that can inform future evaluation. Keep the review process separate from automatic execution so that an AI-generated label does not become an irreversible action by accident.&lt;/p&gt;

&lt;h2&gt;Common Design Mistakes&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Treating valid JSON as proof.&lt;/strong&gt; A schema constrains output shape, not whether the answer is true or correct.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Treating a function call as authorization.&lt;/strong&gt; A model can propose a call; application code must validate and authorize it before execution.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Using the prompt as the whole backend.&lt;/strong&gt; Databases, APIs, services, access rules, and execution remain application responsibilities.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Ignoring refusals or incomplete responses.&lt;/strong&gt; Define explicit behavior for both instead of assuming every request yields a usable result.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Failing silently.&lt;/strong&gt; A fallback that looks like a successful decision can hide provider or validation failures.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Changing behavior without tracking it.&lt;/strong&gt; Version prompt contracts and assess changes against representative cases.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;A prompt contract can provide a useful, structured interface between natural-language requests and an existing application. FastAPI can serve as the HTTP boundary, while the model returns a response constrained by a schema. The pattern is most useful when its limits are explicit: schema validity is not decision correctness, a proposed tool call is not authorization, and a prompt does not replace the backend.&lt;/p&gt;

&lt;p&gt;Build the service around a bounded task, an explicit schema, clear handling for refusals and incomplete responses, and application-side validation and authorization. Then evaluate the decisions themselves before connecting them to real workflows. That is the practical path from prompt experimentation to a more reliable AI-enabled service.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>ai</category>
      <category>tutorial</category>
      <category>discuss</category>
    </item>
    <item>
      <title>Build a JavaScript LLM Regression Test Runner</title>
      <dc:creator>Gate of AI</dc:creator>
      <pubDate>Sun, 15 Nov 2026 05:26:03 +0000</pubDate>
      <link>https://dev.to/gateofai/build-a-javascript-llm-regression-test-runner-1l8o</link>
      <guid>https://dev.to/gateofai/build-a-javascript-llm-regression-test-runner-1l8o</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;🚀 Technical Briefing:&lt;/strong&gt; This tutorial is part of our deep-dive series on Agentic Workflows at &lt;a href="https://gateofai.com" rel="noopener noreferrer"&gt;Gate of AI&lt;/a&gt;. For the full technical breakdown, interactive code sandbox, and the native Arabic translation, visit the &lt;a href="https://gateofai.com/tutorial/javascript-llm-regression-test-runner/" rel="noopener noreferrer"&gt;original article here&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Tutorial · JavaScript · LLM regression testing&lt;/strong&gt;&lt;/p&gt;

&lt;h1&gt;Build a JavaScript LLM Regression Test Runner&lt;/h1&gt;

&lt;p&gt;Language-model applications can regress when prompts, models, or APIs change. This tutorial builds a small JavaScript test runner that evaluates saved responses against explicit, deterministic acceptance rules. It is a provider-neutral foundation: the supplied verified sources establish the importance and challenges of LLM regression testing, but do not verify current OpenAI or Anthropic SDK syntax, model names, or endpoint parameters. For that reason, this implementation does not pretend to provide a verified live API adapter.&lt;/p&gt;

&lt;h2&gt;Why regression tests matter for LLM applications&lt;/h2&gt;

&lt;p&gt;Traditional software tests often compare a function’s output with an expected result. LLM responses are less uniform: an answer can be worded differently while remaining acceptable, or sound convincing while violating an important product rule. A test suite therefore needs carefully chosen assertions rather than a single exact paragraph used as a “golden” answer.&lt;/p&gt;

&lt;p&gt;Research on performance regression in applications that depend on evolving LLM APIs identifies regression as a real engineering concern. Work on LLM-based test generation also describes how generated tests can support regression testing as software changes. But generation is not a substitute for review. The software-engineering survey in the supplied context highlights the test-oracle problem: a test that passes on the current release may still encode the wrong expected behavior. It also reports that generated tests are not guaranteed to be executable. Treat test cases as reviewed product requirements, not unquestionable output from an automated system.&lt;/p&gt;

&lt;p&gt;The tool we build here is deliberately modest. It loads named cases, evaluates recorded responses with deterministic checks, writes a JSON report, and returns a failing process status when an assertion fails. The same evaluation logic can later be connected to a live provider adapter after you verify that adapter against the provider’s current official documentation.&lt;/p&gt;

&lt;h2&gt;Prerequisites and project setup&lt;/h2&gt;

&lt;p&gt;You need a JavaScript runtime with ES module support and npm. The commands below create a minimal project. The harness itself makes no network requests and does not require API keys, so you can verify the evaluator before introducing API cost, credentials, or provider-specific behavior.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;mkdir llm-regression-runner
cd llm-regression-runner
npm init -y
npm pkg set type=module
npm pkg set scripts.test="node --test"
npm pkg set scripts.eval="node src/run.js"
mkdir -p src test fixtures reports&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Create &lt;code&gt;.gitignore&lt;/code&gt; so dependencies and generated reports are not accidentally committed. Reports can contain test prompts and model responses; review their contents and your organization’s handling requirements before storing or sharing them.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;node_modules/
reports/*.json&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This example uses Node’s built-in test runner, filesystem, and assertion facilities. It has no third-party package requirement. If your environment uses a different supported runtime or test framework, adapt the commands and verify the result in that environment.&lt;/p&gt;

&lt;h2&gt;Step 1: Define reviewed cases and saved responses&lt;/h2&gt;

&lt;p&gt;Create &lt;code&gt;src/cases.js&lt;/code&gt;. Each test has a stable identifier, a description that helps explain failures, and explicit checks. These sample cases illustrate policy facts, prohibited language, response length, and a small JSON contract. Replace the fictional policy with rules that your application owners have reviewed. The expected text fragments are examples, not legal or customer-support guidance.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;export const testCases = [
  {
    id: "refund-window",
    description: "Includes the reviewed refund window and offers support.",
    checks: {
      requiredSubstrings: ["30 days", "support"],
      forbiddenSubstrings: ["guaranteed refund"],
      maxCharacters: 900
    }
  },
  {
    id: "account-security",
    description: "Directs the user to a password reset and does not request a password.",
    checks: {
      requiredSubstrings: ["password reset"],
      forbiddenSubstrings: ["send me your password", "share your password"],
      maxCharacters: 700
    }
  },
  {
    id: "shipping-json",
    description: "Returns the expected fields and a numeric delivery estimate.",
    checks: {
      requiredJsonKeys: [
        "status",
        "estimated_delivery_days",
        "customer_message"
      ],
      maxCharacters: 600
    }
  }
];&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Stable IDs make reports understandable even after you add or reorder cases. Keep descriptions concise but useful to a reviewer. Use required fragments only for facts or wording that genuinely matters to the application. Exact phrase checks can be brittle: equivalent wording may fail, while the presence of a phrase does not prove that the complete answer is correct.&lt;/p&gt;

&lt;p&gt;Create &lt;code&gt;fixtures/responses.json&lt;/code&gt; with recorded responses for each case. These are example fixtures for testing the harness, not claims about what a particular model will return. In an API-backed workflow, store appropriately reviewed and permitted sample outputs here, or load them from a controlled test-data source.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
  "refund-window": "The stated refund window is 30 days from delivery. Please contact support to discuss your situation.",
  "account-security": "Do not share your password. Use the password reset flow to regain access to your account.",
  "shipping-json": "{\"status\":\"shipped\",\"estimated_delivery_days\":3,\"customer_message\":\"Your order is on the way.\"}"
}&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Step 2: Implement deterministic response checks&lt;/h2&gt;

&lt;p&gt;Create &lt;code&gt;src/evaluate.js&lt;/code&gt;. The evaluator is a pure function: it receives a case and response text, then returns whether the checks passed and a list of reasons for failure. It does not call a model, modify files, or make assumptions about provider response formats. That separation makes failures quick to test and easier to diagnose.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function parseJsonObject(text) {
  try {
    const value = JSON.parse(text);
    if (value === null || Array.isArray(value) || typeof value !== "object") {
      return null;
    }
    return value;
  } catch {
    return null;
  }
}

export function evaluateResponse(testCase, text) {
  if (typeof text !== "string") {
    throw new TypeError("Response text must be a string.");
  }

  const failures = [];
  const checks = testCase.checks ?? {};
  const normalized = text.toLocaleLowerCase("en-US");

  for (const phrase of checks.requiredSubstrings ?? []) {
    if (!normalized.includes(phrase.toLocaleLowerCase("en-US"))) {
      failures.push(`Missing required text: ${JSON.stringify(phrase)}`);
    }
  }

  for (const phrase of checks.forbiddenSubstrings ?? []) {
    if (normalized.includes(phrase.toLocaleLowerCase("en-US"))) {
      failures.push(`Contains forbidden text: ${JSON.stringify(phrase)}`);
    }
  }

  if (Number.isInteger(checks.maxCharacters) &amp;amp;&amp;amp; text.length &amp;gt; checks.maxCharacters) {
    failures.push(
      `Response has ${text.length} characters; maximum is ${checks.maxCharacters}.`
    );
  }

  if (Array.isArray(checks.requiredJsonKeys) &amp;amp;&amp;amp; checks.requiredJsonKeys.length &amp;gt; 0) {
    const parsed = parseJsonObject(text);

    if (parsed === null) {
      failures.push("Response is not a valid JSON object.");
    } else {
      const actualKeys = Object.keys(parsed).sort();
      const expectedKeys = [...checks.requiredJsonKeys].sort();

      for (const key of expectedKeys) {
        if (!Object.hasOwn(parsed, key)) {
          failures.push(`JSON response is missing required key: ${JSON.stringify(key)}`);
        }
      }

      if (
        actualKeys.length !== expectedKeys.length ||
        actualKeys.some((key, index) =&amp;gt; key !== expectedKeys[index])
      ) {
        failures.push(`JSON keys must be exactly: ${expectedKeys.join(", ")}.`);
      }

      if (
        Object.hasOwn(parsed, "estimated_delivery_days") &amp;amp;&amp;amp;
        typeof parsed.estimated_delivery_days !== "number"
      ) {
        failures.push('JSON key "estimated_delivery_days" must contain a number.');
      }
    }
  }

  return { passed: failures.length === 0, failures };
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This JSON check accepts only raw JSON, not a Markdown code fence. That choice is intentional for a machine-readable fixture: it avoids treating decorated prose as a valid payload. The key check requires exactly the listed keys, which is appropriate only when the contract really is exact. If extra properties are permitted, change the check to require a subset instead. For business-critical data, validate every field and its allowed values using a schema designed for that application.&lt;/p&gt;

&lt;h2&gt;Step 3: Add a command-line runner and JSON report&lt;/h2&gt;

&lt;p&gt;Create &lt;code&gt;src/run.js&lt;/code&gt;. The runner pairs each case with its saved response, evaluates it, prints a readable result, and writes a timestamped report. It exits unsuccessfully if a fixture is missing or a check fails. A missing fixture is an execution problem, not a successful evaluation, so the runner reports it as a failure rather than silently skipping the case.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { testCases } from "./cases.js";
import { evaluateResponse } from "./evaluate.js";

async function main() {
  const fixtureText = await readFile("fixtures/responses.json", "utf8");
  const fixtures = JSON.parse(fixtureText);
  const results = [];

  for (const testCase of testCases) {
    const responseText = fixtures[testCase.id];

    if (typeof responseText !== "string") {
      results.push({
        testCaseId: testCase.id,
        description: testCase.description,
        passed: false,
        failures: ["No string response fixture was found for this test case."]
      });
      continue;
    }

    const evaluation = evaluateResponse(testCase, responseText);
    results.push({
      testCaseId: testCase.id,
      description: testCase.description,
      passed: evaluation.passed,
      failures: evaluation.failures
    });
  }

  for (const result of results) {
    console.log(`[${result.passed ? "PASS" : "FAIL"}] ${result.testCaseId}`);
    for (const failure of result.failures) {
      console.log(`  - ${failure}`);
    }
  }

  const passed = results.filter((result) =&amp;gt; result.passed).length;
  const report = {
    generatedAt: new Date().toISOString(),
    total: results.length,
    passed,
    failed: results.length - passed,
    results
  };

  await mkdir("reports", { recursive: true });
  const filename = `report-${new Date().toISOString().replace(/[:.]/g, "-")}.json`;
  const reportPath = join("reports", filename);
  await writeFile(reportPath, `${JSON.stringify(report, null, 2)}\n`, "utf8");

  console.log(`Completed ${report.total} evaluations: ${report.passed} passed, ${report.failed} failed.`);
  console.log(`Report written to ${reportPath}`);

  if (report.failed &amp;gt; 0) {
    process.exitCode = 1;
  }
}

main().catch((error) =&amp;gt; {
  console.error(error instanceof Error ? error.stack : String(error));
  process.exitCode = 1;
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The report contains test identifiers and assertion failures, but this minimal example omits response text. That reduces the chance of copying sensitive output into a build artifact by default. If you need response text for debugging, add it deliberately and control access, retention, and redaction. A test report is still an engineering data artifact and should be handled accordingly.&lt;/p&gt;

&lt;h2&gt;Step 4: Test the evaluator without API calls&lt;/h2&gt;

&lt;p&gt;Create &lt;code&gt;test/evaluate.test.js&lt;/code&gt;. These tests exercise the assertion logic directly and run without provider credentials or network access. They demonstrate both a successful response and two distinct failure types.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import test from "node:test";
import assert from "node:assert/strict";
import { evaluateResponse } from "../src/evaluate.js";

test("passes when required and prohibited-text checks are satisfied", () =&amp;gt; {
  const result = evaluateResponse(
    {
      checks: {
        requiredSubstrings: ["30 days", "support"],
        forbiddenSubstrings: ["guaranteed refund"],
        maxCharacters: 300
      }
    },
    "The policy states 30 days. Please contact support for help."
  );

  assert.deepEqual(result, { passed: true, failures: [] });
});

test("reports missing required text and a prohibited phrase", () =&amp;gt; {
  const result = evaluateResponse(
    {
      checks: {
        requiredSubstrings: ["password reset"],
        forbiddenSubstrings: ["share your password"]
      }
    },
    "Please share your password with support."
  );

  assert.equal(result.passed, false);
  assert.equal(result.failures.length, 2);
});

test("rejects invalid JSON and detects wrong JSON field types", () =&amp;gt; {
  const checks = {
    requiredJsonKeys: ["status", "estimated_delivery_days", "customer_message"]
  };

  const invalidJson = evaluateResponse({ checks }, "not JSON");
  assert.equal(invalidJson.passed, false);
  assert.ok(invalidJson.failures.includes("Response is not a valid JSON object."));

  const wrongType = evaluateResponse(
    { checks },
    JSON.stringify({
      status: "shipped",
      estimated_delivery_days: "three",
      customer_message: "On the way"
    })
  );
  assert.equal(wrongType.passed, false);
  assert.ok(
    wrongType.failures.includes(
      'JSON key "estimated_delivery_days" must contain a number.'
    )
  );
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Run the local checks:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;npm test
npm run eval&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The test command validates evaluator behavior. The evaluation command checks the saved examples. A passing run means these fixtures satisfy these rules; it does not prove that a model will always respond correctly, that the rules are complete, or that a model provider has not changed its behavior.&lt;/p&gt;

&lt;h2&gt;Step 5: Connect a live model only after verifying its API&lt;/h2&gt;

&lt;p&gt;The next step is a provider adapter that accepts a case’s prompt and returns response text. This tutorial intentionally does not supply one. The verified context does not specify the current OpenAI or Anthropic API method names, SDK versions, supported model IDs, request fields, or response shapes. Copying unverified integration code into a tutorial would create a misleading claim of compatibility.&lt;/p&gt;

&lt;p&gt;When implementing an adapter, consult each provider’s current official documentation and verify the exact SDK package and version, authentication method, model identifier, request and response structure, timeout handling, and error semantics. Keep the adapter separate from &lt;code&gt;evaluateResponse&lt;/code&gt;. That separation lets the same acceptance suite test saved fixtures locally while a distinct integration command exercises live calls. Handle transient errors and rate limits according to the verified provider guidance; do not assume that two providers expose identical errors or retry rules.&lt;/p&gt;

&lt;p&gt;For an API-backed evaluation, record enough metadata to investigate changes—such as the configured provider and model identifier, timestamp, and test-case version—without leaking secrets. Before sharing outputs or retaining reports, check whether prompts and responses contain confidential or personal information. Avoid claiming that a particular model is “better” based only on a handful of cases; results are meaningful only relative to the reviewed test set and intended use.&lt;/p&gt;

&lt;h2&gt;Designing a useful regression suite&lt;/h2&gt;

&lt;p&gt;Begin with cases linked to actual product requirements, incidents, or known failure modes. Keep each case focused so a failure has an understandable cause. Include negative cases where the assistant should avoid a claim, as well as positive cases where it must preserve a critical fact. For structured outputs, verify parseability, required fields, types, and any constraints that downstream code relies on.&lt;/p&gt;

&lt;p&gt;Do not compare complete prose responses to one reference paragraph unless exact text is genuinely required. Phrase-level assertions can catch a missing fact, but they are not semantic proof: a response can contain the required words and still be misleading. Pair deterministic checks with review by qualified people for high-impact cases. If you introduce a model-based judge, treat its score as another fallible signal and validate it against human-reviewed examples before relying on it.&lt;/p&gt;

&lt;p&gt;Keep acceptance criteria versioned and review changes as carefully as application code. When a test fails, first inspect whether the output violates a real requirement, the requirement was expressed clearly, or the check is overly brittle. Do not weaken a meaningful rule just to make a build green; equally, remove assertions that merely enforce a stylistic preference. The goal is a suite that surfaces consequential behavior changes and remains trusted by the people who maintain it.&lt;/p&gt;

&lt;h2&gt;Limitations and next steps&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;This example evaluates saved fixtures; it does not make calls to OpenAI or Anthropic.&lt;/li&gt;
&lt;li&gt;Substring and basic JSON checks cannot establish overall factual correctness or quality.&lt;/li&gt;
&lt;li&gt;A passing test set covers only the scenarios represented by its cases; it is not a guarantee of future behavior.&lt;/li&gt;
&lt;li&gt;Generated tests require review. The supplied research notes that generated tests may not be executable and discusses the broader difficulty of determining whether a test’s expected outcome is correct.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Useful extensions include stricter application-specific schemas, reviewed regression cases derived from incidents, controlled API-backed runs, and a report format that captures only the metadata your team needs. Add concurrency, retries, cost accounting, or latency gates only after defining and verifying their requirements for your chosen providers and deployment environment.&lt;/p&gt;

&lt;h2&gt;Sources and research context&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://arxiv.org/html/2403.16218v3" rel="noopener noreferrer"&gt;CoverUp: Coverage-Guided LLM-Based Test Generation&lt;/a&gt; discusses LLM-based test generation and its relationship to regression testing.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://arxiv.org/html/2310.03533v4" rel="noopener noreferrer"&gt;Large Language Models for Software Engineering: Survey and Open Problems&lt;/a&gt; discusses test correctness, the oracle problem, and limitations of generated tests.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://dl.acm.org/doi/abs/10.1145/3644815.3644950" rel="noopener noreferrer"&gt;(Why) Is My Prompt Getting Worse? Rethinking Regression&lt;/a&gt; addresses performance regression in applications dependent on evolving LLM APIs.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Editorial attribution: Gate of AI Editorial &amp;amp; Engineering Teams, GateOfAI, LLC.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>ai</category>
      <category>tutorial</category>
      <category>discuss</category>
    </item>
    <item>
      <title>Design an Approval-Gated Incident Triage Workflow</title>
      <dc:creator>Gate of AI</dc:creator>
      <pubDate>Sun, 15 Nov 2026 05:25:45 +0000</pubDate>
      <link>https://dev.to/gateofai/design-an-approval-gated-incident-triage-workflow-2932</link>
      <guid>https://dev.to/gateofai/design-an-approval-gated-incident-triage-workflow-2932</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;🚀 Technical Briefing:&lt;/strong&gt; This tutorial is part of our deep-dive series on Agentic Workflows at &lt;a href="https://gateofai.com" rel="noopener noreferrer"&gt;Gate of AI&lt;/a&gt;. For the full technical breakdown, interactive code sandbox, and the native Arabic translation, visit the &lt;a href="https://gateofai.com/tutorial/approval-gated-incident-triage-langgraph/" rel="noopener noreferrer"&gt;original article here&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Tutorial · Architecture guide&lt;/strong&gt;&lt;/p&gt;

&lt;h1&gt;Design an Approval-Gated Incident Triage Workflow&lt;/h1&gt;

&lt;p&gt;Learn how to structure an incident-triage workflow around LangGraph concepts, human review, and research-informed multi-agent patterns. This guide focuses on system design: the verified sources describe LangGraph capabilities and the TRIANGLE incident-triage research approach, but do not verify a specific Claude, ChatGPT, Slack, or production API implementation.&lt;/p&gt;

&lt;h2&gt;What this guide covers&lt;/h2&gt;

&lt;p&gt;Incident reports are often inconsistent, noisy, or incomplete. A useful triage process must turn those reports into information that responders can act on, connect the issue to relevant teams, and preserve a human decision point where judgment is needed. Agent orchestration can help organize such a process, but the architecture should not confuse generated recommendations with verified operational facts.&lt;/p&gt;

&lt;p&gt;This guide combines two separately verified ideas. First, the TRIANGLE research paper describes a multi-agent incident-triage system. Its approach includes semantic distillation to extract actionable information from noisy incident data, a triage decision process that proposes candidate teams, and discussions involving relevant team-manager agents. The agents contribute domain knowledge, and discussion and voting support the assignment decision. Second, the DeepLearning.AI course on AI Agents in LangGraph describes LangGraph as a framework for stateful, multi-step agent applications and covers persistence, streaming, agentic search, and human-in-the-loop patterns.&lt;/p&gt;

&lt;p&gt;Those sources do not establish that TRIANGLE is implemented in LangGraph, or that it uses Claude, ChatGPT, Slack, or the particular APIs in the original draft. The design below is therefore a grounded architecture exercise—not a tested integration recipe or a claim that a particular model can safely execute production operations.&lt;/p&gt;

&lt;h2&gt;Step 1: Define the incident-triage problem&lt;/h2&gt;

&lt;p&gt;Begin by describing the decision your workflow should support. For example, the workflow might help responders interpret a report and identify which team or teams should review it. Keep that scope distinct from performing remediation. The verified TRIANGLE research is about incident triage and team assignment; it does not establish that an agent should change production systems or independently carry out repairs.&lt;/p&gt;

&lt;p&gt;Write down the information available at intake and the decision expected at the end. An intake description might include an incident narrative and any relevant context your organization is authorized to provide. The output might be a concise, reviewable triage summary and a proposed team assignment. Treat this as a design contract: do not let a model silently broaden the workflow into actions that were not part of the defined triage task.&lt;/p&gt;

&lt;p&gt;Also decide what happens when the evidence is insufficient. A useful workflow should be able to surface uncertainty or request more human attention rather than presenting a weak inference as a confirmed diagnosis. This is a design recommendation, not a capability or guarantee established by the cited sources. Validate the behavior against your own requirements and test cases before relying on it.&lt;/p&gt;

&lt;h2&gt;Step 2: Distill noisy incident information&lt;/h2&gt;

&lt;p&gt;TRIANGLE identifies noisy and inconsistent incident descriptions as a challenge for automated triage. Its semantic-distillation mechanism uses language models to extract core, actionable information relevant to triage decisions. It then aligns that distilled information with relevant teams' domain knowledge. The paper describes extracted phrases about failure location, symptoms, and capabilities likely to be required to resolve the incident; those phrases are added to the original incident data as focused input for a triage decision agent.&lt;/p&gt;

&lt;p&gt;Use that sequence as a design pattern rather than assuming a particular implementation. First preserve the original report. Then produce a separate, clearly labeled representation of the information considered relevant to triage. Keeping the source report and its distilled representation distinct makes it easier for a reviewer to compare the summary with the original evidence. The paper supports the semantic-distillation concept; it does not specify the exact schema, prompt, model vendor, or interface you should use.&lt;/p&gt;

&lt;p&gt;For an exercise, define categories that matter to your own incident process, such as symptoms, apparent location, and capabilities that may be needed. Make clear that these are proposed information fields for your workflow, not fields prescribed by TRIANGLE. Have responders review whether the extracted details preserve the meaning of the original reports. Include ambiguous, incomplete, and contradictory examples in evaluation rather than testing only clear-cut incidents.&lt;/p&gt;

&lt;p&gt;Do not treat a distilled summary as independent confirmation. It is a transformation of the supplied information. Keep the original report available to the person reviewing the triage decision, and establish your own procedures for sensitive information and access.&lt;/p&gt;

&lt;h2&gt;Step 3: Map the workflow as stateful stages&lt;/h2&gt;

&lt;p&gt;LangGraph is described in the verified course material as a framework for stateful, multi-step agent applications. The course covers building an agent from scratch and implementing it with LangGraph, then explores components, agentic search, persistence, streaming, and human-in-the-loop patterns. These concepts make it reasonable to plan an incident workflow as a sequence of stages with information carried forward between them. The available sources do not document a specific graph definition or guarantee particular APIs, so treat this as an architectural map rather than copy-and-paste implementation guidance.&lt;/p&gt;

&lt;p&gt;A design diagram might contain the following stages:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Intake:&lt;/strong&gt; receive and retain the incident information that the triage process is permitted to use.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Semantic distillation:&lt;/strong&gt; create a focused representation of the report, keeping it distinguishable from the source.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Candidate-team proposal:&lt;/strong&gt; identify teams that may be relevant based on the information and available domain knowledge.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Team review:&lt;/strong&gt; collect input from relevant team roles or representatives.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Recommendation:&lt;/strong&gt; present the rationale and proposed assignment for review.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Human decision:&lt;/strong&gt; provide a defined point for a responder to accept, reject, or request further review.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This sequence is a way to apply the concepts in the sources; it is not a claim that it reproduces TRIANGLE's complete system or a documented LangGraph reference implementation. The TRIANGLE paper describes an Analyzer Agent, a Decider Agent, and relevant Team Manager Agents, along with discussion and voting. The exact stages and names in a real deployment should match the organization's process.&lt;/p&gt;

&lt;h2&gt;Step 4: Use multi-agent roles to surface team knowledge&lt;/h2&gt;

&lt;p&gt;TRIANGLE's multi-role design addresses the fact that domain knowledge can be distributed across teams and can change. Its Decider Agent proposes candidate teams based on historical data and functional expertise, then initiates a discussion group with relevant Team Manager Agents. Those agents access external tools to contribute insights. The agents discuss and vote on assignment; if the issue is not resolved, the process can iterate with a refined candidate pool.&lt;/p&gt;

&lt;p&gt;When adapting this pattern, define why each role exists and what information it may contribute. A role should correspond to a meaningful source of expertise or a distinct part of the triage process—not simply add another model call. Keep the distinction between an agent's contribution and the final assignment visible. A set of generated opinions is not, by itself, proof that the conclusion is correct.&lt;/p&gt;

&lt;p&gt;The paper's description supports the use of negotiation and voting in its own approach. It does not establish that voting is universally reliable, that a particular number of agents is optimal, or that multiple agents remove the need for human review. Determine how disagreement, missing team knowledge, and changing ownership should be handled in your environment. Make unresolved cases visible instead of masking them with an automatic consensus label.&lt;/p&gt;

&lt;h2&gt;Step 5: Put a human decision in the workflow&lt;/h2&gt;

&lt;p&gt;Human-in-the-loop patterns are explicitly covered in the LangGraph course. For an incident-triage design, use that idea to identify where a responder should review the information before a decision is finalized. The review surface should make the incident report, distilled information, proposed team, and relevant reasoning available together. A reviewer should be able to compare the recommendation with its source rather than being asked to approve a conclusion without context.&lt;/p&gt;

&lt;p&gt;Decide what the human can do at this point. The available sources do not prescribe a particular approval interface or decision vocabulary. A team might choose to accept a proposal, reject it, or send it for additional review, but those are design choices to verify against its own incident process. Record the result in a way that the workflow can use to determine its next stage.&lt;/p&gt;

&lt;p&gt;Be precise about what approval means. Approval of a team assignment is not the same as authorization to execute a remediation action. The verified research concerns triage, and the course material establishes that human-in-the-loop patterns are taught; neither source verifies an approval-gated Slack notification or production-action system. If your organization later connects triage to consequential actions, assess and govern those actions separately.&lt;/p&gt;

&lt;h2&gt;Step 6: Plan persistence and workflow continuity&lt;/h2&gt;

&lt;p&gt;The LangGraph course specifically covers persistence, including state management across multiple threads, switching conversations, and reloading previous states. These topics matter when an incident workflow has multiple stages or needs to continue after a pause. In your design, identify what information must remain available between intake, analysis, team discussion, and human review.&lt;/p&gt;

&lt;p&gt;Before selecting a persistence mechanism, establish the actual requirements: which state is needed to continue a workflow, how long it should be retained, who may access it, and how it should be handled when it is no longer needed. The provided source material confirms that persistence is a LangGraph learning topic; it does not verify a specific storage backend, production deployment, retention policy, or durability guarantee. Do not describe a local or in-memory example as production persistence unless you have verified its behavior and operational properties.&lt;/p&gt;

&lt;p&gt;Likewise, streaming is a course topic, but the sources do not establish a particular incident interface or streaming implementation. Decide whether responders need incremental updates, and test that design with the tools and framework versions you actually deploy.&lt;/p&gt;

&lt;h2&gt;Step 7: Consider agentic search as an optional input&lt;/h2&gt;

&lt;p&gt;The verified LangGraph course covers agentic search and describes it as returning multiple answers in an agent-friendly format, rather than traditional search engines returning links. It also teaches integrating agentic search to provide additional information to agents. This suggests a possible research step in a triage workflow, but it does not verify which search system, data source, or retrieval policy should be used for incidents.&lt;/p&gt;

&lt;p&gt;If you consider adding search, first define which sources are appropriate for the incident and what information the search step is permitted to return. Keep retrieved material distinguishable from the incident report and from team-provided knowledge. The workflow should not imply that retrieved material is authoritative merely because a search component supplied it. Establish how responders can assess whether a result is relevant to the current incident.&lt;/p&gt;

&lt;p&gt;Search is optional in this design. The incident-triage research source and the LangGraph course establish relevant concepts, not a tested connection between a search product and TRIANGLE or a ready-made incident knowledge base.&lt;/p&gt;

&lt;h2&gt;Step 8: Evaluate the design before relying on it&lt;/h2&gt;

&lt;p&gt;The verified sources describe research and course content, not a benchmark for the design proposed here. You will need to evaluate your own workflow. Assemble incident examples that reflect the variety of reports your responders handle, and ask qualified reviewers to assess whether the distilled information and proposed team are appropriate. Include cases where reports are unclear or where multiple teams could reasonably be involved.&lt;/p&gt;

&lt;p&gt;Separate the questions you are measuring. Does the distilled representation retain useful details? Does the proposed team match what knowledgeable responders would choose? Does the workflow expose disagreement rather than concealing it? Can a reviewer understand the basis of the recommendation? These are evaluation questions, not performance claims about TRIANGLE, LangGraph, Claude, or ChatGPT.&lt;/p&gt;

&lt;p&gt;Review failures as well as successful examples. A workflow that produces a plausible summary can still omit an important detail or suggest a team without adequate evidence. Decide what should happen when a stage fails, information is missing, or human reviewers disagree. Run any intended operational use through your organization's normal engineering and incident-management review.&lt;/p&gt;

&lt;h2&gt;Common design mistakes to avoid&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Presenting research as an implementation recipe.&lt;/strong&gt; TRIANGLE is a research system; the provided source does not say it is built with LangGraph.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Claiming unverified model integrations.&lt;/strong&gt; The verified context does not establish Claude or ChatGPT integration, model versions, or their respective roles in an incident workflow.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Confusing triage with remediation.&lt;/strong&gt; The research source discusses incident triage and assignment, not autonomous production changes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Hiding uncertainty behind a vote.&lt;/strong&gt; TRIANGLE describes discussion and voting, but that does not prove every vote is correct or remove the need to handle unresolved cases.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Calling a workflow production-ready without evidence.&lt;/strong&gt; Persistence and human-in-the-loop are verified learning topics, not proof of a specific deployment's reliability, security, or compliance.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Next steps&lt;/h2&gt;

&lt;p&gt;For developers who want to learn the framework concepts behind this design, DeepLearning.AI's AI Agents in LangGraph course covers LangGraph components, agentic search, persistence, streaming, and human-in-the-loop patterns. Its verified course outline lists 9 lessons and 6 code examples. It is aimed at learners with intermediate Python knowledge. The course is educational material, not a substitute for verifying the framework's current documentation and your own deployment requirements.&lt;/p&gt;

&lt;p&gt;As a practical design exercise, sketch the stages, mark which information moves between them, identify where team expertise enters, and place a human decision where your process requires one. Then validate the architecture against the incident-triage needs of the teams who will use it. Keep implementation claims, model choices, and operational guarantees out of the design until they have been independently tested.&lt;/p&gt;

&lt;h2&gt;Sources and scope&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://www.microsoft.com/en-us/research/wp-content/uploads/2025/02/TRIANGLE_ASE25.pdf" rel="noopener noreferrer"&gt;TRIANGLE: Empowering Incident Triage with Multi-Agent&lt;/a&gt;, Microsoft Research-hosted paper.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.deeplearning.ai/courses/ai-agents-in-langgraph" rel="noopener noreferrer"&gt;AI Agents in LangGraph&lt;/a&gt;, DeepLearning.AI course.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This article is a design-oriented tutorial based on the cited source descriptions. It does not claim a tested LangGraph implementation of TRIANGLE, a Claude or ChatGPT integration, or a deployable incident-management service.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>ai</category>
      <category>tutorial</category>
      <category>discuss</category>
    </item>
    <item>
      <title>Build a Type-Safe Multi-Model AI Router</title>
      <dc:creator>Gate of AI</dc:creator>
      <pubDate>Sun, 08 Nov 2026 17:13:11 +0000</pubDate>
      <link>https://dev.to/gateofai/build-a-type-safe-multi-model-ai-router-3pc7</link>
      <guid>https://dev.to/gateofai/build-a-type-safe-multi-model-ai-router-3pc7</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;🚀 Technical Briefing:&lt;/strong&gt; This tutorial is part of our deep-dive series on Agentic Workflows at &lt;a href="https://gateofai.com" rel="noopener noreferrer"&gt;Gate of AI&lt;/a&gt;. For the full technical breakdown, interactive code sandbox, and the native Arabic translation, visit the &lt;a href="https://gateofai.com/tutorial/type-safe-multi-model-ai-router-nextjs/" rel="noopener noreferrer"&gt;original article here&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Tutorial · Verification-first architecture guide&lt;/strong&gt;&lt;/p&gt;

&lt;h1&gt;Build a Type-Safe Multi-Model AI Chat Router&lt;/h1&gt;

&lt;p&gt;This guide explains how to plan and verify a Next.js application that routes chat requests to more than one model provider. It focuses on the boundaries that must be established before code is treated as production-ready: a shared request contract, server-side provider integration, explicit model selection, and a version-security review. The available verified sources do not establish current OpenAI or Anthropic JavaScript SDK syntax, supported model identifiers, or response schemas. Accordingly, this article does not present unverified provider calls as working code.&lt;/p&gt;

&lt;h2&gt;What the Available Evidence Establishes&lt;/h2&gt;

&lt;p&gt;Next.js is a React framework for building web applications. The supplied sources also describe KISS Sorcar, a separate assistant framework that catalogs models across multiple provider categories, including OpenAI and Anthropic. Its description says tasks can mix models by referencing a different model ID and that the framework swaps the backend per call. These facts demonstrate that multi-provider model selection is a real software pattern, but they do not document a Next.js route handler or prove that a particular OpenAI or Anthropic SDK integration works.&lt;/p&gt;

&lt;p&gt;That distinction matters. A tutorial can safely explain design goals and verification steps without pretending that every library call has been checked. SDKs evolve, model names change, and provider request and response formats are not interchangeable by default. Before copying code into an application, consult the current official documentation for each provider and test against the exact package versions and models you intend to deploy.&lt;/p&gt;

&lt;p&gt;This guide therefore treats the implementation as a sequence of engineering decisions. It does not claim that a particular model is available to every account, that a specific token parameter is accepted by both providers, or that one normalized response shape captures every provider capability. Those are integration details to verify independently.&lt;/p&gt;

&lt;h2&gt;Step 1: Define the Router’s Scope&lt;/h2&gt;

&lt;p&gt;Write down what “multi-model router” means for your application before choosing a package or creating a user interface. At minimum, decide whether a user selects a provider, a model, or a preconfigured combination of both. A provider selector alone is not a model registry: each provider can expose multiple models, and availability may depend on account access or configuration.&lt;/p&gt;

&lt;p&gt;Also decide whether the first version handles text-only chat. The supplied context does not verify support for images, tools, structured output, streaming, or multimodal requests through the proposed Next.js implementation. Do not imply those capabilities merely because a provider or another framework may support them. Keep the initial contract narrow and add a capability only after checking the provider documentation and testing the relevant request and response paths.&lt;/p&gt;

&lt;p&gt;Write down the user-visible result you need. A small interface might show the selected provider and model alongside the answer. That is a product decision, not proof that the provider returned the requested model. Where the provider returns an identifier, verify and report the actual response value according to its current API documentation.&lt;/p&gt;

&lt;h2&gt;Step 2: Create a Shared Request Contract&lt;/h2&gt;

&lt;p&gt;Use an application-owned request format rather than allowing provider-specific data structures to spread through the UI. A contract should specify the permitted provider identifiers, the accepted message roles, message content limits, and how the selected model is represented. Validate incoming HTTP data at runtime: TypeScript types describe values during development, but they do not by themselves validate arbitrary JSON received by a server.&lt;/p&gt;

&lt;p&gt;Make role policy explicit. If the client is expected to send only user messages and a system instruction, encode that policy in the runtime validator and test it. If earlier assistant turns must be sent to preserve conversational context, specify that intentionally and validate their order. Do not claim that assistant messages are rejected while writing a schema that accepts them. The draft implementation had precisely this contradiction: its role enum included assistant even though its explanatory text said assistant messages could not be sent.&lt;/p&gt;

&lt;p&gt;Likewise, validate the relationship between provider and model on the server. A browser dropdown is a convenience for users, not a security boundary. A request can be altered outside the interface. Keep an approved list or registry in server-controlled configuration and reject combinations that the application has not explicitly enabled. The supplied sources do not establish a current list of OpenAI or Anthropic model IDs, so populate this registry only after checking official provider information.&lt;/p&gt;

&lt;p&gt;Choose request-size limits based on your product requirements and test them. A character limit can bound the size of a text field, but it is not a token count and should not be presented as one. Provider-specific token accounting, output limits, and billing behavior must be confirmed with the relevant provider documentation.&lt;/p&gt;

&lt;h2&gt;Step 3: Keep Provider Calls Behind a Server Boundary&lt;/h2&gt;

&lt;p&gt;For a web application, design the browser-to-server boundary before connecting a model. The browser should submit an application request to your own server endpoint; the server is where provider credentials and provider-specific integration belong. Do not place secrets in browser-visible configuration or return them in responses. Verify the actual framework conventions and deployment settings for the Next.js version you use.&lt;/p&gt;

&lt;p&gt;Use a separate adapter for each provider. Each adapter should translate the shared application contract into the provider’s documented request format and translate the documented response into your application’s result format. Treat that normalized response as an application abstraction, not as evidence that provider capabilities are identical. If one provider returns content in multiple blocks or exposes additional metadata, handle that according to its official documentation instead of assuming a text field exists in a particular location.&lt;/p&gt;

&lt;p&gt;Before publishing an adapter, verify its package name, installed version, initialization method, method names, required fields, response parsing, and error behavior against official documentation. The verified context supplied for this review does not confirm the draft’s specific JavaScript SDK calls or model identifiers. Therefore, copying those exact calls from the original draft without independent checking would be unsafe.&lt;/p&gt;

&lt;p&gt;Return errors that help the application behave correctly without exposing credentials or raw sensitive request data. Distinguish malformed input from a missing server configuration and an upstream provider failure. Avoid logging full prompts by default unless your organization has reviewed the data, retention, access, and consent implications. These are implementation recommendations; they are not claims that the original code already enforces them.&lt;/p&gt;

&lt;h2&gt;Step 4: Make Model Selection Server-Authoritative&lt;/h2&gt;

&lt;p&gt;A model selector should be backed by server-side configuration. For each enabled option, record the provider and the exact model identifier verified against current official documentation. The server should reject unknown providers, unknown models, and unsupported pairings before making an upstream request. This keeps a modified browser request from selecting arbitrary values the application did not intend to support.&lt;/p&gt;

&lt;p&gt;The supplied description of KISS Sorcar offers a useful example of the general concept: it reports a catalog containing OpenAI and Anthropic model categories and describes switching the backend when a task references a different model ID. That is evidence about KISS Sorcar, not about this tutorial’s proposed Next.js router. Do not imply that KISS Sorcar is a dependency, that its model catalog applies to your application, or that its behavior validates a particular SDK implementation.&lt;/p&gt;

&lt;p&gt;When you add another model, check the provider’s current documentation and account access first. Then update the server-owned registry, the user-facing label, and tests for valid and invalid pairings. Avoid hard-coding a model name in multiple places: duplications make it easier for the interface and server policy to drift apart.&lt;/p&gt;

&lt;h2&gt;Step 5: Verify Next.js Security and Deployment Versions&lt;/h2&gt;

&lt;p&gt;Security review is part of building a router, not a post-launch cleanup task. The supplied NVD context lists several Next.js issues and specific affected version ranges. CVE-2026-44572 affects versions from 12.2.0 up to, but not including, 15.5.16, and versions from 16.0.0 up to, but not including, 16.2.5. The supplied description concerns a middleware redirect behavior involving an &lt;code&gt;x-nextjs-data&lt;/code&gt; header and possible cached redirect responses in deployments behind a CDN or reverse proxy.&lt;/p&gt;

&lt;p&gt;The context also lists CVE-2026-44581 and CVE-2026-44580, with the stated fixed thresholds of 15.5.16 and 16.2.5. The summaries describe issues involving CSP nonces with shared caches and &lt;code&gt;beforeInteractive&lt;/code&gt; scripts with untrusted content, respectively. Check the NVD records and the relevant vendor advisories for the exact impact, affected configurations, and remediation before making a deployment decision.&lt;/p&gt;

&lt;p&gt;Do not assume that selecting a version described as “Next.js 15 or newer” is sufficient. That range can include affected releases. Check the exact version resolved by your lockfile and deployed artifact, then use a release that includes the applicable fixes. Review the deployment architecture as well: shared caches, middleware, script usage, and reverse proxies can affect exposure. The existence of a vulnerability record does not establish that every application is vulnerable in the same way.&lt;/p&gt;

&lt;h2&gt;Step 6: Test Contracts Before Testing Paid Model Calls&lt;/h2&gt;

&lt;p&gt;Start with tests that do not contact a model provider. Test that an allowed request passes, an unknown provider fails, an unknown model fails, malformed JSON is handled, over-limit input is rejected, and role ordering follows the policy you documented. Add a test for each provider/model pairing in the server registry. These tests verify your application’s own contract; they do not prove that an upstream SDK call is valid.&lt;/p&gt;

&lt;p&gt;Next, run a controlled integration test using credentials and a model that have been confirmed in current official provider documentation and are available to the account. Verify the actual HTTP status, response shape, and error path. Do not print credentials or full prompts into test logs. Record which package versions and model identifiers the test used so the result can be reproduced after a dependency or provider change.&lt;/p&gt;

&lt;p&gt;Test failures deliberately: missing credentials, invalid provider configuration, upstream errors, timeouts, and invalid or incomplete response data. Handle those cases according to the current SDK and provider behavior. The original draft proposed specific HTTP status mappings and SDK response fields, but the supplied context does not establish that those details are correct for the proposed integrations.&lt;/p&gt;

&lt;p&gt;Finally, run the application’s normal build and deployment checks for the exact Next.js version selected. Test the deployed route, not just the development server. Verify that secrets are not present in browser assets or public responses and that production configuration matches the server-side design.&lt;/p&gt;

&lt;h2&gt;Step 7: Fix the Draft’s Implementation Defects Before Reusing It&lt;/h2&gt;

&lt;p&gt;Several details in the original tutorial require correction independent of the provider documentation gap. Its schema accepts &lt;code&gt;assistant&lt;/code&gt; as a message role, while the prose claims assistant messages cannot be sent by the client. Its server accepts any bounded model string rather than checking an approved provider/model pair. Its explanation calls for authentication and rate limits before real users access the route, but the sample route does not implement either control. Those gaps mean the sample should not be described as production-ready.&lt;/p&gt;

&lt;p&gt;The shown shell examples also need to be checked. The Git ignore command uses unusual newline escapes, and the multiline &lt;code&gt;curl&lt;/code&gt; examples omit shell line-continuation characters as rendered. Do not assume a code block works because it looks plausible. Copy it into a clean environment, run it, and include the exact command that succeeds. Likewise, verify the test and lint scripts against the selected Next.js and tooling versions rather than assuming a script from an older template remains valid.&lt;/p&gt;

&lt;p&gt;Do not present rate limits, authentication, tenant budgets, observability, or moderation as features of the sample unless the code actually implements and tests them. They may be appropriate future work, but a list of possible improvements is not evidence that the current application provides those protections.&lt;/p&gt;

&lt;h2&gt;What to Confirm Before Adding Features&lt;/h2&gt;

&lt;p&gt;Once the basic path is validated, consider additional capabilities one at a time. Streaming requires provider-specific stream handling and a documented event contract. Tool calls require explicit authorization and validation. Structured output requires checking the provider’s supported format and validating the returned data. Usage reporting requires understanding the provider’s actual usage fields. None of these details is established by the sources supplied for this review.&lt;/p&gt;

&lt;p&gt;Keep a short integration record for each provider: documentation checked, SDK package and version, verified model identifiers, request and response examples, known error handling, and test date. Recheck it when dependencies or provider documentation change. This is particularly important for a router because a change in one adapter can affect multiple user-facing model choices.&lt;/p&gt;

&lt;p&gt;A sound multi-model router is not defined by the number of provider names in a dropdown. It is defined by a clear application contract, verified provider adapters, server-controlled model selection, tested failure handling, and a maintained dependency and security review. The available evidence supports the general idea of routing among models, but it does not certify the draft’s specific SDK code. Mark that distinction clearly until the integration is checked against current official sources.&lt;/p&gt;

&lt;h2&gt;Sources and Verification Notes&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://srmap.hosting.acm.org/blog/getting-started-with-nextjs" rel="noopener noreferrer"&gt;Getting Started with Next.js: A Beginner’s Guide&lt;/a&gt; describes Next.js as a React framework for web applications.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://arxiv.org/html/2604.23822v2" rel="noopener noreferrer"&gt;KISS Sorcar&lt;/a&gt; describes its multi-provider model catalog and per-call model switching. Those are KISS Sorcar capabilities, not proof of this tutorial’s implementation.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://nvd.nist.gov/vuln/detail/CVE-2026-44572" rel="noopener noreferrer"&gt;NVD: CVE-2026-44572&lt;/a&gt; lists affected Next.js ranges and describes the redirect-cache issue.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://nvd.nist.gov/vuln/search?resultType=records&amp;amp;cpeFilterMode=cpe&amp;amp;cpeName=cpe%3A2.3%3Aa%3Avercel%3Anext.js%3A16.0.5%3A%2A%3A%2A%3A%2A%3A%2A%3Anode.js%3A%2A%3A%2A" rel="noopener noreferrer"&gt;NVD Next.js search results&lt;/a&gt; include the supplied summaries for CVE-2026-44580 and CVE-2026-44581.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Editorial attribution: Gate of AI Editorial &amp;amp; Engineering Teams, GateOfAI, LLC.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>ai</category>
      <category>tutorial</category>
      <category>discuss</category>
    </item>
    <item>
      <title>Build a LlamaIndex Document RAG Assistant</title>
      <dc:creator>Gate of AI</dc:creator>
      <pubDate>Sun, 08 Nov 2026 17:12:42 +0000</pubDate>
      <link>https://dev.to/gateofai/build-a-llamaindex-document-rag-assistant-4bha</link>
      <guid>https://dev.to/gateofai/build-a-llamaindex-document-rag-assistant-4bha</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;🚀 Technical Briefing:&lt;/strong&gt; This tutorial is part of our deep-dive series on Agentic Workflows at &lt;a href="https://gateofai.com" rel="noopener noreferrer"&gt;Gate of AI&lt;/a&gt;. For the full technical breakdown, interactive code sandbox, and the native Arabic translation, visit the &lt;a href="https://gateofai.com/tutorial/llamaindex-document-rag-assistant/" rel="noopener noreferrer"&gt;original article here&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Tutorial · LlamaIndex · Retrieval-Augmented Generation&lt;/p&gt;

&lt;h1&gt;Build a LlamaIndex Document RAG Assistant&lt;/h1&gt;

&lt;p&gt;This guide explains the verified building blocks for a document question-answering assistant with LlamaIndex and OpenAI. It covers model and embedding configuration, document preparation, the distinction between basic RAG and agentic RAG, and how to think about persistence without presenting unverified code as tested implementation.&lt;/p&gt;

&lt;h2&gt;What This Guide Covers&lt;/h2&gt;

&lt;p&gt;Retrieval-Augmented Generation, or RAG, combines document retrieval with language-model responses. Instead of treating a question as an isolated prompt, a RAG workflow works with a collection of source material and uses that material as the basis for answering. LlamaIndex provides a framework for connecting documents, nodes, indexes, query components, and language-model integrations.&lt;/p&gt;

&lt;p&gt;The verified LlamaIndex example in the supplied material configures an OpenAI language model and an OpenAI embedding model through LlamaIndex. It uses &lt;code&gt;text-embedding-3-small&lt;/code&gt; with an explicitly selected embedding dimension of 256, and assigns the resulting model configuration through the framework’s &lt;code&gt;Settings&lt;/code&gt; object. This is a concrete configuration example, not a universal recommendation or a guarantee that any particular model or dimension is suitable for every corpus.&lt;/p&gt;

&lt;p&gt;This article is deliberately narrower than the original draft. The available references do not verify a complete, runnable Python application that reads arbitrary local files, persists an index to disk, reloads it, cites retrieved chunks, and passes the draft’s tests. Rather than imply that unverified implementation has been tested, the steps below explain the supported workflow and identify where implementation choices must be checked against the documentation for the LlamaIndex integrations you select.&lt;/p&gt;

&lt;h2&gt;Prerequisites and Scope&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Basic Python knowledge is appropriate for the Python configuration example discussed here. The cited DeepLearning.AI agentic RAG course specifically identifies basic Python knowledge as a suitable starting point.&lt;/li&gt;
&lt;li&gt;An OpenAI integration is used in the verified LlamaIndex configuration example. The sources do not establish account eligibility, current pricing, or access to a particular chat model.&lt;/li&gt;
&lt;li&gt;Prepare documents that you are permitted to use. The references describe document and multi-document RAG use cases, but do not certify support for every file type or parser.&lt;/li&gt;
&lt;li&gt;Decide whether your goal is straightforward document Q&amp;amp;A, summarization, or a more involved research assistant. These are related but distinct application patterns.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The guide does not set Python version requirements, prescribe package versions, or claim that a particular command installs a complete working application. Those details need to be confirmed against the versions and integrations chosen for an actual project.&lt;/p&gt;

&lt;h2&gt;Step 1: Understand the Document-to-Answer Workflow&lt;/h2&gt;

&lt;p&gt;A document RAG system has two broad concerns: preparing content for retrieval and answering questions using retrieved content. The verified MongoDB and LlamaIndex example demonstrates creating LlamaIndex document objects from source records and refers to document and node creation. It also shows LlamaIndex configuration for an OpenAI language model and an OpenAI embedding model. These are useful reference points for understanding the components of a RAG pipeline.&lt;/p&gt;

&lt;p&gt;At a conceptual level, content is represented in a form the indexing and retrieval components can work with; an embedding model is configured for semantic representation; and a language model is configured for responses. The actual parsing, node construction, storage, and query calls depend on the selected LlamaIndex integrations and storage backend. Do not assume that a directory reader supports a particular extension, that a given index persists automatically, or that a query response includes citations unless you have verified those behaviors in the integration you use.&lt;/p&gt;

&lt;p&gt;Keep the source corpus and generated index conceptually separate. The original documents remain the materials your assistant should consult. Index artifacts are derived data. When documents or embedding configuration change, check the selected integration’s guidance for updating or rebuilding its stored representation. The available references include a community discussion specifically titled “Persistence of Embeddings,” and a LlamaIndex JavaScript course that lists persisting data among its topics. They do not, however, establish the Python disk-storage commands used in the draft.&lt;/p&gt;

&lt;h2&gt;Step 2: Configure LlamaIndex with OpenAI&lt;/h2&gt;

&lt;p&gt;The following is the verified configuration pattern from the supplied Hugging Face example. It demonstrates the LlamaIndex settings and OpenAI integrations; it is not a complete application and does not perform ingestion, persistence, or querying by itself.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;from llama_index.core.settings import Settings
from llama_index.llms.openai import OpenAI
from llama_index.embeddings.openai import OpenAIEmbedding

embed_model = OpenAIEmbedding(
    model="text-embedding-3-small",
    dimensions=256,
)
llm = OpenAI()

Settings.llm = llm
Settings.embed_model = embed_model&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice what this snippet does and does not establish. It selects an embedding integration and a model name, supplies a dimension value, constructs an OpenAI LLM integration, and assigns both through LlamaIndex settings. The source does not specify a chat model in the &lt;code&gt;OpenAI()&lt;/code&gt; call. Therefore, this guide does not substitute a model name or claim that the unqualified constructor selects a particular model in every version or environment. Consult the current integration documentation for the exact supported configuration and required credentials.&lt;/p&gt;

&lt;p&gt;Embedding configuration is part of the index design, not merely a query-time option. If you change the embedding model or its dimensions, check the storage integration’s requirements before reusing existing vectors. The available sources do not prescribe a migration process, so do not assume that vectors created under different configurations can be combined or reused interchangeably.&lt;/p&gt;

&lt;h2&gt;Step 3: Prepare Documents and Their Metadata&lt;/h2&gt;

&lt;p&gt;RAG quality depends in part on the content supplied to the system. The verified MongoDB example creates a LlamaIndex &lt;code&gt;Document&lt;/code&gt; with document text and metadata. It also demonstrates excluding selected metadata keys from language-model and embedding-model use. This is a useful reminder that document text and metadata have different roles and may need deliberate handling.&lt;/p&gt;

&lt;p&gt;For your own corpus, start by choosing a small set of representative documents and inspecting the text that your chosen loader or preprocessing path actually produces. Check that important headings, tables, names, and relationships survive extraction. This is a practical validation step; the supplied sources do not guarantee that any particular parser handles PDF, DOCX, HTML, or other formats correctly.&lt;/p&gt;

&lt;p&gt;Metadata can describe a source record, while exclusions can control which metadata fields are considered for particular model operations. The example lists fields excluded from LLM and embedding metadata, including fields such as identifiers and review-related data. Treat that source as an illustration rather than a universal list: the right fields depend on your documents and intended use. Avoid sending irrelevant or sensitive metadata to a model without first deciding whether it is needed.&lt;/p&gt;

&lt;p&gt;Before indexing a large collection, test a few documents end to end. Confirm that the text and metadata represented by the framework match your expectations. Then form questions whose answers are plainly present in those documents and inspect whether the application can retrieve useful evidence. This small test corpus makes it easier to identify extraction or configuration problems before expanding the scope.&lt;/p&gt;

&lt;h2&gt;Step 4: Choose an Index and Persistence Approach&lt;/h2&gt;

&lt;p&gt;The verified context includes a LlamaIndex MongoDB vector-store integration and installation references for the &lt;code&gt;llama-index-vector-stores-mongodb&lt;/code&gt; and &lt;code&gt;pymongo&lt;/code&gt; packages. That establishes MongoDB as one documented integration in the cited example. It does not provide enough detail here to give a complete MongoDB connection, index-creation, or query implementation. Follow the integration’s current documentation for those operational details rather than copying an invented connection recipe.&lt;/p&gt;

&lt;p&gt;Persistence is a separate design decision. The sources include a community item about embedding persistence and a JavaScript LlamaIndex course whose stated topics include persisting data. The course description also discusses building a full-stack JavaScript RAG app and using the &lt;code&gt;create-llama&lt;/code&gt; command-line tool. These references support persistence as a relevant RAG capability and learning topic; they do not verify that the draft’s Python &lt;code&gt;storage/&lt;/code&gt; directory approach, rebuild procedure, or atomic replacement logic works as written.&lt;/p&gt;

&lt;p&gt;When selecting persistence for a real application, identify which component owns the stored vectors and related index data, how the chosen integration restores them, and how updates are handled. Test the lifecycle—initial creation, a later process restart, a document update, and a rebuild—against the backend and framework versions you actually deploy. Keep those checks as implementation tests; do not infer behavior from a folder name or from a different language integration.&lt;/p&gt;

&lt;h2&gt;Step 5: Start with Q&amp;amp;A and Summarization&lt;/h2&gt;

&lt;p&gt;A simple RAG assistant can begin with two distinct document tasks: answering questions and summarizing content. DeepLearning.AI’s verified LlamaIndex agentic RAG course describes building a router over a single document that selects between a Q&amp;amp;A query engine and a summarization query engine. The course then extends the pattern to tool calling, argument selection, multi-step research, and multi-document agents.&lt;/p&gt;

&lt;p&gt;That progression helps keep an initial project manageable. First decide what behavior users need. If they ask direct questions about a document, evaluate Q&amp;amp;A. If they ask for an overview, evaluate summarization. If the application must choose between these behaviors, a router is a relevant next pattern. The source establishes that the course teaches such a router; it does not provide a complete implementation in the supplied excerpt, so this guide does not invent one.&lt;/p&gt;

&lt;p&gt;For a research assistant, the cited course describes an agent that can reason over tools through multiple steps and a multi-document agent that extends research across documents. The course frames agentic RAG as useful for complex requests that may require gathering relevant parts and synthesizing what multiple research papers say. This is a meaningful expansion from a basic retrieval-and-answer workflow, not a prerequisite for every document assistant.&lt;/p&gt;

&lt;h2&gt;Step 6: Evaluate with Representative Questions&lt;/h2&gt;

&lt;p&gt;Test the system using questions tied to the documents you selected. Include direct questions, requests for a summary, and questions that require information from more than one document if multi-document use is part of your goal. Review the retrieved material and generated response rather than judging only whether the answer sounds fluent. The provided sources support Q&amp;amp;A, summarization, and multi-document research as application patterns, but do not prescribe a specific evaluation metric or guarantee an accuracy level.&lt;/p&gt;

&lt;p&gt;When an answer is poor, separate the possible causes. The source text might not contain the needed fact; extraction might have changed the content; the selected retrieval or query flow might not fit the question; or the response model may have received unsuitable context. Inspect each stage in the implementation you are using. Do not treat a fluent response as proof that the retrieved documents support it.&lt;/p&gt;

&lt;p&gt;For agentic workflows, the cited course also emphasizes debugging an agent and guiding its actions. Its lesson description discusses stepping through what an agent is doing and optionally providing guidance at intermediate steps. That is especially relevant when a multi-step process searches the wrong document or follows an unhelpful path. Begin with a simpler workflow when it meets the need, and add agentic behavior only when the task warrants it.&lt;/p&gt;

&lt;h2&gt;Step 7: Expand to Multiple Documents and Tool Use&lt;/h2&gt;

&lt;p&gt;Once a single-document workflow has been understood, the verified course material describes extending a research agent to multiple documents. It also covers a router choosing between query engines, tool calling that selects a function and infers an argument, and multi-step reasoning with tool use. These concepts provide a roadmap for developers whose questions cannot be handled well by one fixed query path.&lt;/p&gt;

&lt;p&gt;Do not collapse these capabilities into one claim that every LlamaIndex assistant automatically behaves as an autonomous research agent. The course presents them as patterns learners build. A basic document assistant and a multi-step agent have different levels of complexity. Choose the simplest pattern that serves the questions your users actually ask, then test additional routing or tool behavior against concrete examples.&lt;/p&gt;

&lt;p&gt;Developers who prefer JavaScript have a separate verified learning path in the supplied context. The JavaScript RAG web-app course describes querying personal data, using a router query engine across multiple data sources, building a backend and React frontend, and learning about persistence and streaming responses. That is a distinct course and implementation path; it should not be conflated with the Python examples in this article.&lt;/p&gt;

&lt;h2&gt;Common Mistakes to Avoid&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Assuming a model choice is verified:&lt;/strong&gt; the cited configuration explicitly names &lt;code&gt;text-embedding-3-small&lt;/code&gt;, but does not name a chat model in its &lt;code&gt;OpenAI()&lt;/code&gt; call. Verify the model selection you use.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Confusing persistence with a particular storage recipe:&lt;/strong&gt; persistence is covered in the supplied learning context, but the Python local-storage implementation in the original draft is not verified by it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Treating every question as the same task:&lt;/strong&gt; the cited course distinguishes Q&amp;amp;A from summarization and teaches routing between them.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Adding an agent before validating the basics:&lt;/strong&gt; multi-step tool use and multi-document research are advanced patterns in the cited course, not automatic requirements for all RAG applications.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Publishing code without executing it:&lt;/strong&gt; the original draft contains newline and shell-command defects. Test every code block in the stated environment before publication.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Key Takeaways&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;LlamaIndex can be configured with an OpenAI LLM integration and an OpenAI embedding integration; the supplied example uses &lt;code&gt;text-embedding-3-small&lt;/code&gt; with a dimension of 256.&lt;/li&gt;
&lt;li&gt;The verified materials cover document and node preparation, a MongoDB vector-store integration, and persistence as a broader RAG topic.&lt;/li&gt;
&lt;li&gt;Agentic RAG patterns described by DeepLearning.AI include a Q&amp;amp;A/summarization router, tool calling, multi-step research, and multi-document agents.&lt;/li&gt;
&lt;li&gt;The available sources do not verify the original draft’s complete Python application, local persistence workflow, or model-specific operational claims.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Use the cited configuration as a starting reference, then verify ingestion, storage, retrieval, and query behavior against the current documentation for your chosen LlamaIndex integrations. Begin with a clear document task, inspect results on a small corpus, and add routing or multi-step agent behavior only when your use case calls for it.&lt;/p&gt;

&lt;h2&gt;Sources&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://huggingface.co/blog/Andyrasika/mongodb-llamaindex-rag" rel="noopener noreferrer"&gt;Hugging Face: Elevate Responses—RAG with LlamaIndex &amp;amp; MongoDB&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.deeplearning.ai/courses/building-agentic-rag-with-llamaindex" rel="noopener noreferrer"&gt;DeepLearning.AI: Building Agentic RAG with LlamaIndex&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://learn.deeplearning.ai/courses/building-agentic-rag-with-llamaindex/lesson/yd6nd/introduction" rel="noopener noreferrer"&gt;DeepLearning.AI: Building Agentic RAG with LlamaIndex, Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.deeplearning.ai/courses/javascript-rag-web-apps-with-llamaindex" rel="noopener noreferrer"&gt;DeepLearning.AI: JavaScript RAG Web Apps with LlamaIndex&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Editorial review by the Gate of AI Editorial &amp;amp; Engineering Teams. GateOfAI, LLC is a Delaware, USA company.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>ai</category>
      <category>tutorial</category>
      <category>discuss</category>
    </item>
    <item>
      <title>Build a Typed FastAPI API with Pydantic</title>
      <dc:creator>Gate of AI</dc:creator>
      <pubDate>Sun, 08 Nov 2026 17:12:32 +0000</pubDate>
      <link>https://dev.to/gateofai/build-a-typed-fastapi-api-with-pydantic-3f0k</link>
      <guid>https://dev.to/gateofai/build-a-typed-fastapi-api-with-pydantic-3f0k</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;🚀 Technical Briefing:&lt;/strong&gt; This tutorial is part of our deep-dive series on Agentic Workflows at &lt;a href="https://gateofai.com" rel="noopener noreferrer"&gt;Gate of AI&lt;/a&gt;. For the full technical breakdown, interactive code sandbox, and the native Arabic translation, visit the &lt;a href="https://gateofai.com/tutorial/typed-fastapi-api-pydantic/" rel="noopener noreferrer"&gt;original article here&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;


&lt;p&gt;&lt;strong&gt;Tutorial | Intermediate&lt;/strong&gt;&lt;/p&gt;
&lt;br&gt;
  &lt;h1&gt;Build a Typed FastAPI Service with Pydantic&lt;/h1&gt;
&lt;br&gt;
  &lt;p&gt;This guide builds a small typed HTTP service using FastAPI and Pydantic. It demonstrates request validation, a stable response contract, and the framework's route-first API structure. It does not claim a verified OpenAI or Anthropic integration: the supplied reference material does not establish provider SDK calls, model identifiers, retry policies, or cross-provider failover behavior.&lt;/p&gt;


&lt;h2&gt;What this tutorial covers&lt;/h2&gt;
&lt;br&gt;
  &lt;p&gt;FastAPI is described in the verified material as a modern Python framework for building APIs. The referenced reviews highlight its asynchronous capabilities, Pydantic validation, and automatic interactive API documentation. Those are the capabilities this example uses: a route receives a typed request, validates it through a Pydantic model, and returns a typed response documented by the framework.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;The example uses a support-ticket classification-shaped contract, but it deliberately does not call a language model. That distinction matters. A validated HTTP API is not, by itself, an AI router. To route requests to OpenAI or Anthropic, an implementation also needs provider-specific clients and verified configuration, response handling, error behavior, and policy decisions. Those details cannot be responsibly supplied from the available sources here.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;The verified context also describes a wider architectural distinction. FastAPI is route-first: an HTTP route declaration is central to registering an endpoint and its schema. If the same capability must also be exposed as an MCP tool, the context says a separate registration may be needed, with independently maintained declarations. HarnessAPI's research describes a skill-first alternative that projects a skill and its type contracts onto transports. This tutorial stays with ordinary FastAPI routes and does not implement MCP or HarnessAPI.&lt;/p&gt;


&lt;h2&gt;Prerequisites&lt;/h2&gt;
&lt;br&gt;
  &lt;ul&gt;

    &lt;li&gt;Python and familiarity with functions, type annotations, and JSON.&lt;/li&gt;

    &lt;li&gt;A terminal where you can install Python packages and run a local development server.&lt;/li&gt;

    &lt;li&gt;Basic understanding of HTTP requests and responses.&lt;/li&gt;

  &lt;/ul&gt;
&lt;br&gt;
  &lt;p&gt;No model API key is required because the sample does not make provider calls. Package versions and provider model identifiers are not specified by the verified context, so this guide avoids claiming specific compatible version floors.&lt;/p&gt;


&lt;h2&gt;Step 1: Create a project and install the framework&lt;/h2&gt;
&lt;br&gt;
  &lt;p&gt;Create a project directory and a virtual environment. Install FastAPI and an ASGI server using your normal Python package workflow. For a shared or deployed project, choose and lock versions that your team has tested; the supplied sources do not verify particular current version numbers.&lt;/p&gt;
&lt;br&gt;
  &lt;pre&gt;&lt;code&gt;mkdir typed-fastapi-service&lt;br&gt;
cd typed-fastapi-service&lt;br&gt;
python -m venv .venv
&lt;h1&gt;
  
  
  macOS or Linux
&lt;/h1&gt;

&lt;p&gt;source .venv/bin/activate&lt;/p&gt;
&lt;h1&gt;
  
  
  Windows PowerShell
&lt;/h1&gt;
&lt;h1&gt;
  
  
  .venv\Scripts\Activate.ps1
&lt;/h1&gt;

&lt;p&gt;python -m pip install fastapi uvicorn&lt;/p&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;br&gt;
  &lt;p&gt;Create a file named &lt;code&gt;main.py&lt;/code&gt; in the project directory. FastAPI uses route declarations to associate HTTP methods and paths with Python endpoint functions. The function's type annotations and Pydantic models can describe the data expected by the endpoint.&lt;/p&gt;


&lt;h2&gt;Step 2: Define typed request and response models&lt;/h2&gt;
&lt;br&gt;
  &lt;p&gt;Define the data contract before writing the route. In this example, the request includes a subject and message. The response is a simple acknowledgement. The sample intentionally avoids claiming that a model has classified the ticket: the endpoint has not called a model and should not misrepresent its output as AI-generated analysis.&lt;/p&gt;
&lt;br&gt;
  &lt;pre&gt;&lt;code&gt;from pydantic import BaseModel, Field

&lt;p&gt;class TicketRequest(BaseModel):&lt;br&gt;
    subject: str = Field(min_length=3, max_length=200)&lt;br&gt;
    body: str = Field(min_length=10, max_length=8000)&lt;/p&gt;

&lt;p&gt;class TicketAccepted(BaseModel):&lt;br&gt;
    status: str&lt;br&gt;
    subject: str&lt;/p&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;br&gt;
  &lt;p&gt;The model declarations make the intended input and output shapes visible in Python. The constraints define minimum and maximum lengths for the two request fields. Pydantic validation is the part of this pattern supported by the provided context: the HarnessAPI description specifically discusses using Pydantic input-model validation and returning an HTTP 422 response when validation fails.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;These models are application contracts, not instructions to a language model. They do not ensure that external model output is safe or correct. If a later implementation calls a model, its response must be treated as external data and validated against an appropriate output contract before the application relies on it. The supplied context does not provide enough information to prescribe provider-specific response parsing.&lt;/p&gt;


&lt;h2&gt;Step 3: Add a route-first FastAPI endpoint&lt;/h2&gt;
&lt;br&gt;
  &lt;p&gt;Use a route decorator to register the endpoint and connect the request model to the function. Return the declared response model. This illustrates the route-first structure described in the verified research: route registration is the organizing unit for the HTTP service.&lt;/p&gt;
&lt;br&gt;
  &lt;pre&gt;&lt;code&gt;from fastapi import FastAPI

&lt;p&gt;from main_models import TicketAccepted, TicketRequest&lt;/p&gt;

&lt;p&gt;app = FastAPI(&lt;br&gt;
    title="Typed Ticket API",&lt;br&gt;
    description="A small API example using typed request and response models.",&lt;br&gt;
    version="1.0.0",&lt;br&gt;
)&lt;/p&gt;

&lt;p&gt;@app.post("/tickets", response_model=TicketAccepted)&lt;br&gt;
async def accept_ticket(ticket: TicketRequest) -&amp;gt; TicketAccepted:&lt;br&gt;
    return TicketAccepted(&lt;br&gt;
        status="accepted",&lt;br&gt;
        subject=ticket.subject,&lt;br&gt;
    )&lt;/p&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;br&gt;
  &lt;p&gt;For this compact example, keep the models and application in one file rather than importing them from a second module. Replace the preceding code with this complete single-file version as &lt;code&gt;main.py&lt;/code&gt;:&lt;/p&gt;
&lt;br&gt;
  &lt;pre&gt;&lt;code&gt;from fastapi import FastAPI&lt;br&gt;
from pydantic import BaseModel, Field

&lt;p&gt;class TicketRequest(BaseModel):&lt;br&gt;
    subject: str = Field(min_length=3, max_length=200)&lt;br&gt;
    body: str = Field(min_length=10, max_length=8000)&lt;/p&gt;

&lt;p&gt;class TicketAccepted(BaseModel):&lt;br&gt;
    status: str&lt;br&gt;
    subject: str&lt;/p&gt;

&lt;p&gt;app = FastAPI(&lt;br&gt;
    title="Typed Ticket API",&lt;br&gt;
    description="A small API example using typed request and response models.",&lt;br&gt;
    version="1.0.0",&lt;br&gt;
)&lt;/p&gt;

&lt;p&gt;@app.post("/tickets", response_model=TicketAccepted)&lt;br&gt;
async def accept_ticket(ticket: TicketRequest) -&amp;gt; TicketAccepted:&lt;br&gt;
    return TicketAccepted(&lt;br&gt;
        status="accepted",&lt;br&gt;
        subject=ticket.subject,&lt;br&gt;
    )&lt;/p&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;br&gt;
  &lt;p&gt;The route accepts a &lt;code&gt;TicketRequest&lt;/code&gt;, not an arbitrary dictionary. FastAPI can use the model and endpoint declaration to describe the HTTP interface. The verified reviews specifically call out automatic interactive documentation and OpenAPI generation as useful FastAPI features. The example makes those generated descriptions available through the framework's documentation interface; it does not claim that the documentation substitutes for authentication or operational controls.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;Run the service locally:&lt;/p&gt;
&lt;br&gt;
  &lt;pre&gt;&lt;code&gt;uvicorn main:app --reload&lt;/code&gt;&lt;/pre&gt;
&lt;br&gt;
  &lt;p&gt;Then open the local documentation page at &lt;code&gt;/docs&lt;/code&gt; on the development server. Use it to inspect the endpoint's request and response shapes and try a request. Interactive docs are a development convenience and a representation of the declared API contract; they do not add an AI provider or business behavior that the endpoint does not implement.&lt;/p&gt;


&lt;h2&gt;Step 4: Exercise validation and inspect the response&lt;/h2&gt;
&lt;br&gt;
  &lt;p&gt;Send a request whose values satisfy the declared constraints. For example:&lt;/p&gt;
&lt;br&gt;
  &lt;pre&gt;&lt;code&gt;curl --request POST "&lt;a href="http://127.0.0.1:8000/tickets" rel="noopener noreferrer"&gt;http://127.0.0.1:8000/tickets&lt;/a&gt;" \&lt;br&gt;
  --header "Content-Type: application/json" \&lt;br&gt;
  --data '{&lt;br&gt;
    "subject": "Cannot sign in after password reset",&lt;br&gt;
    "body": "The reset link worked, but the sign-in page rejects the new password."&lt;br&gt;
  }'&lt;/code&gt;&lt;/pre&gt;
&lt;br&gt;
  &lt;p&gt;The endpoint returns an acknowledgement containing the subject. It does not assign a category, score urgency, generate a reply, or contact a model provider. If a required field is missing or violates a declared constraint, the request-model validation path rejects the input. The HarnessAPI source describes Pydantic validation errors being returned as HTTP 422 in its routing design; this example relies on FastAPI's model-based request handling rather than implementing that separate framework's endpoint.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;Try changing the subject to a value shorter than the minimum or removing the body field. Inspect the response and the generated API documentation. This is a useful way to check that the declared schema is connected to the actual route instead of existing only as an unused Python class.&lt;/p&gt;


&lt;h2&gt;Where a provider router would fit&lt;/h2&gt;
&lt;br&gt;
  &lt;p&gt;A real AI router needs an additional layer beyond this typed HTTP boundary. At a minimum, a design must define how provider configuration is supplied, which provider is selected, how provider responses are converted into an application-owned output shape, and how failures are represented to callers. It also needs tested provider SDK calls and model identifiers. None of those OpenAI- or Anthropic-specific facts are established by the verified material supplied for this audit, so this guide does not invent them or label this example a functioning dual-provider router.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;Keep provider behavior separate from the FastAPI route when adding a verified implementation. The route should express the HTTP contract; a distinct component can own a provider call and translate its result into application types. Validate any returned structured data before using it. The boundary between a declared Python schema and an external model response should be explicit, rather than assuming generated text automatically satisfies the application's requirements.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;The verified HarnessAPI paper offers a related architectural point. In route-first designs, adding a second transport such as MCP can involve a second registration in a different vocabulary, and the paper notes that separately declared schemas can drift when a Pydantic model changes. Its skill-first proposal instead treats the typed skill as the central unit and projects it onto transports. That is a research-described approach, not a feature implemented by this FastAPI sample. Choose an architecture based on the transports the application actually needs, and verify the behavior of the framework you adopt.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;The supplied reporting on PydanticAI describes a model-agnostic agent framework and highlights Python-native control, type safety, and Logfire integration. However, that reporting says Anthropic support was planned in its described context. It should not be read as proof of current Anthropic compatibility or as a substitute for checking current official documentation before selecting a provider stack.&lt;/p&gt;


&lt;h2&gt;Common mistakes to avoid&lt;/h2&gt;
&lt;br&gt;
  &lt;ul&gt;

    &lt;li&gt;
&lt;strong&gt;Calling a typed endpoint an AI router.&lt;/strong&gt; This sample validates and acknowledges a request; it does not make a model call.&lt;/li&gt;

    &lt;li&gt;
&lt;strong&gt;Assuming a schema validates every downstream value.&lt;/strong&gt; The request model covers the incoming HTTP data. Any external response needs its own suitable validation boundary.&lt;/li&gt;

    &lt;li&gt;
&lt;strong&gt;Confusing OpenAPI documentation with implementation.&lt;/strong&gt; Generated documentation describes declared routes and models; it does not implement provider access or operational policy.&lt;/li&gt;

    &lt;li&gt;
&lt;strong&gt;Duplicating transport contracts without considering drift.&lt;/strong&gt; The verified HarnessAPI research identifies separately maintained HTTP and MCP declarations as a maintenance concern and describes a skill-first alternative.&lt;/li&gt;

    &lt;li&gt;
&lt;strong&gt;Assuming provider support from a broad framework description.&lt;/strong&gt; Check the current provider documentation and tested SDK behavior before claiming compatibility.&lt;/li&gt;

  &lt;/ul&gt;


&lt;h2&gt;Key takeaways&lt;/h2&gt;
&lt;br&gt;
  &lt;p&gt;FastAPI's route-first model gives a Python endpoint a clear HTTP registration point. Pydantic models describe typed inputs and outputs, and FastAPI can generate interactive API documentation from the declared interface. The verified context supports those fundamentals and the importance of Pydantic validation; it does not verify the draft's specific dual-provider code, retry implementation, failover policy, or production claims.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;Use this example as a typed API foundation, not as a finished AI router. Before adding OpenAI or Anthropic, verify the current SDK documentation and model availability, implement and test provider-specific adapters, define explicit error and data-handling behavior, and validate model output against an application-owned schema. If the service also needs MCP exposure, account for the separate-registration maintenance issue identified in the verified research and evaluate whether a skill-first design is appropriate.&lt;/p&gt;


&lt;p&gt;Editorial review by the Gate of AI Editorial &amp;amp; Engineering Teams. Gate of AI operates under GateOfAI, LLC, a Delaware, USA entity.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>ai</category>
      <category>tutorial</category>
      <category>discuss</category>
    </item>
    <item>
      <title>Build a Memory-Backed TypeScript Coding Agent</title>
      <dc:creator>Gate of AI</dc:creator>
      <pubDate>Sat, 31 Oct 2026 14:56:02 +0000</pubDate>
      <link>https://dev.to/gateofai/build-a-memory-backed-typescript-coding-agent-43k5</link>
      <guid>https://dev.to/gateofai/build-a-memory-backed-typescript-coding-agent-43k5</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;🚀 Technical Briefing:&lt;/strong&gt; This tutorial is part of our deep-dive series on Agentic Workflows at &lt;a href="https://gateofai.com" rel="noopener noreferrer"&gt;Gate of AI&lt;/a&gt;. For the full technical breakdown, interactive code sandbox, and the native Arabic translation, visit the &lt;a href="https://gateofai.com/tutorial/memory-backed-typescript-coding-agent/" rel="noopener noreferrer"&gt;original article here&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;


&lt;p&gt;&lt;strong&gt;Tutorial · TypeScript agent architecture&lt;/strong&gt;&lt;/p&gt;
&lt;br&gt;
  &lt;h1&gt;Build a Memory-Backed TypeScript Coding Agent&lt;/h1&gt;
&lt;br&gt;
  &lt;p&gt;Learn the architecture behind a coding agent that carries useful knowledge across sessions. This guide focuses on verified design principles: persistent memory outside the model, retrieval of relevant context and tools, structured fact extraction, and a controlled tool-use loop. It does not present an unverified Bun, SQLite, or OpenAI integration as a tested implementation.&lt;/p&gt;


&lt;h2&gt;What You Will Build&lt;/h2&gt;
&lt;br&gt;
  &lt;p&gt;You will plan a TypeScript coding-agent system that can receive a repository task, gather relevant project context, request actions through tools, and preserve selected facts for later sessions. The central design goal is not to save every conversation. It is to make useful knowledge available when the next task begins.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;That distinction matters because a model’s immediate conversation context is not the same thing as long-term memory. A memory-aware agent treats memory as persistent, structured infrastructure outside the model. At startup, it can load prior context; while working, it can retrieve relevant state and tools; after an interaction, it can extract or refine facts and write them back. This makes memory a designed subsystem rather than an ever-growing transcript.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;The supplied evidence does not verify a particular Bun runtime, SQLite schema, FTS5 search implementation, OpenAI SDK version, or complete coding-agent code sample. Accordingly, this tutorial gives an implementation plan and architectural checkpoints, not a copy-and-paste program. Choose and verify the runtime, storage adapter, model provider, and API usage against their current official documentation before writing production code.&lt;/p&gt;


&lt;h2&gt;Prerequisites&lt;/h2&gt;
&lt;br&gt;
  &lt;ul&gt;

    &lt;li&gt;Comfort with TypeScript, asynchronous application flows, and agent tool concepts.&lt;/li&gt;

    &lt;li&gt;A clear definition of the repository or project the agent is intended to assist.&lt;/li&gt;

    &lt;li&gt;A decision about which information may be retained between sessions and which must not be stored.&lt;/li&gt;

    &lt;li&gt;A model provider and storage technology selected from their current documentation, with credentials handled outside source code.&lt;/li&gt;

  &lt;/ul&gt;


&lt;h2&gt;Step 1: Define the Agent’s Memory Contract&lt;/h2&gt;
&lt;br&gt;
  &lt;p&gt;Begin with a written contract that states what the agent may remember, how those facts will be used, and how they can be corrected or removed. Memory engineering treats long-term memory as first-class infrastructure: it exists outside the model and is structured so that an agent can use it deliberately. This is a more useful starting point than simply retaining every message and placing the entire history into every future prompt.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;For a coding assistant, candidate memory categories might include project conventions, architectural decisions, known risks, and commands or procedures confirmed during prior work. These are design examples, not a claim that any specific framework stores those categories automatically. Keep the contract narrow: retain only durable information that could help a future repository task, and distinguish confirmed observations from assumptions.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;Write down the boundary between session context and long-term memory. A task-specific question or temporary debugging detail may be useful only while the current task is active. A confirmed project convention may be useful later. A secret, credential, or unrelated personal detail should not become a durable project memory. The verified sources establish the value of structured memory and fact-extraction pipelines, but they do not prescribe a universal retention policy; define one for your application.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;Also decide who or what can update the memory. A write-back loop can let an agent update its own memory autonomously, but that capability is a design choice, not proof that every proposed fact is correct. Specify how updates will be checked, how conflicting facts will be handled, and how a human can inspect or correct stored knowledge.&lt;/p&gt;


&lt;h2&gt;Step 2: Design the Memory Lifecycle&lt;/h2&gt;
&lt;br&gt;
  &lt;p&gt;Plan memory as a lifecycle with four distinct stages: loading, retrieval, consolidation, and write-back. Keeping these stages separate makes it easier to reason about what information enters a model request and why a fact was preserved.&lt;/p&gt;
&lt;br&gt;
  &lt;ol&gt;

    &lt;li&gt;
&lt;strong&gt;Load at startup.&lt;/strong&gt; Initialize the agent with the persistent state appropriate to its task. The objective is to begin with useful prior context, not to indiscriminately replay every previous interaction.&lt;/li&gt;

    &lt;li&gt;
&lt;strong&gt;Retrieve for the current task.&lt;/strong&gt; Select the facts and tools that are relevant to the task at hand. Memory-aware agent design uses retrieval to assemble context, state, and tools during execution.&lt;/li&gt;

    &lt;li&gt;
&lt;strong&gt;Extract and consolidate.&lt;/strong&gt; Turn conversation evidence into structured facts, then consolidate episodic information into more reusable semantic knowledge where appropriate. The source material describes these as memory-engineering patterns; it does not provide a universal schema or extraction prompt.&lt;/li&gt;

    &lt;li&gt;
&lt;strong&gt;Write back deliberately.&lt;/strong&gt; Store useful updates so a later session can retrieve them. Treat this as a separate operation with its own validation and retention rules, rather than assuming every model response belongs in long-term storage.&lt;/li&gt;

  &lt;/ol&gt;
&lt;br&gt;
  &lt;p&gt;This lifecycle also clarifies the difference between a record and a useful memory. A transcript is a record of what was said. A durable memory is selected information intended to help with future work. Converting the former into the latter requires extraction, structure, and consolidation; simply preserving more text does not by itself create better recall.&lt;/p&gt;


&lt;h2&gt;Step 3: Decide How Retrieval Will Work&lt;/h2&gt;
&lt;br&gt;
  &lt;p&gt;Retrieval is the bridge between persistent storage and the current task. A coding agent may have far more stored context or available tools than it can use effectively in one request. The verified course description specifically highlights semantic search as a way to scale tool access and retrieve only relevant tools at inference time, addressing the challenge of agents with hundreds of tools.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;Before choosing a search method, list the information the agent must find. Project conventions, an architectural decision, or a tool description may call for different retrieval behavior. Establish what relevance means for each category, what scope applies to a result, and how the agent should behave when there is no useful match. These are application design questions; the provided context does not verify that a particular database, search index, ranking formula, or embedding model is required.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;Keep retrieval focused on the task. Supplying every stored fact can recreate the same problem as passing an ever-growing transcript: the model receives more material than it needs. A useful memory system assembles relevant context rather than treating the whole store as a prompt. Inspect the retrieved items during development and test whether they help with representative tasks instead of assuming that a successful search call means the result is useful.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;Tools can be treated as procedural memory: capabilities that the agent can retrieve when needed, rather than a fixed list that grows without limit in every interaction. The verified course describes this pattern as a way to scale tool access through semantic search. It does not specify an implementation for a coding agent, so treat the details—tool metadata, selection rules, and invocation policies—as decisions to document and verify in your own system.&lt;/p&gt;


&lt;h2&gt;Step 4: Build the Agent’s Tool-Use Loop&lt;/h2&gt;
&lt;br&gt;
  &lt;p&gt;A coding agent generally needs a repeating interaction pattern. The verified description of AI coding agents gives the core cycle: the agent receives input and prepares a prompt; the model may answer the user or request a tool call; the application executes a requested tool and returns its output; the model is then queried again. The process repeats until the model provides a final assistant response instead of requesting another action.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;Use that cycle to plan the boundary between the model and your application. The model can request an action, but the application is responsible for deciding what tools exist and executing them. For a coding assistant, identify which operations are needed for the task and document how each operation will be checked before it is run. Do not treat a model-generated request as proof that the action is appropriate or that it succeeded.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;Keep tool results connected to the request that produced them so the agent can interpret the outcome. The model should not claim that it inspected a file, made a change, or completed a validation unless the application has returned evidence for that action. This is a practical design requirement for truthful reporting, not a guarantee that a prompt alone can enforce correctness.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;Set explicit stopping and review conditions as part of the design. The verified context does not prescribe a particular iteration limit, timeout, permission scheme, or file-access sandbox. Those operational controls must be selected and tested for the application rather than presented as already supplied by an agent framework or model provider.&lt;/p&gt;


&lt;h2&gt;Step 5: Choose a TypeScript Framework or Build Your Own Harness&lt;/h2&gt;
&lt;br&gt;
  &lt;p&gt;If you prefer a framework rather than assembling every component yourself, Mastra is described in the verified context as a modern TypeScript framework for AI-powered applications and agents. Its listed capabilities include workflows, memory, streaming, evaluations, tracing, and Studio, an interactive interface for development and testing. The reported starter command is:&lt;/p&gt;
&lt;br&gt;
  &lt;pre&gt;&lt;code&gt;npm create mastra@latest&lt;/code&gt;&lt;/pre&gt;
&lt;br&gt;
  &lt;p&gt;Use the framework’s current documentation to confirm generated files, configuration, model-provider setup, memory adapters, and supported deployment choices. The verified information does not establish the exact APIs or configuration for connecting Mastra to Bun, SQLite, or a particular OpenAI model. Do not infer those integrations from a feature list; verify them against up-to-date framework and provider documentation.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;Alternatively, a custom TypeScript harness gives you direct responsibility for the agent loop and memory lifecycle. That can be appropriate when you need a narrow system, but it also means you must design and test persistence, retrieval, tool execution, error handling, and evaluation yourself. The choice is not simply “framework versus no framework”: compare the capabilities you need with the implementation and maintenance work you are prepared to own.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;For either option, write down the components that actually exist in your chosen implementation. A diagram might include a task entry point, context assembly, model interaction, tool execution, persistent memory, and evaluation. Do not label a component as secure, durable, or production-ready solely because it appears in a diagram or framework feature list.&lt;/p&gt;


&lt;h2&gt;Step 6: Account for Context Growth and Agent Limits&lt;/h2&gt;
&lt;br&gt;
  &lt;p&gt;A memory-backed agent still needs a strategy for the immediate conversation. The verified reporting on OpenAI’s coding-agent architecture explains one important trade-off: when each new turn includes the complete history of earlier messages and tool calls, the prompt grows as the interaction continues, with performance implications. It also describes a design in which requests remain stateless and send the history with each API call. That report is evidence about the described Codex approach, not a universal statement about every API or agent system.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;Separate this immediate conversation history from your long-term memory. Conversation history can explain the current sequence of actions; persistent memory is intended to carry selected knowledge across sessions. A design that grows the full prompt without limit can become less efficient. A design that omits relevant evidence can leave the agent without the context it needs. Determine what should remain in the active interaction and what should instead be summarized or stored as structured memory, then evaluate those decisions on real tasks.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;Be realistic about coding-agent performance. The verified reporting notes that these tools can be fast on simple tasks but brittle beyond their training data, and that production work requires human oversight. A promising initial scaffold does not eliminate the debugging needed to complete details or resolve limitations. Plan for a developer to review proposed changes and confirm important outcomes.&lt;/p&gt;


&lt;h2&gt;Step 7: Evaluate Memory and Tool Behavior&lt;/h2&gt;
&lt;br&gt;
  &lt;p&gt;Do not evaluate the system only by asking whether it returns a fluent answer. Test whether it loads relevant prior knowledge, retrieves the right facts for a new task, avoids irrelevant memory, and updates stored information in a way that remains useful later. The verified context describes evaluations and tracing among Mastra’s framework capabilities and highlights memory pipelines that extract structured facts, consolidate episodic memory, and support write-back. It does not provide a test suite for this specific coding-agent design.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;Create a set of representative tasks from the kinds of work your agent is expected to support. Include cases where a relevant memory should change the answer, cases where stored context should not affect an unrelated request, and cases where the right response is to proceed without a remembered fact. Record which facts were retrieved, what tools were requested, and whether the final answer was supported by the returned results.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;Review memory updates as carefully as retrieval. Check whether extracted facts are supported by the interaction, whether distinct episodes have been consolidated sensibly, and whether an update conflicts with information already stored. A write-back loop can be autonomous, but that does not establish that every write is correct. Establish a process for identifying and repairing bad memories before relying on the system for consequential work.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;When tracing is available in the framework or application you select, use it to understand how the workflow proceeded. Confirm the actual observability features and data captured in your chosen setup; the verified context names tracing and evaluations as Mastra capabilities but does not specify an implementation’s precise trace format, retention, or privacy behavior.&lt;/p&gt;


&lt;h2&gt;Step 8: Introduce the Agent Carefully&lt;/h2&gt;
&lt;br&gt;
  &lt;p&gt;Start with a narrow, well-defined use case. For example, evaluate whether memory helps an agent answer recurring questions about project conventions or retrieve the relevant tool for a task. Expand its scope only after you have evidence that retrieval, write-back, and tool interactions behave as intended.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;Keep human review in the workflow for code that matters. The verified reporting emphasizes that coding agents can require tedious debugging and remain brittle beyond their training data. Review the changes or recommendations, run the checks appropriate to your project, and make the decision to accept the work yourself. Do not claim that an agent has validated a change unless the relevant validation was actually performed and its result is available.&lt;/p&gt;
&lt;br&gt;
  &lt;p&gt;Before using persistent memory with sensitive or proprietary repositories, decide what may be retained and who can access it. The supplied sources establish architectural ideas about persistent memory, but they do not establish the privacy, retention, security, or data-handling properties of any particular storage provider or model integration. Verify those properties independently for the tools you select.&lt;/p&gt;


&lt;h2&gt;Key Takeaways&lt;/h2&gt;
&lt;br&gt;
  &lt;ul&gt;

    &lt;li&gt;Treat long-term memory as structured infrastructure outside the model, not as an unbounded transcript.&lt;/li&gt;

    &lt;li&gt;Design a lifecycle for loading prior context, retrieving relevant facts and tools, extracting information, consolidating it, and writing updates back.&lt;/li&gt;

    &lt;li&gt;Use retrieval to make the current task’s context and tools relevant rather than exposing an ever-growing collection by default.&lt;/li&gt;

    &lt;li&gt;Understand the tool-call cycle and account for the cost and performance implications of repeatedly sending conversation history where that design applies.&lt;/li&gt;

    &lt;li&gt;Verify runtime, storage, provider, security, and framework APIs in their current documentation; the available evidence does not validate a specific Bun, SQLite, or OpenAI implementation.&lt;/li&gt;

    &lt;li&gt;Evaluate the complete system and keep human oversight for coding work, particularly before production use.&lt;/li&gt;

  &lt;/ul&gt;


&lt;h2&gt;Sources and Scope&lt;/h2&gt;
&lt;br&gt;
  &lt;p&gt;This tutorial draws on the verified description of DeepLearning.AI’s Agent Memory course for persistent memory, retrieval, structured fact extraction, consolidation, and write-back; reporting on the coding-agent loop and conversation-history growth; and the verified Mastra framework listing for its TypeScript agent capabilities and starter command. These sources support the architecture and cautions described here. They do not verify the original draft’s detailed Bun/SQLite/OpenAI code, exact package compatibility, or security claims.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>ai</category>
      <category>tutorial</category>
      <category>discuss</category>
    </item>
    <item>
      <title>OpenAI-Compatible Proxy Security in FastAPI</title>
      <dc:creator>Gate of AI</dc:creator>
      <pubDate>Sat, 31 Oct 2026 14:55:50 +0000</pubDate>
      <link>https://dev.to/gateofai/openai-compatible-proxy-security-in-fastapi-1ahn</link>
      <guid>https://dev.to/gateofai/openai-compatible-proxy-security-in-fastapi-1ahn</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;🚀 Technical Briefing:&lt;/strong&gt; This tutorial is part of our deep-dive series on Agentic Workflows at &lt;a href="https://gateofai.com" rel="noopener noreferrer"&gt;Gate of AI&lt;/a&gt;. For the full technical breakdown, interactive code sandbox, and the native Arabic translation, visit the &lt;a href="https://gateofai.com/tutorial/openai-compatible-proxy-security-fastapi/" rel="noopener noreferrer"&gt;original article here&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Tutorial · LLM API security&lt;/strong&gt;&lt;/p&gt;

&lt;h1&gt;Assessing Security Risks in an OpenAI-Compatible FastAPI Proxy&lt;/h1&gt;

&lt;p&gt;This source-bounded walkthrough explains what an OpenAI-compatible LLM router can observe or alter, how to reason about the intermediary threat described in the verified research, and how to assess the defense categories reported by that work. It does not provide a deployable security product or claim that the described defenses eliminate every supply-chain risk.&lt;/p&gt;

&lt;h2&gt;Scope and evidence&lt;/h2&gt;

&lt;p&gt;The verified research describes an implementation called Mine: an OpenAI-compatible FastAPI proxy that forwards requests to an upstream provider and conditionally applies attack conditions identified as AC-1, AC-1.a, AC-1.b, and AC-2. The same source describes companion client-side modules for three evaluated defense categories: a tool policy gate, response-side anomaly screening, and an append-only transparency log.&lt;/p&gt;

&lt;p&gt;This is a report about an evaluated research implementation, not evidence that every FastAPI proxy has these features or that Mine is a generally available product. The supplied context does not include source code, installation instructions, request examples, benchmark results, or a complete implementation guide. Accordingly, this article does not invent API endpoints, code, configuration values, or guarantees that are absent from the evidence.&lt;/p&gt;

&lt;p&gt;The distinction matters for engineering teams: a description of a research prototype can inform a threat model, but it is not sufficient documentation for copying a production architecture. Before implementing controls, consult the original paper and any linked artifacts, verify their current availability and contents, and review the design against your own deployment environment.&lt;/p&gt;

&lt;h2&gt;Step 1: Understand the intermediary threat model&lt;/h2&gt;

&lt;p&gt;The paper considers an attacker that operates a malicious LLM API router or has compromised a legitimate router. The described compromise paths include supply-chain compromise, insider access, or server-side exploitation. The key architectural fact in the source is that the client explicitly configures the router as its API endpoint. The router terminates the client-side TLS connection and originates a separate TLS connection to the upstream provider.&lt;/p&gt;

&lt;p&gt;That arrangement places the router in an application-layer intermediary position by design. TLS on each network connection does not, by itself, prevent the configured router from handling the application request and response. According to the source, the intermediary can read, retain, rewrite, or fabricate request and response bodies, headers, and request metadata.&lt;/p&gt;

&lt;p&gt;The paper names sensitive material that may cross this boundary: tool definitions, prompts, tool outputs, API keys, and returned tool-call payloads across OpenAI-, Anthropic-, and Gemini-style interfaces. These are not interchangeable categories. A prompt may contain instructions or business data; a tool definition describes capabilities exposed to the model; a tool result can contain information returned by an application; and a tool-call payload may request an action in a connected system. The source’s threat model says the router may be able to handle these materials. It does not establish that every deployment sends every category, or that every router stores or modifies them.&lt;/p&gt;

&lt;p&gt;For a security review, start by documenting the configured endpoint and the party operating it. Identify which systems can change that endpoint, deploy or update the router, access its runtime, or inspect its traffic at the application layer. The research context supports asking these questions; it does not prescribe a vendor-selection checklist or a specific network topology.&lt;/p&gt;

&lt;h2&gt;Step 2: Map the data that passes through the router&lt;/h2&gt;

&lt;p&gt;Build an inventory from the actual client configuration and request flows. Record whether requests include prompts, tool descriptions, tool results, credentials, or other metadata, and whether responses include natural-language content or tool-call data. Keep the inventory factual: do not assume a field is absent merely because it is not visible in a user interface.&lt;/p&gt;

&lt;p&gt;The paper notes that a router may keep cross-request state. That possibility changes the review: security analysis should not be limited to a single request in isolation. Consider whether an intermediary can relate activity across requests and what impact that could have in the particular application. The supplied source does not specify a retention period, storage mechanism, or exact cross-request attack sequence, so do not treat any particular retention behavior as a confirmed fact.&lt;/p&gt;

&lt;p&gt;Pay special attention to credentials and tool payloads. The source explicitly includes API keys and returned tool-call payloads in the material an intermediary may handle. This is a reason to include those elements in the threat assessment, not proof that a particular key was exposed or that a particular tool action was executed. Determine what your client actually sends and what trust your application places in responses.&lt;/p&gt;

&lt;p&gt;Document data flow in a simple sequence: client to configured router, router to upstream provider, upstream response to router, and router response to client. For each leg, note which component originates the connection and which party controls it. This description follows the paper’s stated intermediary arrangement without assuming any additional proxy behavior.&lt;/p&gt;

&lt;h2&gt;Step 3: Separate request integrity, response integrity, and tool authority&lt;/h2&gt;

&lt;p&gt;A useful review distinguishes three questions. First, can a request be observed or changed before it reaches the upstream provider? Second, can a response be observed or changed before it reaches the client? Third, what does the client or surrounding application do with any tool-call payload it receives? The paper’s threat model makes the first two questions relevant because it says the intermediary can read, retain, rewrite, or fabricate request and response material. The third is relevant because the source explicitly includes tool definitions, tool outputs, and tool-call payloads.&lt;/p&gt;

&lt;p&gt;Do not collapse these questions into a single claim that a model response is “safe” or “signed.” The supplied context describes a signed-response envelope design and a client-side tool policy gate, but it does not establish that a signature alone makes every response trustworthy, that a policy gate blocks every malicious action, or that a particular client has implemented either measure correctly.&lt;/p&gt;

&lt;p&gt;Where an application uses model-directed tools, review the boundary between receiving a proposed tool call and permitting an application to perform an operation. The verified source identifies a tool policy gate as a companion defense module. It does not provide enough implementation detail here to specify its policy language, enforcement point, or exact behavior. Treat the category as a design area to inspect in the paper, not as a ready-made control that can be enabled by copying a snippet from this article.&lt;/p&gt;

&lt;h2&gt;Step 4: Review the defense categories reported in the research&lt;/h2&gt;

&lt;h3&gt;Tool policy gate&lt;/h3&gt;

&lt;p&gt;The paper reports a client-side tool policy gate among the deployable defenses it evaluates. At a high level, this category concerns applying a policy to tool use. The source excerpt does not specify policy rules, supported tool formats, or the gate’s precise decision process. A team assessing the work should read the paper’s defense section and artifacts before claiming that a proposed implementation matches the evaluated module.&lt;/p&gt;

&lt;h3&gt;Response-side anomaly screening&lt;/h3&gt;

&lt;p&gt;The second reported category is response-side anomaly screening. Its placement, as named in the source, is on the response side. The available context does not provide its detection method, thresholds, measured accuracy, or false-positive behavior. Do not describe it as a universal detector or state that it catches every fabricated or modified response.&lt;/p&gt;

&lt;h3&gt;Append-only transparency log&lt;/h3&gt;

&lt;p&gt;The third reported category is an append-only transparency log. The source identifies this as a companion client-side defense module. An append-only log is a particular design description, but the supplied excerpt does not specify its storage format, integrity mechanism, retention policy, or operational guarantees. A team should verify those details in the original work before using the label to make security or compliance claims.&lt;/p&gt;

&lt;p&gt;These are separate defense categories in the paper, not evidence that one control replaces the others. The context says the modules were implemented for the defenses evaluated in the research. It does not establish universal effectiveness, production readiness, or protection against every intermediary compromise.&lt;/p&gt;

&lt;h2&gt;Step 5: Interpret the signed-response envelope carefully&lt;/h2&gt;

&lt;p&gt;The verified source lists fields for a signed-response envelope. The fields include an envelope version (&lt;code&gt;v&lt;/code&gt;) for compatibility and rollout; provider identity; a signing-key identifier for verification and rotation; the model identifier associated with the signed response; a client-supplied request nonce bound to the corresponding request; provider issue and expiry timestamps; assistant content, if any; tool calls with names and native-JSON arguments; a finish reason; and a signature algorithm identifier.&lt;/p&gt;

&lt;p&gt;These fields show which pieces of information the described envelope is designed to carry. The excerpt does not provide a complete wire format, a signing-key distribution procedure, a canonicalization algorithm, or code that verifies signatures. Therefore, this article cannot responsibly provide a working verifier or claim that the envelope prevents a malicious router from altering all relevant traffic. Consult the paper for the protocol details and validate any implementation against the exact specification.&lt;/p&gt;

&lt;p&gt;When reviewing such a design, ask whether the verifier checks the request binding and validity window, how it identifies trusted signing keys, and what it does when verification fails. These are review questions derived from the listed fields; they are not claims that the source specifies a particular answer. Do not treat a field name as proof that a security property has been achieved in a deployed system.&lt;/p&gt;

&lt;h2&gt;Step 6: Build a source-grounded review record&lt;/h2&gt;

&lt;p&gt;For an internal assessment, record the version of the paper and the exact claims you have verified. Separate statements made by the source from your own implementation decisions. For example, “the paper describes a FastAPI proxy that forwards OpenAI-compatible requests” is a source-level statement. “Our service prevents all prompt tampering” would be an independent security claim and is not established by the supplied context.&lt;/p&gt;

&lt;p&gt;Track at least the following review topics in prose or a structured internal record: configured router ownership; request and response data categories; whether tool definitions and tool results cross the boundary; whether credentials or tool-call payloads are in scope; whether cross-request state is possible; and which of the three described defense categories your implementation actually uses. Record unknowns explicitly as open review questions rather than silently filling gaps with assumptions.&lt;/p&gt;

&lt;p&gt;Also distinguish research evidence from deployment evidence. The first source reports an implementation and evaluated defenses. The second supplied source discusses a separate framework and artifacts, including a caution that its evidence should not be read as showing that it governed the upstream FastAPI maintainer workflow. It does not verify the release-risk-gate design in the original draft, and it should not be used to claim that a framework controls upstream FastAPI development or resolves general multi-agent runtime races.&lt;/p&gt;

&lt;h2&gt;Common mistakes to avoid&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Assuming TLS eliminates the intermediary risk.&lt;/strong&gt; In the described setup, the client configures the router, which terminates one TLS connection and originates another. The paper’s concern is the router’s application-layer position.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Assuming the router only forwards bytes.&lt;/strong&gt; The source says the intermediary may read, retain, rewrite, or fabricate requests, responses, headers, and metadata.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Assuming a tool call is harmless text.&lt;/strong&gt; Tool definitions, tool outputs, and returned tool-call payloads are explicitly named in the threat model. Review how your application handles them.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Turning a research defense into a guarantee.&lt;/strong&gt; The paper reports a tool policy gate, response-side anomaly screening, and an append-only transparency log. The supplied context does not prove complete protection or production readiness.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Importing unrelated findings into the conclusion.&lt;/strong&gt; The separate framework source does not substantiate the original release-risk tutorial or establish governance over upstream FastAPI development.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Copying unsupported implementation details.&lt;/strong&gt; The available context does not include enough information to reproduce the proxy, defense modules, or signed-envelope verifier. Use the paper and its artifacts for implementation-specific claims.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;The verified research presents a concrete security concern for OpenAI-compatible routing: a client-configured intermediary can occupy an application-layer position between a client and upstream provider, and the paper’s threat model includes the ability to observe or alter sensitive request and response material. It also reports three client-side defense categories and describes fields for a signed-response envelope.&lt;/p&gt;

&lt;p&gt;The practical takeaway is not that a particular proxy or defense is automatically secure. It is to identify the router as a trust boundary, understand which data and tool-call materials cross it, and verify the design and limitations of any defenses against the source itself. The original release-risk-gate implementation is omitted because the supplied verified context does not substantiate its code, model settings, policies, or operational claims.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Editorial note: This article is limited to the supplied verified context. It does not claim that the described research artifacts are a production service or that they provide comprehensive protection.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>ai</category>
      <category>tutorial</category>
      <category>discuss</category>
    </item>
  </channel>
</rss>
