<?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 Nagendra K on Medium]]></title>
        <description><![CDATA[Stories by Nagendra K on Medium]]></description>
        <link>https://medium.com/@nagendrak?source=rss-dadfca5f64eb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*GJucTPjw_kJRpPfR.jpg</url>
            <title>Stories by Nagendra K on Medium</title>
            <link>https://medium.com/@nagendrak?source=rss-dadfca5f64eb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 00:21:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nagendrak/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[Building an AI-Powered Chat Application in .NET Using Ollama Server]]></title>
            <link>https://medium.com/@nagendrak/building-an-ai-powered-chat-application-in-net-using-ollama-server-4c06b9445d93?source=rss-dadfca5f64eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c06b9445d93</guid>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chat-api]]></category>
            <dc:creator><![CDATA[Nagendra K]]></dc:creator>
            <pubDate>Sat, 16 Aug 2025 19:01:08 GMT</pubDate>
            <atom:updated>2025-08-16T19:18:25.066Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an AI-Powered Chat Application in .NET Using Ollama</h3><p>Artificial Intelligence (AI) has become a transformative force across industries, and its integration into software applications is no longer a novelty — it’s a necessity. In this article, we’ll walk through the process of building an AI-powered chat application using .NET Web API and the Ollama Large Language Model (LLM), leveraging both direct API integration and Microsoft’s Semantic Kernel for orchestration.</p><h3><strong>Overview</strong></h3><p>This guide focuses on implementing a conversational AI backend using the Ollama LLM hosted via Docker. We’ll explore two integration paths:</p><ul><li><strong>Direct API calls to Ollama’s chat completion endpoint</strong></li><li><strong>Using Semantic Kernel to abstract and orchestrate LLM interactions</strong></li></ul><p>By the end of this article, you’ll have a functional .NET Web API that can serve as the foundation for intelligent chat interfaces in web or mobile applications.</p><h3>Prerequisites</h3><p>Before diving into the implementation, ensure the following components are installed and configured:</p><ul><li><strong>.NET SDK (7.0 or later)</strong></li><li><strong>Docker Desktop</strong></li><li><strong>Ollama Server (via Docker container)</strong></li><li><strong>Semantic Kernel NuGet package (optional but recommended)</strong></li></ul><h3><strong>Setting Up the Ollama Server via Docker</strong></h3><p>To run the Ollama LLM locally, you’ll need to pull and start the Ollama container using Docker Desktop. Follow these steps:</p><ol><li><strong>Launch Docker Desktop</strong></li><li>Navigate to the <strong>Docker Hub</strong> tab</li><li>Search for <strong>“Ollama”</strong></li><li>Select the official Ollama image from the search results</li><li>Pull the image and run the container</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zQ2l5lIZAiSpMrdnvwlz6w.png" /></figure><p>Click “Run” button as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQTfEaq3j_KMdAMO_9L6fA.png" /></figure><p>2. Alternatively, to Install in more precise way, we can issue following docker command in the Terminal :</p><pre>docker run -d -v ollama:/root/.ollama -p 11434:11434 --name ollama ollama/ollama</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*43wAraI9gVpRNf-1YyEu_w.png" /></figure><p>This will expose the Ollama API on port 11434, allowing your .NET application to interact with it via HTTP requests.</p><p>By default, the Ollama server runs on <strong>port 11434</strong> when hosted locally via Docker. It’s crucial to ensure that your application targets the correct port; otherwise, you may encounter connectivity issues such as “Ollama is not running locally.”</p><p>✅ Verifying Ollama Server Status</p><p>To confirm that the Ollama container is running successfully:<br>- Open Docker Desktop<br>- Navigate to the Containers tab<br>- Click on the container’s exposed port number (11434)<br>If the server is active, you should see a confirmation message such as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RCQL9y38XsJL8QbOGUWjKw.png" /></figure><p>🧠 Executing a Specific Ollama Model</p><p>Once the server is up, the next step is to load and run a specific model. In this example, we’ll use the <strong>LLaMA 3.2</strong> model. Execute the following command in Docker Desktop’s terminal or your system shell:</p><p>This command initializes the model within the running container.</p><pre>docker exec -it ollama ollama run llama3.2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ahabwa4H14DoMCcFL-es2g.png" /></figure><p>📋 Verifying Model Installation</p><p>To ensure that the model has been successfully added, you can list all available models using “ollama list” command as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vOf0sDbt1oMrWp7tXUQ5yw.png" /></figure><p>Alternatively, you can verify the model via Ollama’s REST API:</p><p>GET <a href="http://localhost:11434/api/tags">http://localhost:11434/api/tags</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tX-oMRmxZNyBk7012KiMuQ.png" /></figure><p>This endpoint returns a JSON response containing all installed models and their metadata.</p><h3>💬 Next Step: Implementing the .NET Chat Application</h3><p>Now, we have added the model “llama3.2” to the our local docker container. Now it’s time to implement chat application in .Net using llama3.2 model . As I mentioned earlier, we can initially implement it using Ollama LLM End point as shown below:</p><h3>🔌 Approach 1: Integrating with Ollama LLM Endpoint</h3><p>To begin building your AI-powered chat application in .NET, one straightforward method is to interact directly with Ollama’s REST API. Specifically, we’ll use the /api/generate endpoint to send prompts and receive responses from the LLM.</p><p>📦 Step 1: Add Required Packages</p><p>Ensure your project includes the necessary packages for HTTP communication and dependency injection. You may need:</p><ul><li>Microsoft.AspNetCore.Mvc</li><li>Microsoft.Extensions.Http</li><li>Swashbuckle.AspNetCore (for Swagger UI testing)</li></ul><p>You can install these via NuGet Package Manager or CLI:</p><pre>dotnet add package Microsoft.Extensions.AI<br>dotnet add package OllamaSharp<br>dotnet add package Swashbuckle.AspNetCore</pre><p>Go to the Program.cs file, add the following to connect to the Ollama Server running in local on the port 11434.</p><pre>builder.Services.AddHttpClient(&quot;http.OllamaClient&quot;, client =&gt;<br>{<br>    client.BaseAddress = new Uri(&quot;http://localhost:11434/&quot;);<br>    client.DefaultRequestHeaders.Clear();<br>    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(&quot;application/json&quot;));<br>});</pre><p>🧩 Step 2: Create the Controller</p><p>Define a controller with an action method that accepts user input and returns the LLM-generated response:</p><pre>  [HttpPost(&quot;chat/api/prompt&quot;)]<br>  public async Task&lt;IActionResult&gt; Chat([FromBody] string prompt)<br>  {<br>      try<br>      {<br>          if (string.IsNullOrWhiteSpace(prompt))<br>          {<br>              return BadRequest(&quot;Prompt cannot be empty.&quot;);<br>          }<br><br>          var response = await _ollmaServie.GetChatResponseUsingEndPointAsync(prompt);<br>          return Ok(response);<br>      }<br>      catch (Exception ex)<br>      {<br>          _logger.LogError(ex, &quot;error details: {message}&quot;, ex.Message);<br>          return StatusCode(StatusCodes.Status500InternalServerError, &quot;An error occurred while processing your request.&quot;);<br>      }<br>  }</pre><p>🔹 Note: The method GetChatResponseUsingEndPointAsync is implemented in the OllamaService class. You can ignore the alternate method GetChatResponseUsingKernelAsync for now—it will be covered in a later section.</p><pre>public interface IOllamaService<br>{<br>    Task&lt;string&gt; GetChatResponseUsingEndPointAsync(string prompt);<br><br>    Task&lt;string&gt; GetChatResponseUsingKernelAsync(string prompt);<br>}<br><br>public class OllamaService : IOllamaService<br>{<br>    private readonly HttpClient _httpClient;<br>    private readonly ILogger&lt;OllamaService&gt; _logger;<br>    private readonly Kernel _kernel;<br><br>    public OllamaService(IHttpClientFactory factory, ILogger&lt;OllamaService&gt; logger, Kernel kernel)<br>    {<br>        _httpClient = factory.CreateClient(&quot;http.OllamaClient&quot;);<br>        _logger = logger;<br>        _kernel = kernel;<br>    }<br><br>    public async Task&lt;string&gt; GetChatResponseUsingEndPointAsync(string prompt)<br>    {<br>        var requestBody = new<br>        {<br>            model = &quot;llama3.2&quot;,<br>            prompt = prompt,<br>            Stream = false<br>        };<br><br>        var response = await _httpClient.PostAsJsonAsync(&quot;/api/generate&quot;, requestBody);<br>        string responseContent = await response.Content.ReadAsStringAsync();<br><br>        if (response.IsSuccessStatusCode)<br>        {<br>            _logger.LogInformation(&quot;Request successful.&quot;);<br>        }<br>        else<br>        {<br>            _logger.LogError(&quot;Request failed with status code: {StatusCode}, Response: {ResponseContent}&quot;, response.StatusCode, responseContent);<br>        }<br>        return responseContent;<br>    }<br><br>    public async Task&lt;string&gt; GetChatResponseUsingKernelAsync(string prompt)<br>    {<br>        try<br>        {<br>            /* Uncomment this section if you want to use Semantic Kernel directly (without DI) with Ollama for chat completions.<br>            Uri uri = new(&quot;http://localhost:11434&quot;); // Ensure this matches your Ollama server URL<br>            var _kernel = Kernel.CreateBuilder()<br>                .AddOllamaChatCompletion(&quot;llama3.2&quot;, uri)<br>                .Build();<br>            */<br>            var chatCompletionService = _kernel.GetRequiredService&lt;IChatCompletionService&gt;();<br>            var chatHistory = new ChatHistory();<br>            chatHistory.AddSystemMessage(&quot;You are a helpful assistant.&quot;);<br>            chatHistory.AddUserMessage(prompt);<br>            OllamaPromptExecutionSettings settings = new() { Temperature = 0.7f };<br><br>            var result = await chatCompletionService.GetChatMessageContentAsync(chatHistory, settings);<br><br>            chatHistory.AddAssistantMessage(result.Content!);<br>            return result.Content!;<br>        }<br>        catch (Exception ex)<br>        {<br>            _logger.LogError(ex, &quot;An error occurred while processing the chat request: {Message}&quot;, ex.Message);<br>            throw;<br>        }<br>    }<br>}</pre><pre>//In Program.cs, Add DI for the following service<br>builder.Services.AddTransient&lt;IOllamaService, OllamaService&gt;();</pre><p>🌐 Step 3: Understanding the /api/generate Endpoint</p><p>The Ollama endpoint /api/generate accepts a prompt in the request body and returns a structured response generated by the LLM. The response typically includes metadata such as token usage, model name, and the actual generated text.</p><p>🧪 Step 4: Testing the API</p><p>Once your application is running, you can test the chat endpoint using Swagger UI or a cURL command.</p><p>Example Prompt via Swagger:</p><pre>Explain about new Microsoft products launched recently?</pre><p>(or) Equivalent cURL Request:</p><pre>curl -X &#39;POST&#39; \<br>  &#39;https://localhost:7084/chat/api/prompt&#39; \<br>  -H &#39;accept: */*&#39; \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;&quot;Explain about new Microsoft products launched recently?&quot;&#39;</pre><p>⏳ The response may take a few moments depending on model size and system performance. Once received, you can extract and format the relevant fields for display.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wl_h-YZPsHLihSd-FFu4hg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*73e4NNfkJhn8AXo4TmGukQ.png" /></figure><p>The response typically includes metadata such as token usage, model name, and the actual generated text.</p><p>Here it is giving additional fields like Model, Created At etc.. along with actual response. You can format the response as needed for display in your frontend UI.</p><h3>🧠 Approach 2: Integrating with Semantic Kernel</h3><p>The second approach to building your AI-powered chat application involves using <strong>Semantic Kernel</strong>, a powerful orchestration framework developed by Microsoft. Semantic Kernel provides greater flexibility for working with various LLMs — including <strong>OpenAI</strong>, <strong>Azure OpenAI</strong>, and <strong>Ollama</strong> — and simplifies prompt management, memory handling, and skill composition.</p><p>📦 Step 1: Add Required NuGet Packages</p><p>To enable Semantic Kernel and Ollama integration, install the following packages:</p><pre>dotnet add package Microsoft.SemanticKernel<br>dotnet add package Microsoft.SemanticKernel.Connectors.Ollama</pre><p>These packages provide the core functionality and Ollama-specific connectors needed to interact with the LLM.</p><p>🧱 Step 2: Configure Semantic Kernel in Program.cs</p><p>Register the Ollama chat completion service and the Semantic Kernel instance for dependency injection:</p><pre>//To work with Semantic Kernel and Ollama, add following 2 statements.<br>builder.Services.AddOllamaChatCompletion(&quot;llama3.2&quot;, new Uri(&quot;http://localhost:11434&quot;));<br>builder.Services.AddTransient((sp) =&gt; { return new Kernel(sp); });</pre><ul><li>&quot;llama3.2&quot; is the model name you previously loaded into the Ollama container.</li><li>http://localhost:11434 is the default endpoint exposed by the Ollama server.</li></ul><p>💡 <strong>Note:</strong> If you prefer not to inject Kernel globally, you can instantiate it directly within your service class using the KernelBuilder.</p><pre>Uri uri = new(&quot;http://localhost:11434&quot;); // Ensure this matches your Ollama server URL<br>var _kernel = Kernel.CreateBuilder()<br>                .AddOllamaChatCompletion(&quot;llama3.2&quot;, uri)<br>                .Build();</pre><p>🧩 Step 3: Implement Chat Logic Using Semantic Kernel</p><p>Create an action method in your controller that calls the Semantic Kernel-based service method:</p><pre>[HttpPost(&quot;chat/kernel/prompt&quot;)]<br>public async Task&lt;IActionResult&gt; PostChat([FromBody] string prompt)<br>{<br>    try<br>    {<br>        if (string.IsNullOrWhiteSpace(prompt))<br>        {<br>            return BadRequest(&quot;Prompt cannot be empty.&quot;);<br>        }<br><br>        var response = await _ollmaServie.GetChatResponseUsingKernelAsync(prompt);<br>        return Ok(response);<br>    }<br>    catch (Exception ex)<br>    {<br>        _logger.LogError(ex, &quot;error details: {message}&quot;, ex.Message);<br>        return StatusCode(StatusCodes.Status500InternalServerError, &quot;An error occurred while processing your request.&quot;);<br>    }<br>}</pre><p>Now implement the GetChatResponseUsingKernelAsync method in your service class:</p><pre>public async Task&lt;string&gt; GetChatResponseUsingKernelAsync(string prompt)<br>{<br>    try<br>    {<br>        /* Uncomment this section if you want to use Semantic Kernel directly (without DI) with Ollama for chat completions.<br>        Uri uri = new(&quot;http://localhost:11434&quot;); // Ensure this matches your Ollama server URL<br>        var _kernel = Kernel.CreateBuilder()<br>            .AddOllamaChatCompletion(&quot;llama3.2&quot;, uri)<br>            .Build();<br>        */<br>        var chatCompletionService = _kernel.GetRequiredService&lt;IChatCompletionService&gt;();<br>        var chatHistory = new ChatHistory();<br>        chatHistory.AddSystemMessage(&quot;You are a helpful assistant.&quot;);<br>        chatHistory.AddUserMessage(prompt);<br>        OllamaPromptExecutionSettings settings = new() { Temperature = 0.7f }; // Adjust for creativity vs. precision<br><br>        var result = await chatCompletionService.GetChatMessageContentAsync(chatHistory, settings);<br><br>        chatHistory.AddAssistantMessage(result.Content!);<br>        return result.Content!;<br>    }<br>    catch (Exception ex)<br>    {<br>        _logger.LogError(ex, &quot;An error occurred while processing the chat request: {Message}&quot;, ex.Message);<br>        throw;<br>    }<br>}</pre><p>🔍 Key Concepts Explained</p><ul><li><strong>IChatCompletionService</strong>: Interface provided by Semantic Kernel to abstract LLM interactions.</li><li><strong>ChatHistory</strong>: Maintains the conversation context, including system, user, and assistant messages.</li><li><strong>ChatRequestSettings</strong>: Allows you to fine-tune model behavior (e.g., temperature, max tokens).</li><li><strong>System Message</strong>: Sets the assistant’s behavior or persona.</li><li><strong>User Message</strong>: Represents the prompt or query from the user.</li><li><strong>Assistant Message</strong>: Stores the model’s response for continuity in multi-turn conversations.</li></ul><p>🧪 Step 4: Testing the Semantic Kernel API</p><p>Once your application is running, test the new endpoint using Swagger or cURL:</p><p>Example Prompt:</p><pre>Explain about new Microsoft products launched recently?</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0GIAbi4WIHDs9MMo0WqHfg.png" /></figure><p>🎉 Conclusion</p><p>You’ve now explored two robust approaches for integrating Ollama LLM into a .NET chat application:</p><ol><li><strong>Direct API Integration</strong> for simplicity and control</li><li><strong>Semantic Kernel Integration</strong> for modularity and scalability</li></ol><p>Both methods offer unique advantages depending on your project’s complexity and future extensibility needs.</p><p><strong>Happy coding! 🚀</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c06b9445d93" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to run Docker commands on Ubuntu using Docker Desktop App]]></title>
            <link>https://medium.com/@nagendrak/how-to-run-docker-commands-on-ubuntu-using-docker-desktop-app-75475c5f1b1f?source=rss-dadfca5f64eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/75475c5f1b1f</guid>
            <dc:creator><![CDATA[Nagendra K]]></dc:creator>
            <pubDate>Mon, 19 Jun 2023 09:46:31 GMT</pubDate>
            <atom:updated>2023-06-19T09:47:30.411Z</atom:updated>
            <content:encoded><![CDATA[<p>This article presents a comprehensive, step-by-step guide on running Docker commands on Ubuntu using the Docker Desktop app.</p><h3>1. Install Docker Desktop</h3><p>Install Docker Desktop App using the following url : <a href="https://docs.docker.com/desktop/install/windows-install/">https://docs.docker.com/desktop/install/windows-install/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*51EEr3RrP1CJ9aIE.png" /></figure><h3>2. Install Ubuntu software</h3><p>Install Ubuntu from the following url:<br><a href="http://ubuntu%20url/">https://learn.microsoft.com/en-us/windows/wsl/install-manual#step-4---download-the-linux-kernel-update-package</a><br><br>It recommends downloading the Docker Desktop app from the App Store and selecting the latest version if available. After downloading the software, please provide your login credentials for convenience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9luYYtAOQiJapsRE.png" /></figure><h3>3. Check the Docker version in Ubuntu</h3><p>Check the installed version of Docker by using the following command:</p><pre>docker —version</pre><p>This time, the following error occurs because Docker Desktop does not recognize or enable Ubuntu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vAvcDeWESmrY81tw.png" /></figure><p>To avoid this error, Enable the WSL Integration setting for Ubuntu in docker desktop app.</p><h3>4. Enable Ubuntu integration distro option in Docker Desktop App</h3><p>Enable Ubuntu integration distro option as shown in following screenshot and click on “Apply and Restart“ button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_ddA9leWVIEUtEqH.png" /></figure><h3>5. Issue Docker command in Ubuntu</h3><p>Once Docker Desktop app is restarted and issue the Docker Version command to recognize the docker installation. It works!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/0*JgGbBsfyfYLg-qX0.png" /></figure><p>This was originally published in <a href="https://dotnetdummy.substack.com/">https://dotnetdummy.substack.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75475c5f1b1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fullstack Developer| .net core|Angular| Azure| SQL server]]></title>
            <link>https://medium.com/@nagendrak/fullstack-developer-net-core-angular-azure-sql-server-f6bb725e343e?source=rss-dadfca5f64eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6bb725e343e</guid>
            <dc:creator><![CDATA[Nagendra K]]></dc:creator>
            <pubDate>Thu, 06 Oct 2022 01:55:14 GMT</pubDate>
            <atom:updated>2022-10-06T01:55:14.677Z</atom:updated>
            <content:encoded><![CDATA[<p>Fullstack Developer| .net core|Angular| Azure| SQL server</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6bb725e343e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>