<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alberto Ugolini on Medium]]></title>
        <description><![CDATA[Stories by Alberto Ugolini on Medium]]></description>
        <link>https://medium.com/@glaros441?source=rss-67d49ed1f4a1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*B-ybD1H6yVli3JNc</url>
            <title>Stories by Alberto Ugolini on Medium</title>
            <link>https://medium.com/@glaros441?source=rss-67d49ed1f4a1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 14:11:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@glaros441/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Adding AI to an Existing ASP.NET Core MVC Application]]></title>
            <link>https://medium.com/@glaros441/adding-ai-to-an-existing-asp-net-core-mvc-application-2889f103dc9f?source=rss-67d49ed1f4a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2889f103dc9f</guid>
            <category><![CDATA[aspnet-mvc]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Alberto Ugolini]]></dc:creator>
            <pubDate>Sun, 22 Nov 2026 10:59:25 GMT</pubDate>
            <atom:updated>2026-11-22T10:59:25.150Z</atom:updated>
            <content:encoded><![CDATA[<h3>A practical architecture with a Python AI service, secure ticket access, RAG, and operational dashboards</h3><p>AI features do not require replacing a mature web application or moving its data into a new platform. In this project, an existing ASP.NET Core MVC ticketing application remains responsible for users, roles, permissions, and ticket records. A separate Python/FastAPI service adds knowledge search, AI assistance, and an agent copilot.</p><p>The separation is deliberate: the MVC application stays the system of record, while the AI service receives only the data it needs for a specific, authorized request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n5HUXiRlcb2JirbUfW3PwQ.png" /></figure><h3>Start with the application you already have</h3><p>The MVC application already handles the everyday ticket workflow: requesters create and track their own tickets, while support staff can manage the wider queue. Its controllers and ASP.NET Identity roles continue to enforce those rules.</p><p>The AI service is an addition, not a second ticket application:</p><ul><li><strong>ASP.NET Core MVC</strong> owns authentication, authorization, ticket business rules, and the SQLite ticket database.</li><li><strong>FastAPI</strong> handles AI-facing HTTP endpoints, retrieval orchestration, and model integration.</li><li><strong>Qdrant and SQLite FTS5</strong> search the knowledge base locally using vector and lexical retrieval.</li><li><strong>OpenAI</strong> is an optional generation provider, controlled by separate configuration switches.</li><li><strong>Prometheus and Grafana</strong> provide operational metrics and dashboards.</li></ul><p>This pattern also applies to an existing CRM, service portal, or internal operations tool: keep ownership of business data in the application that already understands its permissions, and add AI through a narrow service boundary.</p><h3>A short-lived token connects the two applications</h3><p>The browser is signed in to MVC with the application’s normal authentication cookie. When the AI UI needs to call FastAPI, it requests a short-lived access token from AiSessionController.</p><p>The controller builds the token from the authenticated user and their MVC roles:</p><pre>var claims = new List&lt;Claim&gt;<br>{<br>    new(&quot;sub&quot;, userId),<br>    new(&quot;name&quot;, User.Identity?.Name ?? string.Empty)<br>};<br>claims.AddRange(roles.Select(role =&gt; new Claim(&quot;role&quot;, role)));</pre><pre>var token = new JwtSecurityToken(<br>    issuer: &quot;service-desk-main-app&quot;,<br>    audience: &quot;service-desk-agentic-app&quot;,<br>    claims: claims,<br>    notBefore: DateTime.UtcNow,<br>    expires: DateTime.UtcNow.AddMinutes(5),<br>    signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));</pre><p>In <a href="https://medium.com/main-app/Controllers/AiSessionController.cs">main-app/Controllers/AiSessionController.cs</a>, the token endpoint is authenticated and protected by MVC&#39;s anti-forgery validation. FastAPI checks the signature, issuer, audience, and expiry in <a href="https://medium.com/agentic-app/auth.py">agentic-app/auth.py</a>. A five-minute lifetime limits how long a copied token remains useful.</p><p>This is not a replacement for authorization. It is a signed way for the AI service to learn which MVC user and roles made the request.</p><h3>Keep ticket access behind MVC</h3><p>FastAPI does not connect directly to the MVC database. When it needs ticket context, it calls MVC’s internal API with the user’s token. The internal endpoint validates that token and applies ticket visibility rules before returning data.</p><p>For example, the search action restricts non-staff users to tickets they created:</p><pre>if (!User.IsInRole(&quot;Agent&quot;) &amp;&amp; !User.IsInRole(&quot;Admin&quot;))<br>{<br>    var requesterId = User.FindFirst(&quot;sub&quot;)?.Value;<br>    tickets = tickets.Where(ticket =&gt; ticket.CreatedById == requesterId);<br>}</pre><p>That code lives in <a href="https://medium.com/main-app/Controllers/InternalTicketsController.cs">main-app/Controllers/InternalTicketsController.cs</a>. The AI service calls it through <a href="https://medium.com/agentic-app/ticket_tools.py">agentic-app/ticket_tools.py</a>, forwarding the signed bearer token rather than creating a second, more privileged identity.</p><p>The result is a useful boundary: MVC remains the place where ticket access is decided, and the AI service cannot bypass the application’s existing data rules.</p><h3>Add AI features as explicit workflows</h3><p>The project offers two distinct experiences rather than a single opaque chatbot:</p><ol><li><strong>Agent Copilot</strong> takes a ticket number, retrieves the ticket the signed-in agent is authorized to see, and returns a summary, suggested category and priority, missing information, and a draft reply. It does not update the ticket or send the reply.</li><li><strong>AI Help</strong> takes a written question and a selected source: the knowledge base, the user’s visible tickets, or web search.</li></ol><p>The difference matters. A copilot can be designed as a reviewable suggestion in an existing workflow, while a conversational help feature can be treated as a separate user-initiated request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*umO4ZOI0jr_YkkMR-Yh5hQ.png" /></figure><p>For ticket analysis, <a href="https://medium.com/agentic-app/main.py">agentic-app/main.py</a> checks that the user is an Agent or Admin and that ticket sharing is explicitly enabled. The prompt contains the ticket title, description, category, priority, and status; the ticket number is used to retrieve the record, not included in the model input. The model&#39;s structured response is displayed for a person to review.</p><p>The AI should assist a decision-maker, not silently take a business action. In this implementation, accepting a suggestion and changing a ticket remain explicit human actions in MVC.</p><h3>Use retrieval for knowledge-grounded answers</h3><p>A language model by itself does not know an organization’s current procedures. Retrieval-augmented generation (RAG) provides relevant source material to the answer workflow.</p><p>This project uses a hybrid retrieval pipeline:</p><ol><li>Documents are parsed and split into overlapping text chunks.</li><li>FastEmbed creates local multilingual embeddings and Qdrant retrieves semantic candidates.</li><li>SQLite FTS5 retrieves lexical candidates for exact terms and acronyms.</li><li>Reciprocal Rank Fusion combines the two candidate lists.</li><li>A local multilingual INT8 cross-encoder reranks the leading candidates.</li><li>Results include citations, so the user can inspect the document behind an answer.</li></ol><p>The core search logic is in <a href="https://medium.com/agentic-app/rag.py">agentic-app/rag.py</a>. The ticket records are not added to this knowledge index: ticket context is retrieved live through MVC, with the caller&#39;s authorization applied.</p><p>Search and generation are also separate concerns. Retrieval can run locally; sending a question and retrieved excerpts to an external generation provider is a separate data-flow decision.</p><h3>Make data sharing an explicit choice</h3><p>There is no universal answer to whether ticket or document text may be sent to a model provider. The application makes those choices visible as independent settings:</p><ul><li>OPENAI_TICKET_CONTEXT_ENABLED controls sharing authorized ticket fields for ticket help and Copilot.</li><li>OPENAI_KNOWLEDGE_CONTEXT_ENABLED controls sharing knowledge excerpts for generated knowledge answers, and optionally Copilot.</li><li>WEB_SEARCH_ENABLED controls the web-search workflow, which sends the user&#39;s question to the configured provider.</li></ul><p>All three are disabled by default. When an operation needs a disabled data flow, FastAPI rejects it instead of silently sending the data. OpenAI requests set store=False; that is a request parameter, not a guarantee of zero provider retention. A production deployment still needs an approved provider, retention policy, data residency review, and appropriate user notices.</p><p>This is an important integration lesson: define the data flows before adding prompts. Decide what data the feature needs, who may request it, what leaves the system, and what the UI tells the user.</p><h3>Docker keeps the local stack reproducible</h3><p>The repository’s <a href="https://medium.com/compose.yaml">compose.yaml</a> runs the MVC app, FastAPI, Qdrant, Prometheus, and Grafana as separate services. Persistent Docker volumes hold the ticket database, knowledge data and models, vector index, and monitoring state.</p><p>For local development, create the .env file from .env.example, set unique secrets and passwords, and start the stack:</p><pre>Copy-Item .env.example .env<br>docker compose up --build -d<br>docker compose ps</pre><p>The web applications use the local HTTPS development certificate. The FastAPI exporter is available to Prometheus only on the Docker metrics network; the metrics listener is not published to the host. This keeps the telemetry path separate from user-facing APIs.</p><h3>View Grafana remotely with ngrok</h3><p>The Grafana dashboard reads Prometheus through the internal Docker network, so remote dashboard access needs a tunnel to Grafana — not a public Prometheus endpoint. This project includes an optional Compose profile for that purpose.</p><p>After creating an ngrok account, put the authtoken and your ngrok public hostname in the local .env file:</p><pre>NGROK_AUTHTOKEN=&lt;your-ngrok-authtoken&gt;<br>NGROK_GRAFANA_DOMAIN=&lt;your-reserved-ngrok-hostname&gt;<br>GRAFANA_ROOT_URL=https://&lt;your-reserved-ngrok-hostname&gt;/</pre><p>Then start only the tunnel service:</p><pre>docker compose --profile ngrok up -d ngrok-grafana<br>docker compose logs -f ngrok-grafana</pre><p>Open the configured HTTPS hostname and sign in to Grafana with username admin and the local GRAFANA_ADMIN_PASSWORD. The tunnel is publicly reachable, so share its address only with authorized people and use a strong password. Prometheus remains unexposed through ngrok; Grafana queries it internally. The normal docker compose up does not start the tunnel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zsd-ju9d7W9tRwanmVtRBg.png" /></figure><h3>Add observability without logging private content</h3><p>The FastAPI service publishes aggregate request counts and durations, RAG outcomes and latency, AI operation counts, and runtime measurements. Prometheus scrapes those metrics, and Grafana presents the provisioned <strong>Service Desk AI Operations</strong> dashboard.</p><p>The instrumentation uses bounded labels such as route templates, status codes, and operation outcomes. It does not put ticket text, prompts, query strings, or ticket/user IDs into metric labels. This makes the dashboard useful for operational questions — such as whether requests are failing or retrieval latency is rising — without turning telemetry into a copy of user content.</p><p>Metrics are not a substitute for application logs, traces, or a full production observability design. They are a useful baseline that can be expanded as service-level objectives and operational needs become clearer.</p><h3>What this pattern makes possible</h3><p>An existing ASP.NET MVC system can adopt AI incrementally:</p><ul><li>Keep identity, domain rules, and data ownership where they are.</li><li>Add a separately deployable AI service behind a narrow, authenticated API.</li><li>Retrieve only data the current user is allowed to see.</li><li>Ground answers in indexed, cited knowledge rather than relying on model memory.</li><li>Keep suggestions reviewable and avoid autonomous writes.</li><li>Make external data sharing opt-in and observable.</li><li>Deploy and operate the stack with familiar container and monitoring tools.</li></ul><p>The example is intentionally a starting point, not a claim that one architecture fits every organization. Before using real customer data, add the controls required by the application’s threat model and compliance obligations — such as document-level knowledge permissions, secrets management, rate limits, audit policy, retention controls, and deployment-specific network security.</p><p>If you are evaluating how to add AI to an existing .NET application, the central design question is not “How do I add a chatbot?” It is “How can I add a useful AI workflow without weakening the application’s existing boundaries?”</p><h3>PS</h3><p>This documentation was heavely built on AI, as the code. I tried to do my best for the quality of this work but I am sure there will be some error. Sorry for that.</p><p>The repository will be soon available on https://github.com/alt3517/agentic-app.git</p><p>Definitely this application can be improved, particularly in the RAG stack. This was just about an idea: publishing something online and nothing more. I hope this is of some interest for the reader. For any improvement or clarification, I would be happy to answer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2889f103dc9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>