<?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 Matias Paulo on Medium]]></title>
        <description><![CDATA[Stories by Matias Paulo on Medium]]></description>
        <link>https://medium.com/@matias.paulo84?source=rss-1701886feae1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kbm01OS2Gntq5LFFQGK9qg.jpeg</url>
            <title>Stories by Matias Paulo on Medium</title>
            <link>https://medium.com/@matias.paulo84?source=rss-1701886feae1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 12:29:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@matias.paulo84/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[A real example: troubleshooting agent]]></title>
            <link>https://medium.com/@matias.paulo84/a-real-example-troubleshooting-agent-797357c64f55?source=rss-1701886feae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/797357c64f55</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Matias Paulo]]></dc:creator>
            <pubDate>Thu, 14 Aug 2025 13:59:11 GMT</pubDate>
            <atom:updated>2025-08-14T13:59:11.846Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yx_RGcElsy_Q540jrP4S5Q.png" /></figure><p>In this final chapter, we’re putting everything into action with a real-world scenario.</p><p>We’ll build an <strong>AI troubleshooting agent</strong> that can help users diagnose problems across different types of equipment. The agent will suggest actionable steps to solve the issue and, if those steps don’t work, it will <strong>simulate creating a work order</strong> to escalate the case.</p><p>But that’s not all — our agent will also have a <strong>growing knowledge base</strong>. We’ll make it possible to <strong>upload PDF documents</strong> directly into a local database, so the agent can search them on demand. This means smarter, more accurate answers every time.</p><p>We’ll combine everything we’ve learned in the series, along with tools, all in C# with LangChain.</p><p>In our case, we mentioned that we want the agent to be able to create a work order, but to interact with the “outside world,” we can make use of <strong>tools</strong>. A tool is an external capability or function that the agent can call to perform a specific action beyond just generating text.</p><p>While the language model (LLM) can reason, plan, and converse, tools give it the power to act — for example, retrieving information from a database, creating a work order, sending an email, or calling an API.</p><p>Enough talk, let’s code. We’ll start coding the ingestion endpoint:</p><pre>[HttpPost(&quot;ingest&quot;)]<br>public async Task&lt;IActionResult&gt; IngestAsync([FromBody] string documentUrl)<br>{<br>    using var http = new HttpClient();<br>    var pdfBytes = await http.GetByteArrayAsync(documentUrl);<br>    using var pdfStream = new MemoryStream(pdfBytes);<br>    await _vectorDatabase.AddDocumentsFromAsync&lt;PdfPigPdfLoader&gt;(<br>        _embeddingModel, // Used to convert text to embeddings<br>        dimensions: 1536, // Should be 1536 for TextEmbeddingV3SmallModel<br>        dataSource: new DataSource<br>        {<br>            Type = DataSourceType.Stream,<br>            Stream = pdfStream,<br>        },<br>        collectionName: CollectionName,<br>        textSplitter: null,<br>        behavior: AddDocumentsToDatabaseBehavior.OverwriteExistingCollection);<br>    return Ok();<br>}</pre><p>This part is pretty straightforward. As we did in the previous post, we just take a document’s URL, vectorize its contents, and store the resulting embeddings in a <strong>SqLiteVector</strong> database.</p><p>Now, I want to show you my “tool” for creating work orders. It is very simple since it is a simulation, but it will help you figure out how it works.</p><pre>public sealed class CreateWorkOrderTool : IAiTool<br>{<br>    public string Name =&gt; &quot;create_work_order&quot;;<br>    <br>    public string Description =&gt; &quot;Create a maintenance work order. Args: equipmentId (string), summary (string), priority (Low|Medium|High).&quot;;<br>    <br>    public async Task&lt;object&gt; ExecuteAsync(Dictionary&lt;string, object&gt; args, CancellationToken cancellationToken = default)<br>    {<br>        // Simulate work order creation<br>        await Task.Delay(100, cancellationToken);<br>        <br>        return new<br>        {<br>            WorkOrderId = Guid.NewGuid().ToString()<br>        };<br>    }<br>}</pre><p>The function has defined a “<em>Name</em>” and a “<em>Description</em>” that will help the AI to understand what this “tool” does. The function receives some parameters that we have defined in the prompt.</p><p>Now, let’s see how we can “chat” with the agent:</p><pre>[HttpPost(&quot;/{conversationId}/ask&quot;)]<br>public async Task&lt;ActionResult&lt;string&gt;&gt; AskAsync([FromRoute] Guid conversationId, [FromBody] string question,<br>    CancellationToken cancellationToken)<br>{<br>    _memory.AddUser(conversationId, question);<br>    var context = await RetrieveRelevantContextAsync(question, cancellationToken);<br>    var toolCatalog = BuildToolCatalog();<br>    var systemPrompt = Prompts.SystemPrompt.Replace(&quot;{tools_catalog}&quot;, toolCatalog);<br>    var finalPrompt = BuildRagPrompt(conversationId, context, question);<br>    bool toolExecuted = false;<br>    for (var step = 0; step &lt; 4; step++)<br>    {<br>        var agentReply = await GenerateAgentReplyAsync(systemPrompt, finalPrompt, cancellationToken);<br>        var normalizedReply = NormalizeAgentReply(agentReply);<br>        if (normalizedReply.StartsWith(&quot;CALL_TOOL:&quot;, StringComparison.OrdinalIgnoreCase))<br>        {<br>            if (toolExecuted)<br>            {<br>                normalizedReply = &quot;A tool was already executed. Provide the final answer without calling tools.&quot;;<br>            }<br>            else<br>            {<br>                if (!TryParseToolCall(normalizedReply, out var toolName, out var argsDict, out var parseError))<br>                {<br>                    var errorMsg = $&quot;Bad tool call format: {parseError}&quot;;<br>                    _memory.AddAssistant(conversationId, errorMsg);<br>                    return errorMsg;<br>                }<br>                var tool = _tools.FirstOrDefault(t =&gt; t.Name.Equals(toolName, StringComparison.OrdinalIgnoreCase));<br>                if (tool is null)<br>                    return $&quot;Unknown tool: {toolName}&quot;;<br>                var toolResult = await tool.ExecuteAsync(argsDict, cancellationToken);<br>                toolExecuted = true;<br>                finalPrompt = BuildFinalAnswerPrompt(conversationId, context, toolName, toolResult, question);<br>                continue;<br>            }<br>        }<br>        _memory.AddAssistant(conversationId, normalizedReply);<br>        return normalizedReply;<br>    }<br>    const string failMessage = &quot;I couldn&#39;t complete the request.&quot;;<br>    _memory.AddAssistant(conversationId, failMessage);<br>    return failMessage;<br>}</pre><h4>Step-by-Step Breakdown</h4><ol><li>Add User Message to Memory: The user’s question is stored in the conversation history for context.</li><li>Retrieve Relevant Context: Uses a vector database to find documents similar to the question, providing background information for the AI.</li><li>Build Prompts: Prepares prompts for the AI model, including available tools and conversation history.</li><li>Agent Reply Loop: The method allows up to 4 steps for the AI agent to respond, supporting tool calls and follow-up answers.</li><li>Tool Call Handling:<br>• If the AI’s reply starts with “CALL_TOOL:”, it tries to parse the tool call.<br>• If a tool is called and hasn’t been executed yet:<br>• Parses the tool name and arguments.<br>• Finds the tool in _tools and executes it.<br>• Updates the prompt to include the tool result, asking the AI to provide a final answer.<br>• If a tool was already executed, instruct the AI to provide a final answer without calling tools again.</li><li>Normal Reply Handling: If the reply is not a tool call, it is added to the conversation history and returned as the answer.</li><li>Failure Case: If no valid answer is produced after 4 steps, it returns a failure message.</li></ol><h4>Wrapping up</h4><p>With this last step, we’ve taken our <strong>LangChain</strong> <em>+</em> <strong>C#</strong> journey from basic prompt templates to a fully functional <strong>AI troubleshooting agent</strong> capable of retrieving context from a local knowledge base, reasoning through problems, and even interacting with external systems through <strong>tools</strong>.</p><p>What we’ve built here is just the beginning. The same architecture can be extended to:</p><ul><li>Integrate with <strong>real APIs</strong> for ticketing, monitoring, or IoT devices.</li><li>Add <strong>advanced retrieval techniques</strong> like hybrid search or semantic re-ranking.</li><li>Incorporate <strong>memory summarization</strong> for longer-running conversations.</li><li>Combine <strong>multiple tools</strong> for multi-step workflows.</li></ul><p>The evolution of .NET tooling and the maturity of frameworks like LangChain mean that AI agents are no longer limited to Python or JavaScript ecosystems. With strong type safety, dependency injection, and the performance of .NET, developers can now build <strong>production-ready AI systems</strong> directly in C#.</p><p>The next generation of AI applications won’t just answer questions, they’ll <strong>act</strong>, <strong>adapt</strong>, and <strong>learn</strong> from their environment. And with the foundation you now have, you’re ready to start building them.</p><p>Happy coding!</p><h4>Posts in this series:</h4><ol><li>Templated prompts</li><li><a href="https://medium.com/@matias.paulo84/chaining-prompts-in-c-sequential-reasoning-with-langchain-bf43e41a1438">Chaining Prompts in C#: Sequential Reasoning with LangChain</a></li><li><a href="https://medium.com/@matias.paulo84/memory-a-key-feature-for-conversational-agents-b96e2ba8d6fd">Memory: a key feature for conversational agents</a></li><li><a href="https://medium.com/@matias.paulo84/local-rag-in-c-connect-your-ai-to-external-knowledge-9cc16ddea07e">Local RAG in C#: Connect Your AI to External Knowledge</a></li><li>Real world example: A troubleshooting agent</li></ol><p>You can check the source code <a href="https://github.com/matipaulo/LangchainDemo">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=797357c64f55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Templated Prompts]]></title>
            <link>https://medium.com/@matias.paulo84/templated-prompts-256f9d2777d0?source=rss-1701886feae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/256f9d2777d0</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Matias Paulo]]></dc:creator>
            <pubDate>Tue, 12 Aug 2025 12:40:03 GMT</pubDate>
            <atom:updated>2025-08-14T13:57:23.503Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yx_RGcElsy_Q540jrP4S5Q.png" /></figure><p>One of the core concepts in LangChain is the <strong>PromptTemplate</strong> — a reusable string template that you can dynamically populate with runtime values before sending it to a language model.</p><p>Let’s see how we can achieve this in C#. We’ll start by creating a new console application:</p><pre>dotnet new console -n TemplatedPrompts<br>cd TemplatedPrompts</pre><p>Next, add the following NuGet packages:</p><pre>dotnet add package LangChain<br>dotnet add package Microsoft.Extensions.Configuration.UserSecrets</pre><p>As you can see, we’ve included the package for handling user secrets during development. This is a good practice to avoid hardcoding sensitive data — in this case, your OpenAI API key.</p><p>To set up your secret:</p><pre>dotnet user-secrets init<br>dotnet user-secrets set &quot;OpenAI:ApiKey&quot; &quot;...&quot;</pre><h4>Let’s Code</h4><p>Here’s a working example that uses a templated prompt to ask a question to the model:</p><pre>using LangChain.Prompts;<br>using LangChain.Providers.OpenAI;<br>using LangChain.Schema;<br>using Microsoft.Extensions.Configuration;<br><br>var builder = new ConfigurationBuilder()<br>    .AddUserSecrets&lt;Program&gt;();<br><br>var config = builder.Build();<br>var apiKey = config[&quot;OpenAI:ApiKey&quot;]!;<br><br>var openAiModel = new OpenAiChatModel(apiKey, &quot;gpt-4o-mini&quot;);<br><br>var dynamicChatTemplate = new ChatPromptTemplate(new ChatPromptTemplateInput<br>{<br>    InputVariables = [&quot;domain&quot;, &quot;question&quot;],<br>    ValidateTemplate = true,<br>    PromptMessages = [<br>        new SystemMessagePromptTemplate(new PromptTemplate(new PromptTemplateInput(<br>            &quot;You are a helpful assistant specialized in {domain}.&quot;,<br>            [&quot;domain&quot;]<br>        ))),<br>        new HumanMessagePromptTemplate(new PromptTemplate(new PromptTemplateInput(<br>            &quot;{question}&quot;,<br>            [&quot;question&quot;]<br>        )))<br>    ]<br>});<br><br>var chatMessages = await dynamicChatTemplate.FormatAsync(new InputValues(new Dictionary&lt;string, object&gt;<br>{<br>    [&quot;domain&quot;] = &quot;travel agent&quot;,<br>    [&quot;question&quot;] = &quot;Could you recommend me 3 travel destinations with beach, warm weather and sunny?&quot;<br>}));<br><br>await foreach (var result in openAiModel.GenerateAsync(chatMessages, OpenAiChatSettings.Default))<br>{<br>    Console.WriteLine(result);<br>}</pre><p>The code starts by loading your OpenAI API key from user secrets, then initializes a OpenAiChatModel instance using the GPT-4o-mini model. A <strong>chat prompt template</strong> is constructed, consisting of two parts:</p><ul><li>A <strong>system message</strong> that defines the assistant’s role dynamically based on a domain (e.g., travel agent).</li><li>A <strong>human message</strong> that captures the actual user question.</li></ul><p>These components are defined using LangChain’s PromptTemplate and ChatPromptTemplate classes, allowing for reusable and composable prompt logic. Once the template is populated with values (domain and question), it&#39;s formatted into a list of messages, which is then passed to the model for generation.</p><p>The model responds asynchronously, and the final result is printed to the console.</p><p>This pattern mirrors LangChain’s approach in other languages — combining structured prompts with LLMs in a modular, testable way — but adapted to .NET idioms and tooling.</p><h4>Posts in this series:</h4><ol><li>Templated prompts</li><li><a href="https://medium.com/@matias.paulo84/chaining-prompts-in-c-sequential-reasoning-with-langchain-bf43e41a1438">Chaining Prompts in C#: Sequential Reasoning with LangChain</a></li><li><a href="https://medium.com/@matias.paulo84/memory-a-key-feature-for-conversational-agents-b96e2ba8d6fd">Memory: a key feature for conversational agents</a></li><li><a href="https://medium.com/@matias.paulo84/local-rag-in-c-connect-your-ai-to-external-knowledge-9cc16ddea07e">Local RAG in C#: Connect Your AI to External Knowledge</a></li><li><a href="https://medium.com/@matias.paulo84/a-real-example-troubleshooting-agent-797357c64f55">Real world example: A troubleshooting agent</a></li></ol><p>You can check the source code <a href="https://github.com/matipaulo/LangchainDemo">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=256f9d2777d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangChain for C# Developers]]></title>
            <link>https://medium.com/@matias.paulo84/langchain-for-c-developers-7f739b7664b0?source=rss-1701886feae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f739b7664b0</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Matias Paulo]]></dc:creator>
            <pubDate>Tue, 12 Aug 2025 12:39:57 GMT</pubDate>
            <atom:updated>2025-08-14T13:57:44.264Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yx_RGcElsy_Q540jrP4S5Q.png" /></figure><h3>What is LangChain?</h3><p>LangChain is an open-source framework designed to simplify the development of applications powered by large language models (LLMs). It provides high-level abstractions for prompt templates, chains, memory, agents, and more — all aimed at helping developers orchestrate intelligent, conversational workflows.</p><p>While LangChain is officially supported in Python and JavaScript, its architecture and patterns can be adopted in any language, including C#. The goal of this series is to show you how.</p><p>LangChain has gained significant traction in the Python and JavaScript ecosystems for building powerful, modular AI-driven applications. But what if you’re a .NET developer who wants to take advantage of the same capabilities — like templated prompts, memory, chains, and retrieval-augmented generation (RAG) — without leaving your C# comfort zone?</p><p>In this series, we’ll explore how to use LangChain concepts in C#, showing how to implement common AI workflows step-by-step using modern .NET practices. Whether you’re building intelligent assistants, automation agents, or simply experimenting with LLMs, this series will give you practical tools and inspiration.</p><p>Each post will focus on a specific aspect of LangChain-style architecture, from prompt engineering to memory and RAG, culminating in a real-world example. We’ll start with the basics: templated prompts, arguably the building blocks of any structured interaction with a language model. <br>As usual in my posts, we will be focusing on the implementation and having a working code.</p><h4>Posts in this series:</h4><ol><li>Templated prompts</li><li><a href="https://medium.com/@matias.paulo84/chaining-prompts-in-c-sequential-reasoning-with-langchain-bf43e41a1438">Chaining Prompts in C#: Sequential Reasoning with LangChain</a></li><li><a href="https://medium.com/@matias.paulo84/memory-a-key-feature-for-conversational-agents-b96e2ba8d6fd">Memory: a key feature for conversational agents</a></li><li><a href="https://medium.com/@matias.paulo84/local-rag-in-c-connect-your-ai-to-external-knowledge-9cc16ddea07e">Local RAG in C#: Connect Your AI to External Knowledge</a></li><li><a href="https://medium.com/@matias.paulo84/a-real-example-troubleshooting-agent-797357c64f55">Real world example: A troubleshooting agent</a></li></ol><p>You can check the source code <a href="https://github.com/matipaulo/LangchainDemo">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f739b7664b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chaining Prompts in C#: Sequential Reasoning with LangChain]]></title>
            <link>https://medium.com/@matias.paulo84/chaining-prompts-in-c-sequential-reasoning-with-langchain-bf43e41a1438?source=rss-1701886feae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf43e41a1438</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Matias Paulo]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 12:35:44 GMT</pubDate>
            <atom:updated>2025-08-14T13:58:00.126Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yx_RGcElsy_Q540jrP4S5Q.png" /></figure><p>In the previous post, we explored how to use <strong>templated prompts</strong> in C# to structure inputs for large language models. While this is a powerful foundation, real-world use cases often involve more than a single input-output interaction. You might want to break down a task into multiple steps, process intermediate results, or create multi-turn reasoning flows.</p><p>This is where <strong>chains</strong> come in.</p><p>In LangChain, a <strong>chain</strong> allows you to connect multiple prompt-execution steps together, passing the output of one as the input to the next. This mirrors how humans solve complex problems: step by step.</p><p>Although the official LangChain SDK for .NET is still evolving, we can implement the same architectural patterns using plain C# with LangChain’s building blocks.</p><h4>Understanding with an example</h4><p>This example demonstrates how to build a <strong>sequential chain</strong> using the LangChain C# SDK to solve a multi-step language modeling task:</p><ol><li>Generate a funny name for a pet.</li><li>Use that name to create a catchy slogan.</li></ol><p>The idea is to model a task where the output of one LLM call feeds directly into the next, just like a chain of reasoning.</p><pre>using LangChain.Chains.LLM;<br>using LangChain.Chains.Sequentials;<br>using LangChain.Prompts;<br>using LangChain.Providers.OpenAI;<br>using LangChain.Schema;<br>using Microsoft.Extensions.Configuration;<br><br>var builder = new ConfigurationBuilder()<br>    .AddUserSecrets&lt;Program&gt;();<br><br>var config = builder.Build();<br>var apiKey = config[&quot;OpenAI:ApiKey&quot;]!;<br>var openAiModel = new OpenAiChatModel(apiKey, &quot;gpt-4o-mini&quot;);<br><br>var nameChain = &quot;Generate a funny pet name for a {petType}.&quot;;<br>var firstPrompt = new PromptTemplate(new PromptTemplateInput(nameChain, new List&lt;string&gt;(1) { &quot;petType&quot; }));<br>var chainOne = new LlmChain(new LlmChainInput(openAiModel, firstPrompt)<br>{<br>    Verbose = true,<br>    OutputKey = &quot;petName&quot;<br>});<br><br>var catchyPhraseChain = &quot;Create a catchy phrase for a pet named &#39;{petName}&#39;.&quot;;<br>var secondPrompt = new PromptTemplate(new PromptTemplateInput(catchyPhraseChain, new List&lt;string&gt;(1) { &quot;petName&quot; }));<br>var chainTwo = new LlmChain(new LlmChainInput(openAiModel, secondPrompt)<br>{<br>    Verbose = true<br>});<br><br>var overallChain = new SequentialChain(new SequentialChainInput(<br>    [<br>        chainOne,<br>        chainTwo<br>    ],<br>    [&quot;petType&quot;],<br>    [&quot;petName&quot;, &quot;text&quot;]<br>));<br><br>var result = await overallChain.CallAsync(new ChainValues(new Dictionary&lt;string, object&gt;(1)<br>{<br>    { &quot;petType&quot;, &quot;dog&quot; },<br>    {&quot;petName&quot;, &quot;text&quot;}<br>}));</pre><p>The chain executes both prompts in order, and the result includes:</p><ul><li>A generated funny name for the dog (e.g., “Bark Twain”),</li><li>A slogan built from that name (e.g., “Life’s better with Bark Twain at your side!”).</li></ul><h4>When to use it?</h4><p>This approach allows you to break complex language interactions into clean, testable units. Sequential chains are particularly useful for:</p><ul><li>Multi-step instructions</li><li>Data transformation</li><li>Task decomposition</li><li>Progressive reasoning flows</li></ul><p>In the next post, we’ll explore how to maintain context across multiple interactions using <strong>memory</strong>, a key feature for conversational and agentic experiences.</p><h4>Posts in this series:</h4><ol><li>Templated prompts</li><li><a href="https://medium.com/@matias.paulo84/chaining-prompts-in-c-sequential-reasoning-with-langchain-bf43e41a1438">Chaining Prompts in C#: Sequential Reasoning with LangChain</a></li><li><a href="https://medium.com/@matias.paulo84/memory-a-key-feature-for-conversational-agents-b96e2ba8d6fd">Memory: a key feature for conversational agents</a></li><li><a href="https://medium.com/@matias.paulo84/local-rag-in-c-connect-your-ai-to-external-knowledge-9cc16ddea07e">Local RAG in C#: Connect Your AI to External Knowledge</a></li><li><a href="https://medium.com/@matias.paulo84/a-real-example-troubleshooting-agent-797357c64f55">Real world example: A troubleshooting agent</a></li></ol><p>You can check the source code <a href="https://github.com/matipaulo/LangchainDemo">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf43e41a1438" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory: a key feature for conversational agents]]></title>
            <link>https://medium.com/@matias.paulo84/memory-a-key-feature-for-conversational-agents-b96e2ba8d6fd?source=rss-1701886feae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b96e2ba8d6fd</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Matias Paulo]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 12:35:25 GMT</pubDate>
            <atom:updated>2025-08-14T13:58:12.733Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yx_RGcElsy_Q540jrP4S5Q.png" /></figure><p>When working with large language models (LLMs), the interaction is inherently <strong>stateless</strong> — each prompt is processed in isolation, without knowledge of what came before. This makes building coherent, multi-turn applications challenging.</p><p>That’s where <strong>memory</strong> comes into play: a mechanism that preserves conversational context across requests, allowing each model call to “remember” previous exchanges. LangChain offers robust abstractions to support this, including <strong>buffered memory</strong>, <strong>windowed memory</strong>, <strong>summary memory</strong>, and more.</p><p>In .NET, the LangChain approach mirrors these ideas, enabling .NET developers to compose context-aware workflows using familiar patterns from the C# world. By the end of this post, you’ll be able to:</p><ul><li><strong>Add memory</strong> to your chains so that prompts can refer to past user input or model output.</li><li>Choose the right memory implementation for different use cases — whether it’s retaining the full chat history, only recent exchanges, or summarizing long conversations.</li><li>Seamlessly integrate memory into your chains and watch them evolve from one-shot prompts to rich, conversational agents.</li></ul><h4>Types of Memory in LangChain</h4><p>LangChain provides several memory strategies depending on how much context you want to retain and how you want to manage it:</p><pre>| Memory Type                       | Description                                                                                                             |<br>| --------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |<br>| **BufferMemory**                  | Stores the full chat history. Ideal for rich, long conversations.                                                       |<br>| **BufferWindowMemory**            | Stores only the most recent `k` messages. Great for performance-limited scenarios.                                      |<br>| **SummaryMemory**                 | Summarizes old interactions to avoid token limits while retaining context.                                              |<br>| **ConversationTokenBufferMemory** | Keeps messages until a token limit is reached, trimming old ones. Useful for precise control over model context length. |</pre><h4>Let’s code!</h4><p>This example demonstrates how to create a <strong>conversational chatbot</strong> in C# using LangChain’s functional chaining style and built-in memory support.</p><p>Unlike previous examples where each input was treated in isolation, here we maintain a running <strong>conversation history</strong> that the model uses to understand context and continuity between messages.</p><pre>using LangChain.Memory;<br>using LangChain.Providers.OpenAI;<br>using Microsoft.Extensions.Configuration;<br>using static LangChain.Chains.Chain;<br><br>var builder = new ConfigurationBuilder()<br>    .AddUserSecrets&lt;Program&gt;();<br><br>var config = builder.Build();<br>var apiKey = config[&quot;OpenAI:ApiKey&quot;]!;<br>var openAiModel = new OpenAiChatModel(apiKey, &quot;gpt-4o-mini&quot;);<br><br>var template = @&quot;The following is a conversation between a helpful assistant and a user.<br><br>{history}<br>Human: {input}<br>Assistant: &quot;;<br><br>var memory = new ConversationBufferMemory();<br><br>var chain =<br>    LoadMemory(memory, outputKey: &quot;history&quot;)<br>    | Template(template)<br>    | LLM(openAiModel)<br>    | UpdateMemory(memory, requestKey: &quot;input&quot;, responseKey: &quot;text&quot;);<br><br>Console.WriteLine(&quot;Start a conversation with an assistant!&quot;);<br><br>while (true)<br>{<br>    Console.WriteLine();<br><br>    Console.Write(&quot;Human: &quot;);<br>    var input = Console.ReadLine() ?? string.Empty;<br>    if (input == &quot;exit&quot;)<br>    {<br>        break;<br>    }<br><br>    // Build a new chain by prepending the user&#39;s input to the original chain<br>    var currentChain = Set(input, &quot;input&quot;)<br>                       | chain;<br><br>    // Get a response from the Assistant<br>    var response = await currentChain.RunAsync(&quot;text&quot;);<br><br>    Console.Write(&quot;Assistant: &quot;);<br>    Console.WriteLine(response);<br><br>    Console.WriteLine(&quot;Memory contents: \n&quot; + string.Join(&#39;\n&#39;, memory.ChatHistory.Messages.Select(x =&gt; $&quot;{x.Role}: {x.Content}&quot;)));<br>}</pre><h4>How it Works</h4><ol><li><strong>Initialize the Model and Prompt Template</strong><br> The assistant is instructed via a static prompt that includes two placeholders:</li></ol><ul><li>{history} – the full chat history (provided by memory)</li><li>{input} – the latest user message</li></ul><p><strong>2. Set up Memory</strong><br> We use ConversationBufferMemory, which stores all exchanged messages between the human and the assistant. This memory will automatically be injected into the prompt via the {history} variable.</p><p><strong>3. Build a Dynamic Chain</strong><br> The chain is constructed using a pipeline-like syntax:</p><ul><li>LoadMemory(...): loads the chat history into the context.</li><li>Template(...): applies the message structure using the prompt.</li><li>LLM(...): sends the final prompt to the OpenAI model.</li><li>UpdateMemory(...): stores the latest human input and assistant response in memory.</li></ul><p><strong>4. Interactive Loop</strong><br> The program enters a loop, allowing the user to interact with the assistant. Each new input is wrapped in a Set(...) call, merged with the base chain, and then executed. The model&#39;s response is printed, and memory is updated.</p><p><strong>5. Inspecting Memory</strong><br> After each exchange, the current memory state is printed to the console so you can see exactly what the model has seen so far.</p><h4>Posts in this series:</h4><ol><li>Templated prompts</li><li><a href="https://medium.com/@matias.paulo84/chaining-prompts-in-c-sequential-reasoning-with-langchain-bf43e41a1438">Chaining Prompts in C#: Sequential Reasoning with LangChain</a></li><li><a href="https://medium.com/@matias.paulo84/memory-a-key-feature-for-conversational-agents-b96e2ba8d6fd">Memory: a key feature for conversational agents</a></li><li><a href="https://medium.com/@matias.paulo84/local-rag-in-c-connect-your-ai-to-external-knowledge-9cc16ddea07e">Local RAG in C#: Connect Your AI to External Knowledge</a></li><li><a href="https://medium.com/@matias.paulo84/a-real-example-troubleshooting-agent-797357c64f55">Real world example: A troubleshooting agent</a></li></ol><p>You can check the source code <a href="https://github.com/matipaulo/LangchainDemo">here</a>.</p><h4>References:</h4><ul><li><a href="https://python.langchain.com/docs/how_to/chatbots_memory/?utm_source=chatgpt.com">How to add memory to chatbots | 🦜️🔗 LangChain</a></li><li><a href="https://developersvoice.com/blog/ai-development/using-langchain-with-csharp/?utm_source=chatgpt.com">Using LangChain with C#: A Comprehensive Guide to Building Composable AI Applications</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b96e2ba8d6fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Local RAG in C#: Connect Your AI to External Knowledge]]></title>
            <link>https://medium.com/@matias.paulo84/local-rag-in-c-connect-your-ai-to-external-knowledge-9cc16ddea07e?source=rss-1701886feae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cc16ddea07e</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Matias Paulo]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 12:35:01 GMT</pubDate>
            <atom:updated>2025-08-14T13:58:22.919Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yx_RGcElsy_Q540jrP4S5Q.png" /></figure><p>Generative AI is powerful, but LLMs alone often fall short when it comes to delivering factually grounded, up-to-date, or domain-specific responses. That’s where <strong>Retrieval-Augmented Generation (RAG)</strong> comes in — by supplementing your model with relevant external knowledge before generating an answer, you significantly boost accuracy and relevance.</p><p>In this post, we’ll focus on <strong>local RAG</strong>, a variation that avoids sending your data to the cloud. Instead, everything — from embeddings to inference — runs on your machine, enhancing <strong>privacy</strong>, <strong>low latency</strong>, and <strong>cost-efficiency</strong>.</p><p>Popular tools like <strong>Ollama</strong> let you run LLMs locally, and you can pair them with lightweight vector stores such as <strong>SQLite‑VSS</strong> or even Azure Cosmos DB emulators in .NET environments. We’ll show you how to build a fully local pipeline using LangChain for C#, bringing together:</p><ul><li><strong>Embedding your documents</strong>,</li><li><strong>Storing and retrieving them</strong> via a local vector store,</li><li><strong>Injecting retrieved context</strong> into prompts,</li><li><strong>Generating grounded responses</strong> with a local LLM.</li></ul><p>As a result, your applications can answer questions about your own documents — like manuals, private records, or internal knowledge bases — without compromising security or privacy.</p><h4>Show me the code!</h4><p>In this demo, we’ll vectorize a PDF and ask questions that the LLM will answer using local context.</p><p><em>Install Ollama</em></p><p>You’ll need to download and install Ollama first.<br>Then pull the required models:</p><pre>ollama pull llama3<br>ollama pull all-minilm</pre><p><em>Start the server</em></p><pre>ollama serve</pre><p>Once running, the Ollama API will be available at: <a href="http://localhost:11434/api">http://localhost:11434/api</a></p><pre>using LangChain.Databases.Sqlite;<br>using LangChain.DocumentLoaders;<br>using LangChain.Extensions;<br>using LangChain.Providers;<br>using LangChain.Providers.Ollama;<br><br>var provider = new OllamaProvider();<br>var embeddingModel = new OllamaEmbeddingModel(provider, id: &quot;all-minilm&quot;);<br>var llm = new OllamaChatModel(provider, id: &quot;llama3&quot;);<br><br>var vectorDatabase = new SqLiteVectorDatabase(dataSource: &quot;vectors.db&quot;);<br>const string collectionName = &quot;dotnet&quot;;<br><br>var url = &quot;https://raw.githubusercontent.com/dotnet-architecture/eBooks/main/current/microservices/NET-Microservices-Architecture-for-Containerized-NET-Applications.pdf&quot;;<br>using var http = new HttpClient();<br>var pdfBytes = await http.GetByteArrayAsync(url);<br>using var pdfStream = new MemoryStream(pdfBytes);<br><br>var vectorCollection = await vectorDatabase.AddDocumentsFromAsync&lt;PdfPigPdfLoader&gt;(<br>    embeddingModel, // Used to convert text to embeddings<br>    dimensions: 1536, // Should be 1536 for TextEmbeddingV3SmallModel<br>    //dimensions: 384, //for all-MiniLM- 384 dimensions<br>    dataSource: new DataSource<br>    {<br>        Type = DataSourceType.Stream,<br>        Stream = pdfStream,<br>    },<br>    collectionName: collectionName,<br>    textSplitter: null,<br>    behavior: AddDocumentsToDatabaseBehavior.OverwriteExistingCollection);<br><br>const string question = &quot;What products can work on top of RabbitMQ?&quot;;<br><br>var similarDocuments = await vectorCollection.GetSimilarDocuments(embeddingModel, question, amount: 5);<br><br>Console.WriteLine(&quot;Similar Documents:&quot;);<br>foreach(var document in similarDocuments)<br>{<br>    Console.WriteLine(document);<br>}<br><br>var answer = await llm.GenerateAsync(<br>    $&quot;&quot;&quot;<br>     Use the following pieces of context to answer the question at the end.<br>     If the answer is not in context then just say that you don&#39;t know, don&#39;t try to make up an answer.<br>     Keep the answer as short as possible.<br><br>     {similarDocuments.AsString()}<br><br>     Question: {question}<br>     Helpful Answer:<br>     &quot;&quot;&quot;);<br><br>Console.WriteLine($&quot;LLM answer: {answer}&quot;);</pre><p><em>What’s Happening Behind the Scenes?</em></p><ol><li><strong>The PDF is downloaded</strong> and parsed into text.</li><li><strong>The content is embedded</strong> using the all-minilm model from Ollama.</li><li><strong>The vector representations</strong> are stored locally in SQLite.</li><li><strong>At query time</strong>, we embed the question and find the most semantically similar passages.</li><li>The retrieved content is injected into the prompt to provide <strong>context</strong> to the LLM.</li><li>The LLM (running locally via Ollama) generates a grounded, context-aware response.</li></ol><p>Retrieval-Augmented Generation is a game changer for building intelligent and reliable AI systems. By connecting language models to your own data sources, you enable them to move from generic completions to <strong>useful</strong>, <strong>truthful</strong>, and <strong>domain-specific</strong> answers.</p><p>In this post, you’ve learned how to implement a <strong>local RAG pipeline</strong> in C# using LangChain, Ollama, and SQLite. You now have full control over both the <strong>knowledge base</strong> and the <strong>LLM</strong> — all running privately on your own machine.</p><p>Whether you’re building developer tools, business intelligence agents, or personal assistants, this pattern provides the flexibility and power to bring generative AI closer to your data, your infrastructure, and your users.</p><h4>Posts in this series:</h4><ol><li>Templated prompts</li><li><a href="https://medium.com/@matias.paulo84/chaining-prompts-in-c-sequential-reasoning-with-langchain-bf43e41a1438">Chaining Prompts in C#: Sequential Reasoning with LangChain</a></li><li><a href="https://medium.com/@matias.paulo84/memory-a-key-feature-for-conversational-agents-b96e2ba8d6fd">Memory: a key feature for conversational agents</a></li><li><a href="https://medium.com/@matias.paulo84/local-rag-in-c-connect-your-ai-to-external-knowledge-9cc16ddea07e">Local RAG in C#: Connect Your AI to External Knowledge</a></li><li><a href="https://medium.com/@matias.paulo84/a-real-example-troubleshooting-agent-797357c64f55">Real world example: A troubleshooting agent</a></li></ol><p>You can check the source code <a href="https://github.com/matipaulo/LangchainDemo">here</a>.</p><h4>References</h4><ul><li><a href="https://jasonhaley.com/2024/12/22/introducing-sk-local-rag-series">Introducing: the Local RAG Series (with Semantic Kernel)</a></li><li><a href="https://www.educative.io/blog/ollama-guide">Ollama guide: Building local RAG chatbots with LangChain</a></li><li><a href="https://devblogs.microsoft.com/cosmosdb/build-a-rag-application-with-langchain-and-local-llms-powered-by-ollama">Build a RAG application with LangChain and Local LLMs powered by Ollama - Azure Cosmos DB Blog</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cc16ddea07e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Are you handling exceptions correctly?]]></title>
            <link>https://medium.com/@matias.paulo84/are-you-handling-exceptions-correctly-9966983e329d?source=rss-1701886feae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9966983e329d</guid>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[filters]]></category>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[exception]]></category>
            <category><![CDATA[problemdetails]]></category>
            <dc:creator><![CDATA[Matias Paulo]]></dc:creator>
            <pubDate>Mon, 27 Jun 2022 14:54:39 GMT</pubDate>
            <atom:updated>2022-06-27T14:54:39.799Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello!! Today I want to share with you 3 different ways to perform global error handling.<br>The idea is to catch the exceptions, transform them into some standard and return it to the client.</p><p>This sound pretty straightforward but there are some details that I want to share with you. The first thing to discuss is how we can return the exception to the client in some kind of standard way, the answer to this is the “Problem Details” <a href="https://datatracker.ietf.org/doc/html/rfc7807">specification</a>.</p><blockquote>This document defines a &quot;problem detail&quot; as a way to carry machine-<br> readable details of errors in a HTTP response to avoid the need to<br> define new error response formats for HTTP APIs.</blockquote><p>The “Problem Details” can have the following members:</p><ul><li><strong>type</strong> (string) — A URI reference [<a href="https://datatracker.ietf.org/doc/html/rfc3986">RFC3986</a>] that identifies the<br> problem type. This specification encourages that, when<br> dereferenced, it provide human-readable documentation for the<br> problem type (e.g., using HTML [<a href="https://datatracker.ietf.org/doc/html/rfc7807#ref-W3C.REC-html5-20141028">W3C.REC-html5–20141028</a>]). When<br> this member is not present, its value is assumed to be<br> “about:blank”.</li><li><strong>title</strong> (string) — A short, human-readable summary of the problem<br> type. It SHOULD NOT change from occurrence to occurrence of the<br> problem, except for purposes of localization.</li><li><strong>status</strong> (number) — The HTTP status code generated by the origin server for this occurrence of the problem.</li><li><strong>details</strong> (string) — A human-readable explanation specific to this<br> occurrence of the problem.</li><li><strong>instance</strong> (string) — A URI reference that identifies the specific<br> occurrence of the problem. It may or may not yield further<br> information if dereferenced.</li></ul><p>Now let’s try to implement it in our project, in order to achieve it we can do it in 3 different ways:</p><ul><li>A custom middleware</li><li>A custom filter</li><li>Error endpoint</li></ul><p>Let’s see how we can implement each one of the options.</p><h4>Middleware</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3c8b327bb6fe1fb80ce669fcc7a2963/href">https://medium.com/media/d3c8b327bb6fe1fb80ce669fcc7a2963/href</a></iframe><p>As you can see, when an exception occurs we are creating a “ProblemDetails” object and return it as a response.</p><pre>{<br>  &quot;type&quot;: &quot;https://datatracker.ietf.org/doc/html/rfc7231#section-6.6.1&quot;,<br>  &quot;title&quot;: &quot;An error occurred trying to process the request.&quot;,<br>  &quot;status&quot;: 500,<br>  &quot;detail&quot;: &quot;My testing exception.&quot;,<br>  &quot;instance&quot;: &quot;/WeatherForecast&quot;<br>}</pre><h4>Filter</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf817e386f6aadb2f3883b4d4562cd99/href">https://medium.com/media/cf817e386f6aadb2f3883b4d4562cd99/href</a></iframe><p>Pretty simple and straightforward, the only thing is that you need to remember to register the filter and add it to your controller.</p><h4>Error endpoint</h4><p>This approach is quite different, first, we need to add the “UseExceptionHandler” middleware, it will catch the exception, log it and route it to the specified path.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9565e7b71140cdca4c2219eaa0547548/href">https://medium.com/media/9565e7b71140cdca4c2219eaa0547548/href</a></iframe><p>Then, we need to create the controller.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2eeac55a251ccda9a436400929eb16ae/href">https://medium.com/media/2eeac55a251ccda9a436400929eb16ae/href</a></iframe><p>Now, let’s take a look at the response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kz6GxzTNAdwsskCrQ0Gy7w.png" /></figure><p>As you can notice the response looks similar but it is adding a new property, “traceId”. In the following post, we will review how is that this property is being returned and how to enrich our response.</p><p>As always you can check the source code from <a href="https://github.com/matipaulo/Demos/tree/main/GlobalErrorHandling">here</a>.</p><p>Enjoy and happy coding! : )</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9966983e329d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Minimal APIs in Net6]]></title>
            <link>https://medium.com/@matias.paulo84/minimal-apis-in-net6-b6c263197434?source=rss-1701886feae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6c263197434</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[minimal-api]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[net6]]></category>
            <dc:creator><![CDATA[Matias Paulo]]></dc:creator>
            <pubDate>Wed, 09 Mar 2022 14:02:45 GMT</pubDate>
            <atom:updated>2022-03-10T13:01:05.464Z</atom:updated>
            <content:encoded><![CDATA[<p>With the release of NET6, the DotNet team introduced a lot of new features, one of those being the minimal APIs.<br>Minimal APIs are being designed to create HTTP APIs with the minimum dependencies possible.</p><p>According to Microsoft:</p><blockquote>There’s no plan to deprecate controllers, but we do want Minimal APIs to be able to be used in place of controllers for maybe 80–90% of scenarios. Controllers in ASP.NET Core MVC have many, many features that while powerful add a lot of complexity and, in some cases, ceremony that simply isn’t required for a lot of apps. That complexity also adds overhead that means there’s a limit to how much we can improve the performance of Controllers before hitting diminishing returns (in truth we’re already there).</blockquote><p>Creating an API in .NET, until this release, was kind of complex; you need to add all the things related to the “host” in the <strong>Program.cs</strong> class and also configure all what we need in the <strong>Startup</strong>.</p><p>In the <strong>Startup</strong> class, we define our services, controllers, authentication, pipelines, etc. Is not hard when you know how to do it. The main idea of the DotNet team was to help to make life easier for new developers, with that in mind they introduced this new way to create APIs.</p><h4>Let’s create a new project</h4><p>Before starting you should be aware that .NET 6 only works with VS2022, if you have a previous version you will have to update it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*0XQdF8nbxbPK8eBAdcTqUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*_q5E5daQerxWWhXHUeoueQ.png" /></figure><p>Here, you will have to ucheck “Use controllers”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*qIeoZSZge_BCjkPazlGq5Q.png" /></figure><p>And that is it. This is how it looks our <strong>Program.cs</strong> class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*JXTOWMQmWKcC6OHK50iqig.png" /></figure><p>As you can notice, in line 24 we are exposing a HttpGet endpoint, this is the old get weather endpoint but using the minimal APIs feature.</p><p>So, let’s try to improve the generated code, the first thing we can do is remove the delegate code and move it to a service class.</p><p>We can create a <em>WeatherService</em> class, which will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*7IcRcRs0t5XVv0gIFEB_Nw.png" /></figure><p>After that, you need to register the service in the container and update the endpoint call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6F4QcdViQwqU7AyVMV1lVw.png" /></figure><p>Looks better! but each new endpoint we need, we will have to map it in the <em>Program.cs</em> class, which could be kinda annoying, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YX9YBFqI4QoAm2XZTgZX6Q.png" /></figure><p>Let’s try again. Something that we can do, is create a class per resource.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w2iCiNWqJkMSgrgJ7mOnbw.png" /></figure><p>We have a couple of things to point out here.</p><ul><li>The class is implementing the <strong>IEndpointRouting</strong> interface.</li><li>Under the “<em>Register</em>” method, we are mapping our endpoints and defining the delegates.</li><li>We don’t have an extension method for the “<em>Patch</em>” verb, so we are making use of the “<em>MapMethods</em>” extension in order to map this verb.</li><li>We are injecting the “<em>WeatherForecastService</em>” created previously as our delegate.</li></ul><p>Th last step we need to do, is to update our <strong>Program.cs</strong> class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*nFtjppsV1aTHfMR-uWko9w.png" /></figure><p>Here, we are just adding the new class to the container and mapping all the endpoints in line 24.</p><p>The final result looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J00ZEengaA4qQhmhm94I3w.png" /></figure><p>As always you can check the source code from <a href="https://github.com/matipaulo/Demos/tree/main/MinimalAPIs">here</a>.</p><p>Enjoy and happy coding! : )</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6c263197434" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load and stress testing in .NET 6]]></title>
            <link>https://medium.com/@matias.paulo84/load-and-stress-testing-in-net-6-725ba346cf78?source=rss-1701886feae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/725ba346cf78</guid>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[stress-testing]]></category>
            <category><![CDATA[net6]]></category>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[k6]]></category>
            <dc:creator><![CDATA[Matias Paulo]]></dc:creator>
            <pubDate>Wed, 02 Feb 2022 14:05:51 GMT</pubDate>
            <atom:updated>2022-02-02T14:08:06.632Z</atom:updated>
            <content:encoded><![CDATA[<h3>Load and stress testing in .NET 6</h3><p>Hello! In this story, I want to show how you can perform load and stress testing in NET6, in a really quick and easy way.</p><p>Recently, I discovered the excellent library <a href="https://k6.io/">K6</a>, which makes performing tests really easy.</p><h4>Why do I need to test the performance of my app?</h4><p>Measuring the performance of our app in an early stage will help us to build resilient and performant applications that will be able to scale without performance degradation.</p><p>In this article, I’ll show you how you can perform the test in a Windows environment but you can check the documentation about how you can use the tool from Linux, MacOS, or even docker. Also, you can add the tests to your pipeline and make it fail if some commit did some impact on the performance.</p><h4>Installation</h4><p>You can check <a href="https://k6.io/docs/getting-started/installation/">here</a> how to install the tool. Since we are focusing on “Windows”, you just need to <a href="https://dl.k6.io/msi/k6-latest-amd64.msi">download</a> and install the package, and done! we can start coding!</p><p>Because I’m kind of a lazy boy, I’ll use the default weather forecast example. Let’s create a new project and add the tests.</p><h4>Load tests</h4><p>Load Testing is a type of Performance Testing used to determine a system’s behavior under both normal and peak conditions.</p><p>Load Testing is used to ensure that the application performs satisfactorily when many users access it at the same time.</p><p>In this case, we will add a new file to the root of our app, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*WFgVMefLTc1Samtg4LUP4g.png" /></figure><p>The file content looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57e4d439edb1a1c728b071271040a5b3/href">https://medium.com/media/57e4d439edb1a1c728b071271040a5b3/href</a></iframe><p><strong>Note</strong>: Checks are like assertions, but differ in that they don’t halt the execution. Instead, they store the result of the check, pass or fail, and let the script execution continue. If you want to know how you can create stages, please check: <a href="https://k6.io/docs/using-k6/options/#stages">https://k6.io/docs/using-k6/options/#stages</a>.</p><h4>Stress tests</h4><p>Stress testing is one of the many different types of load testing. While load testing is primarily concerned with assessing the system’s performance, the purpose of stress testing is to assess the availability and stability of the system under heavy load.</p><p>Again, we need a new file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b62b4120c13aa411832f7b5908f8ba22/href">https://medium.com/media/b62b4120c13aa411832f7b5908f8ba22/href</a></iframe><h4>How to run them?</h4><p>The first thing we need to do is open a console and go to the API folder. Once we are at the root of th API project, we need to run the API with the following command: <strong><em>dotnet run -c release</em></strong></p><p>This command will run the API using the “release” profile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*40EPEaNZWxuCv8s11WGSGg.png" /></figure><p>Now, we only need to perform the test. Open a new console, go to the API folder again, and execute the following command: <strong><em>k6 run load.js</em></strong></p><p>This will execute the load tests that we defined in the <strong><em>load.js</em></strong> file, if we want to run the stress tests, we only need to run the command again but using the <strong><em>stress.js</em></strong> file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*yMyTuD2oAa_6AEdz77acpQ.png" /></figure><p>Results are back:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*xSMRgv6GIaMm54SvjAHF4A.png" /></figure><p>As we can see in the output, 100% of the check were successful, which in this case makes sense, since is a really simple scenario.</p><p>Also we have information about the requests per second, the duration, requests failed, etc.</p><p>If you want to know more about the ouptput, please check <a href="https://k6.io/docs/getting-started/results-output/">https://k6.io/docs/getting-started/results-output/</a>.</p><p>As always you can check the source code from <a href="https://github.com/matipaulo/Demos/tree/main/LoadTests">here</a>.</p><p>Enjoy and happy coding! : )</p><h4>References</h4><ul><li><a href="https://k6.io/">https://k6.io</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=725ba346cf78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Containerized microservices with sync/async communication]]></title>
            <link>https://medium.com/@matias.paulo84/containerized-microservices-with-sync-async-communication-56d871866795?source=rss-1701886feae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/56d871866795</guid>
            <category><![CDATA[mass-transit]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Matias Paulo]]></dc:creator>
            <pubDate>Fri, 12 Nov 2021 20:32:36 GMT</pubDate>
            <atom:updated>2021-11-12T20:32:36.990Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello! In the <a href="https://medium.com/@matias.paulo84/collecting-metrics-in-aspnet-core-app-c626d946ca8a">previous article</a>, we created a containerized solution for collecting metrics from our API, and that encourage me to create another article talking about containerized microservices and how to implement the communication between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*010Rz6c_j-zLv_JTmsBlQw.png" /></figure><p>So, the history of this app is very simple, the main idea is to simulate in a real simple (and dummy) way an e-commerce backend. We will have 4 containers, where 3 of them are APIs and the last one is for <a href="https://www.rabbitmq.com/">RabbitMQ</a>.</p><h4>Containers</h4><ul><li><strong>catalogapi</strong>: This API, makes use of <a href="https://github.com/bchavez/Bogus">Bogus</a> in order to generate fake random products. It exposes a set of endpoints for interacting with them.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ZHb-G2P0B05znvEeq-9Zg.png" /></figure><ul><li><strong>basketapi</strong>: From here we are going to create our basket, add items to him, and perform the checkout. This API performs a sync communication with the catalog services and an async communication with the ordering API, we will review how all this works later.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VpmTzAdGeecOmBKEhr74eQ.png" /></figure><ul><li><strong>oderingapi</strong>: The last API has only a purpose, create an order and save it. The service is consuming a checkout event raised by the basket service.</li><li><strong>rabbitmq</strong>: In this case, we have running an instance the RabbitMQ mananagement app, from here manage our queues, users, etc.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*RxgwUtEnBY0Zif52BTyF8A.png" /></figure><h4>Composing</h4><p>Before start jumping into the code, we are going to create 3 .NET Core API projects, each one of them will represent the services described previously. We are going to dockerize each one of them and composite them along with RabittMQ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*ADMGRb23pQHKXXpdB0s21g.png" /></figure><p>Your <em>docker-compose</em> file will look like this:</p><pre>version: &#39;3.8&#39;<br><br>networks:<br>  dotnetcorenetwork:<br>    driver: bridge<br><br>services:<br>  rabbitmq:<br>    container_name: rabbitmq<br>    ports:<br>        - 5672:5672<br>        - 15672:15672<br>    environment:<br>        - RABBITMQ_DEFAULT_USER=guest<br>        - RABBITMQ_DEFAULT_PASS=guest<br>    image: rabbitmq:3-management<br>    networks:<br>        - dotnetcorenetwork<br><br>  catalog.api:<br>    container_name: catalogapi<br>    ports:<br>        - 5000:80<br>        - 5001:443<br>    environment:<br>        - ASPNETCORE_ENVIRONMENT=Development<br>    image: ${DOCKER_REGISTRY-}catalogapi<br>    build:<br>      context: .<br>      dockerfile: Services/Catalog.Api/Dockerfile<br>    restart: always<br>    networks:<br>        - dotnetcorenetwork<br>  <br>  basket.api:<br>    container_name: basketapi<br>    ports:<br>        - 6000:80<br>        - 6001:443<br>    environment:<br>      - ASPNETCORE_ENVIRONMENT=Development<br>      - ASPNETCORE_URLS=https://+:443;http://+:80<br>    image: ${DOCKER_REGISTRY-}basketapi<br>    build:<br>      context: .<br>      dockerfile: Services/Basket.Api/Dockerfile<br>    restart: always<br>    networks:<br>        - dotnetcorenetwork<br>    depends_on:<br>        - rabbitmq<br>        - catalogapi<br><br>  ordering.api:<br>    container_name: orderingapi<br>    ports:<br>        - 7000:80<br>        - 7001:443<br>    environment:<br>        - ASPNETCORE_ENVIRONMENT=Development<br>        - ASPNETCORE_URLS=https://+:443;http://+:80<br>    image: ${DOCKER_REGISTRY-}orderingapi<br>    build:<br>      context: .<br>      dockerfile: Services/Ordering.Api/Dockerfile<br>    restart: always<br>    networks:<br>        - dotnetcorenetwork<br>    depends_on:<br>        - rabbitmq</pre><p>As you can see, the composition doesn’t have anything weird, we are mapping ports, setting some environment variables and specifying the path to the “Dockerfile”.</p><h4>Basket API</h4><p>This API will consume the Catalog API and also will publish a message in RabbitMQ using the “<a href="https://masstransit-project.com/">Masstransit</a>” library.</p><p>Let’s review the implementation of the method for adding an item to the basket.</p><pre>[HttpPost(&quot;{basketId}/items&quot;)]<br>public async Task&lt;ActionResult&gt; AddItem([FromRoute] string basketId, [FromBody] AddItem request)<br>{<br>    if (!_basket.ContainsKey(basketId))<br>        return BadRequest();<br>    <br>    var product = await _catalogApiClient.GetProduct(request.Id);<br>    if (product is null)<br>        return BadRequest();<br><br>    _basket[basketId].Items.Add(new ShoppingCartItem<br>    {<br>        Id = request.Id,<br>        Name = product.Name,<br>        Price = product!.Price,<br>        Quantity = request.Quantity<br>    });<br><br>    return Ok();<br>}</pre><p>The code is simple, at the beginning we are checking if the basket exists, getting the product details from the catalog service and adding the item to the basket. The thing that I want to show you here is how we are getting the product in a synchronous way making a Http request to the catalog API, in order to achieve it, we are making use of the HttpClient. If you want to know more, please check this <a href="https://medium.com/@matias.paulo84/experimenting-with-httpclient-cf9f5dda7195">article</a>.</p><p>The API client look like this:</p><pre>public class CatalogApiClient<br>{<br>    private readonly HttpClient _httpClient;<br><br>    public CatalogApiClient(HttpClient httpClient)<br>    {<br>        _httpClient = httpClient;<br>    }<br><br>    public async Task&lt;ProductDto?&gt; GetProduct(int productId)<br>    {<br>        return await _httpClient.GetFromJsonAsync&lt;ProductDto&gt;($&quot;api/Catalog/{productId}&quot;);<br>    }<br>}</pre><p>As you can notice we are exposing a method which receives a “productId” and perform a “GET” call and finally deserialize and return the data. The way to register this client is like this:</p><pre>builder.Services.AddHttpClient&lt;CatalogApiClient&gt;(x =&gt;<br>{<br>    x.BaseAddress = new Uri(&quot;http://catalogapi/&quot;);<br>});</pre><p>As base URL, we are using the container name defined in the <em>docker-compose</em> file.</p><p>NOTE: I’m using .NET 6, so this can look a little different from you if you didn’t see anything about the new features.</p><p>The other endpoint that I want to review with you is the “checkout”.</p><pre>[HttpPost(&quot;{basketId}/checkout&quot;)]<br>public async Task&lt;IActionResult&gt; Checkout([FromRoute] string basketId, [FromBody] BasketCheckout basketCheckout)<br>{<br>    var basket = _basket[basketId];<br>    if (basket == null)<br>        return BadRequest();<br><br>    var eventMessage = new CheckoutEvent<br>    {<br>        Address = basketCheckout.Address,<br>        CardName = basketCheckout.CardName,<br>        CardNumber = basketCheckout.CardNumber,<br>        CVV = basketCheckout.CVV,<br>        Email = basketCheckout.Email,<br>        Expiration = basketCheckout.Expiration,<br>        FirstName = basketCheckout.FirstName,<br>        LastName = basketCheckout.LastName,<br>        Total = _basket[basketId].Total,<br>        Items = _basket[basketId].Items.Select(x =&gt; new Item<br>        {<br>            Id = x.Id,<br>            Name = x.Name,<br>            Price = x.Price,<br>            Quantity = x.Quantity<br>        }).ToList()<br>    };<br><br>    await _publishEndpoint.Publish&lt;CheckoutEvent&gt;(eventMessage);<br><br>    _basket.TryRemove(basketId, out _);<br><br>    return Accepted();<br>}</pre><p>We are creating an event, which is being published using Masstransit, and removing the basket from the memory.</p><p>Publishing an event to RabbitMQ is very easy with Mmasstransit. In order to publish messages, we should make use of “<em>IPublishEndpoint</em>”.</p><p>The last piece here is the registration. Adds MassTransit Service to the .NET Core Service Container and creates a new Service Bus connection using RabbitMQ. We need to set paramteres like host url, username and password.</p><pre>builder.Services.AddMassTransit(config =&gt;<br>{<br>    config.UsingRabbitMq((ctx, cfg) =&gt;<br>    {<br>     cfg.Host(builder.Configuration[&quot;EventBusSettings:HostAddress&quot;]);<br>    });<br>});</pre><p><em>Appsettings.json</em> file.</p><pre>{<br>  &quot;Logging&quot;: {<br>    &quot;LogLevel&quot;: {<br>      &quot;Default&quot;: &quot;Information&quot;,<br>      &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;<br>    }<br>  },<br>  &quot;EventBusSettings&quot;: {<br>    &quot;HostAddress&quot;: &quot;amqp://guest:guest@rabbitmq:5672&quot;<br>  },<br>  &quot;AllowedHosts&quot;: &quot;*&quot;<br>}</pre><h4>Ordering API</h4><p>In this API we are just going to consume “<strong><em>CheckoutEvent</em></strong>”, after receiving it, we are going to create an “<em>Order</em>” and save it. The consumption of the event is an async communication between the basket and ordering services.</p><p>We are going to use Masstransit in order to consume the event, which needs to be registered like this:</p><pre>builder.Services.AddMassTransit(config =&gt;<br>{<br>    config.AddConsumer&lt;CheckoutConsumer&gt;();<br>    config.UsingRabbitMq((ctx, cfg) =&gt;<br>    {<br>      cfg.Host(builder.Configuration[&quot;EventBusSettings:HostAddress&quot;]);<br><br>        cfg.ReceiveEndpoint(EventBusConstants.BasketCheckout, c =&gt;<br>        {<br>            c.ConfigureConsumer&lt;CheckoutConsumer&gt;(ctx);<br>        });<br>    });<br>});</pre><pre>builder.Services.AddMassTransitHostedService();</pre><p>As you can notice, this is similar to the registration that we did in the Basket API. Here we are registering a consumer, in our case “<strong><em>CheckoutConsumer</em></strong>” and also we are specifying the endpoint that we are listening with his consumer. Finally, we are adding Masstransit as hosted service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*mo7Phvejno09mdSEM_eacw.png" /></figure><p>Let’s take a look to the consumer.</p><pre>public class CheckoutConsumer : IConsumer&lt;CheckoutEvent&gt;<br>{<br>    private readonly IMediator _mediator;<br>    private readonly ILogger&lt;CheckoutConsumer&gt; _logger;<br><br>    public CheckoutConsumer(IMediator mediator, ILogger&lt;CheckoutConsumer&gt; logger)<br>    {<br>        _mediator = mediator;<br>        _logger = logger;<br>    }<br><br>    public async Task Consume(ConsumeContext&lt;CheckoutEvent&gt; context)<br>    {<br>        var command = new CheckoutCommand<br>        {<br>            Address = context.Message.Address,<br>            CardName = context.Message.CardName,<br>            CardNumber = context.Message.CardNumber,<br>            CVV = context.Message.CVV,<br>            Email = context.Message.Email,<br>            Expiration = context.Message.Expiration,<br>            FirstName = context.Message.FirstName,<br>            LastName = context.Message.LastName,<br>            Total = context.Message.Total,<br>            Items = context.Message.Items.Select(x =&gt; new OrderItem<br>            {<br>                Name = x.Name,<br>                Price = x.Price,<br>                Quantity = x.Quantity<br>            }).ToList()<br>        };<br><br>        var orderId = await _mediator.Send(command);<br>        _logger.LogInformation($&quot;Order created: {orderId}&quot;);<br>    }<br>}</pre><p>Our consumer class it is implementing the “<strong><em>IConsumer&lt;T&gt;</em></strong>” interface. In the exposed method we are receiving the message and creating a command.</p><p>We are going to implement the mediator pattern with the “<em>MediatR</em>” library. The handler will create a new order, save it and return his “<em>Id</em>”.</p><p>We are going to use EF In-Memory in order to store the orders.</p><pre>public async Task&lt;int&gt; Handle(CheckoutCommand request, CancellationToken cancellationToken)<br>{<br>    _logger.LogInformation(&quot;Create and save the order.&quot;);<br><br>    var savedOrder = await _context.Orders.AddAsync(new Order<br>    {<br>        Address = request.Address,<br>        CardName = request.CardName,<br>        CardNumber = request.CardNumber,<br>        CVV = request.CVV,<br>        Email = request.Email,<br>        Expiration = request.Expiration,<br>        FirstName = request.FirstName,<br>        LastName = request.LastName,<br>        Total = request.Total,<br>        Items = request.Items.Select(x =&gt; new Data.OrderItem<br>        {<br>            Name = x.Name,<br>            Price = x.Price,<br>            Quantity = x.Quantity<br>        }).ToList()<br>    });<br><br>    await _context.SaveChangesAsync();<br><br>    return savedOrder.Entity.Id;<br>}</pre><h4>Conclusions</h4><p>In this article we reviewed real quick how we can implement <em>sync/async</em> communication between different dockerized services.<br>For the sync communication, we implemented an API client which will perform <em>HTTP</em> requests to the services.<br>In the async scenario, we discovered that using <strong><em>Masstransit</em></strong> with <strong><em>RabbitMQ</em></strong> is really easy to integrate.</p><p>In the repository you will find a <em>Postman</em> in order to test the APIs.</p><p>As always you can check the source code from <a href="https://github.com/matipaulo/Demos/tree/main/MicroservicesWithRabbitMQ">here</a>.</p><p>Enjoy and happy coding! : )</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56d871866795" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>