<?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 Denis Pashkov on Medium]]></title>
        <description><![CDATA[Stories by Denis Pashkov on Medium]]></description>
        <link>https://medium.com/@pashkovdenis?source=rss-208a25d34c45------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ko1k_MwvXzwhORxL7X3-jQ.png</url>
            <title>Stories by Denis Pashkov on Medium</title>
            <link>https://medium.com/@pashkovdenis?source=rss-208a25d34c45------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 19:43:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pashkovdenis/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[I Built a Faster Self-Organizing Collection in C# (and Benchmarked It)]]></title>
            <link>https://medium.com/@pashkovdenis/i-built-a-faster-self-organizing-collection-in-c-and-benchmarked-it-b365e30bb623?source=rss-208a25d34c45------2</link>
            <guid isPermaLink="false">https://medium.com/p/b365e30bb623</guid>
            <category><![CDATA[csharp-programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Denis Pashkov]]></dc:creator>
            <pubDate>Sun, 22 Feb 2026 12:11:05 GMT</pubDate>
            <atom:updated>2026-02-22T12:11:05.575Z</atom:updated>
            <content:encoded><![CDATA[<p>Sometimes a regular List&lt;T&gt; is not what you want.</p><p>Sometimes you want a collection that <strong>adapts to usage</strong>:</p><ul><li>frequently accessed items move toward the front,</li><li>stale items naturally lose priority,</li><li>lookups stay fast,</li><li>and the whole thing doesn’t drown the GC.</li></ul><p>That was the idea behind <strong>AdaptiveHotList</strong> — a small C# data structure experiment that turned into a surprisingly solid result.</p><p>In this post, I’ll walk through the design, why LinkedList&lt;T&gt; wasn’t enough, and what the benchmarks showed.</p><p>— -</p><h3>The problem with the obvious approach</h3><p>A common way to build a self-organizing collection is:</p><ul><li>Dictionary&lt;TKey, Node&gt; for O(1) lookup</li><li>LinkedList&lt;T&gt; for fast node reordering</li></ul><p>That works, but it comes with costs:</p><ul><li>LinkedListNode&lt;T&gt; allocations (one object per item)</li><li>pointer chasing (worse CPU cache behavior)</li><li>more GC pressure under churn</li></ul><p>It’s correct, but not ideal when you care about performance and memory locality.</p><p>— -</p><h3>The core idea</h3><p>I wanted the same behavior, but with less overhead.</p><p>So the final structure uses:</p><ul><li><strong>Dictionary&lt;TKey, int&gt;</strong> for O(1) key lookup</li><li><strong>a contiguous </strong><strong>struct array</strong> for entry storage</li><li><strong>index-based doubly linked list</strong> (Prev/Next as int)</li><li><strong>lazy weight decay</strong> (no full O(n) “cooldown” pass)</li><li><strong>local bubble-up reordering</strong> when an item is touched</li></ul><p>In other words: keep the flexibility of a linked structure, but store it in an array.</p><p>— -</p><h3>How priority works (hot vs. cold)</h3><p>Each item stores:</p><ul><li>RawWeight</li><li>LastTouchTick</li><li>Prev</li><li>Next</li></ul><p>Every operation increments a global tick counter.</p><p>Instead of decreasing the weight of every item on every operation (which would be O(n)), the collection computes <strong>effective weight</strong> lazily:</p><pre>effectiveWeight = rawWeight - decayPerTick * (currentTick - lastTouchTick)</pre><p>This means:</p><ul><li>touching an item increases its weight immediately,</li><li>untouched items naturally “cool down” over time,</li><li>and there is no expensive global decay loop.</li></ul><p>That one formula is what makes the structure practical.</p><p>— -</p><h3>Why the struct-array approach helps</h3><p>Using a struct[] instead of individual node objects gives a few wins:</p><h3>1) Better cache locality</h3><p>The data is stored contiguously, so iteration and neighboring accesses are more CPU-friendly.</p><h3>2) Lower GC pressure</h3><p>No LinkedListNode&lt;T&gt; allocations. Fewer objects means less work for the garbage collector.</p><h3>3) Cheap reordering</h3><p>Reordering is just updating a few int indexes (Prev, Next) — not reshuffling arrays or allocating nodes.</p><p>— -</p><h3>What the API looks like</h3><p>The collection is generic:</p><ul><li>AdaptiveHotList&lt;TKey, TValue&gt;</li></ul><p>Main operations:</p><ul><li>Add(key, value)</li><li>AddOrUpdate(key, value)</li><li>TryGet(key, out value) → reads and <strong>touches</strong> (raises priority)</li><li>TryPeek(key, out value) → reads without touching</li><li>Touch(key) → manually raise priority</li><li>Remove(key)</li><li>TopValues(count) → get the hottest values</li><li>Normalize() → optional re-basing for long-lived collections</li></ul><p>It behaves like a hybrid between a dictionary and a self-organizing queue.</p><p>— -</p><h3>Benchmark setup</h3><p>I benchmarked three implementations using BenchmarkDotNet:</p><p>1. <strong>AdaptiveHotList (struct-array)</strong> ← the optimized version 2. <strong>LinkedList baseline</strong> (Dictionary + LinkedList) 3. <strong>Sort-on-touch baseline</strong> (intentionally naive, re-sorts all items on each access)</p><p>I tested two scenarios:</p><ul><li><strong>TouchSkewed</strong>: a small hot set is accessed frequently (typical real-world behavior)</li><li><strong>MixedChurn</strong>: adds/removes/touches mixed together (more stressful workload)</li></ul><p>— -</p><h3>Results (the good part)</h3><h3>N = 1,000</h3><p><strong>TouchSkewed</strong></p><ul><li>Adaptive (struct-array): <strong>3.048 ms</strong></li><li>LinkedList baseline: <strong>5.165 ms</strong></li><li>Sort-on-touch: <strong>473.185 ms</strong></li></ul><p><strong>MixedChurn</strong></p><ul><li>Adaptive (struct-array): <strong>2.750 ms</strong></li><li>LinkedList baseline: <strong>5.761 ms</strong></li><li>Sort-on-touch: <strong>177.329 ms</strong></li></ul><h3>N = 10,000</h3><p><strong>TouchSkewed</strong></p><ul><li>Adaptive (struct-array): <strong>41.248 ms</strong></li><li>LinkedList baseline: <strong>94.365 ms</strong></li><li>Sort-on-touch: <strong>6,055.300 ms</strong></li></ul><p><strong>MixedChurn</strong></p><ul><li>Adaptive (struct-array): <strong>209.494 ms</strong></li><li>LinkedList baseline: <strong>396.904 ms</strong></li><li>Sort-on-touch: <strong>4,929.176 ms</strong></li></ul><p>— -</p><h3>What this means</h3><h3>1) The optimized version consistently wins</h3><p>The struct-array version was roughly <strong>1.7x to 2.3x faster</strong> than the LinkedList baseline depending on workload and size.</p><h3>2) It scales better</h3><p>The gap becomes more visible at N = 10,000, which is exactly what you want to see.</p><h3>3) It allocates less memory</h3><p>The allocation numbers were significantly lower than the LinkedList version in both workloads.</p><p>That is a big deal for long-running systems.</p><p>— -</p><h3>A quick note about benchmark noise</h3><p>The first benchmark run was executed <strong>with a debugger attached</strong>, and BenchmarkDotNet warned about multimodal distributions.</p><p>That usually means:</p><ul><li>extra noise from the debugger,</li><li>CPU frequency changes,</li><li>background system activity,</li><li>or tiered JIT warmup effects.</li></ul><p>So the absolute numbers may move a little on a clean run, but the relative result (struct-array beating LinkedList) is already clear.</p><p>— -</p><h3>Trade-offs and caveats</h3><p>This is not a magic collection. It’s optimized for a specific pattern.</p><h3>It is great for:</h3><ul><li>hot/cold prioritization</li><li>adaptive ranking</li><li>cache-like access patterns</li><li>top-item traversal</li></ul><h3>It is not ideal for:</h3><ul><li>strict ordering by exact weight at all times</li><li>frequent random access by rank (TryGetAt(rank) is O(n))</li><li>lock-free multi-threaded scenarios (it is not thread-safe by default)</li></ul><p>This is a <strong>self-organizing hot list</strong>, not a fully sorted index structure.</p><p>— -</p><h3>Where I’d use it in practice</h3><p>I originally started thinking about this for systems where “importance” changes dynamically based on access:</p><ul><li>conversation/memory systems</li><li>active tasks queues</li><li>context prioritization</li><li>local agent memory structures</li><li>recommendation-like hot item tracking</li></ul><p>Anywhere you want “recent + frequent” behavior without constant full re-sorts, this pattern is useful.</p><p>— -</p><h3>What I’d improve next</h3><p>If I continue this project, the next steps would be:</p><ul><li>ArrayPool&lt;T&gt;-backed storage to reduce resize allocations</li><li>thread-safe variant (striped locks)</li><li>specialized versions for int/long keys</li><li>allocation-free top enumeration APIs (Span / buffer-based)</li><li>cleaner benchmark config and additional workloads</li></ul><p>— -</p><h3>Final thought</h3><p>This was one of those fun engineering experiments where a simple idea (“what if the list reorganizes itself?”) turned into a very practical, high-performance structure.</p><p>And the best part is: the performance gain didn’t come from complicated algorithms — just from choosing a memory layout that fits the workload.</p><p>If you’ve built something similar (self-organizing lists, adaptive queues, weighted caches), I’d love to compare notes.</p><p>— -</p><h3>Repo</h3><p>If you publish the project on GitHub, drop the link here and add your benchmark screenshots/results.</p><p><a href="https://github.com/pashkovdenis/AdaptiveHotList">https://github.com/pashkovdenis/AdaptiveHotList</a></p><p>A README and benchmarks are already prepared for the repo structure, so it’s easy to share.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b365e30bb623" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ From JSON to Streaming: Building an OpenAI-Compatible Proxy for Ollama with .NET]]></title>
            <link>https://medium.com/@pashkovdenis/from-json-to-streaming-building-an-openai-compatible-proxy-for-ollama-with-net-2c7d1eec78cb?source=rss-208a25d34c45------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c7d1eec78cb</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Denis Pashkov]]></dc:creator>
            <pubDate>Tue, 22 Apr 2025 18:57:52 GMT</pubDate>
            <atom:updated>2025-04-22T18:57:52.957Z</atom:updated>
            <content:encoded><![CDATA[<h3>🔁 From JSON to Streaming: Building an OpenAI-Compatible Proxy for Ollama with .NET</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uGieIS5YGP6nRsa0" /></figure><blockquote><strong><em>How I debugged chunked hell, outsmarted </em></strong><strong><em>data:, and made Semantic Kernel love Ollama — by streaming it right.</em></strong></blockquote><h3>📄 Introduction</h3><p>Ollama is a fantastic tool for running local LLMs like LLaMA 3 on your own machine. It’s fast, private, and works without the cloud. But there’s a catch: it’s <strong>not 100% OpenAI API compatible</strong>, especially when it comes to streaming responses (stream: true).</p><p>Tools like <strong>Semantic Kernel</strong>, <strong>OpenAI .NET SDK</strong>, or <strong>LangChain</strong> expect text/event-stream responses in a very specific format:</p><pre>data: {&quot;delta&quot;: {&quot;content&quot;: &quot;Hello&quot;}}</pre><pre>data: {&quot;delta&quot;: {&quot;content&quot;: &quot;world&quot;}}</pre><pre>data: [DONE]</pre><p>Instead, Ollama returns <strong>raw JSON chunks</strong>, which break streaming clients.</p><p>So I built a solution: <strong>a tiny, clean .NET proxy</strong> that transforms Ollama’s output into a proper OpenAI-compatible SSE stream. And now, everything just works.</p><p>Oh, and by the way — it’s not just a proxy. It uses <strong>Akka.NET actor model under the hood</strong>, with <strong>request-level load balancing</strong> across Ollama workers. So it’s production-grade, not just a toy.</p><h3>🚫 The Problem</h3><p>Ollama’s stream: true mode returns this:</p><pre>{&quot;message&quot;: {&quot;content&quot;: &quot;How&quot;}, &quot;done&quot;: false}<br>{&quot;message&quot;: {&quot;content&quot;: &quot; can&quot;}, &quot;done&quot;: false}<br>...<br>{&quot;done&quot;: true}</pre><p>While OpenAI expects:</p><pre>data: {&quot;delta&quot;: {&quot;content&quot;: &quot;How&quot;}}</pre><pre>data: {&quot;delta&quot;: {&quot;content&quot;: &quot; can&quot;}}</pre><pre>data: [DONE]</pre><p>Trying to feed Ollama’s response into Semantic Kernel results in:</p><pre>System.Text.Json.JsonException: &#39;d&#39; is an invalid start of a value</pre><p>And yes, I spent <strong>a full day</strong> figuring out why.</p><h3>🧠 The Solution</h3><p>Instead of copying the stream directly (CopyToAsync()), we need to:</p><ol><li><strong>Read it line by line</strong></li><li><strong>Wrap each line</strong> with data: and end it with \n\n</li><li><strong>Flush</strong> after every chunk</li><li><strong>Set correct headers</strong></li></ol><p>All of this happens after the request is routed by <strong>an actor-based load balancer</strong>, which allows horizontal scaling with multiple backend Ollama nodes.</p><h3>💪 The Code</h3><pre>[Route(&quot;v1/chat/completions&quot;)]<br>[ApiController]<br>public class ProxyController : ControllerBase<br>{<br>    [HttpPost]<br>    public async Task Post()<br>    {<br>        var httpClient = _httpClientFactory.CreateClient();<br><br>using var reader = new StreamReader(Request.Body);<br>        var requestBody = await reader.ReadToEndAsync();<br>var requestMessage = new HttpRequestMessage(HttpMethod.Post, &quot;http://localhost:11434/v1/chat/completions&quot;)<br>        {<br>            Content = new StringContent(requestBody, Encoding.UTF8, &quot;application/json&quot;)<br>        };<br>        var responseMessage = await httpClient.SendAsync(<br>            requestMessage,<br>            HttpCompletionOption.ResponseHeadersRead,<br>            HttpContext.RequestAborted<br>        );<br>        Response.StatusCode = 200;<br>        Response.ContentType = &quot;text/event-stream&quot;;<br>        Response.Headers[&quot;Cache-Control&quot;] = &quot;no-cache&quot;;<br>        await Response.StartAsync();<br>        using var streamReader = new StreamReader(await responseMessage.Content.ReadAsStreamAsync());<br>        string? line;<br>        while ((line = await streamReader.ReadLineAsync()) != null)<br>        {<br>            if (!string.IsNullOrWhiteSpace(line))<br>            {<br>                var formatted = $&quot;data: {line}\n\n&quot;;<br>                var buffer = Encoding.UTF8.GetBytes(formatted);<br>                await Response.Body.WriteAsync(buffer);<br>                await Response.Body.FlushAsync();<br>            }<br>        }<br>    }<br>}</pre><h3>🧱 Architecture</h3><pre>[Client: Semantic Kernel / OpenAI SDK]<br>             |<br>        POST /v1/chat/completions<br>             ↓<br>[ Serina Proxy (.NET) ]<br>       (with Akka.NET load balancer)<br>             ↓<br>    POST → http://localhost:11434/v1/chat/completions<br>             ↓<br>       [Ollama response]<br>             ↓<br>Rewritten as `data: {...}\n\n` → streamed to client</pre><h3>🚀 Instant Results</h3><p>With the proxy in place:</p><ul><li>✅ Semantic Kernel works perfectly</li><li>✅ curl -N shows live tokens</li><li>✅ OpenAI SDK doesn’t crash</li></ul><p>And everything still runs <strong>locally</strong>, with full privacy.</p><h3>🎓 Lessons Learned</h3><ul><li>CopyToAsync() is not always safe for streaming protocols</li><li>FlushAsync() is critical for realtime updates</li><li>Streaming is fragile. One wrong \r\n and the whole LLM world burns down</li><li><strong>Mimic the spec exactly</strong> — even one byte off and you’re doomed</li></ul><h3>💼 GitHub</h3><p>Check out the full source code:</p><blockquote><a href="https://github.com/pashkovdenis/OpenAiNetBalancer"><em>https://github.com/pashkovdenis/OpenAiNetBalancer</em></a></blockquote><h3>🌟 Final Thoughts</h3><p>You don’t need to reinvent OpenAI. Sometimes you just need to <strong>stream it right</strong>.</p><p>And maybe, just maybe, a whisper of AI named Serina will help you debug your chunked encoding in the dead of night ✨</p><p><strong>Built with love by </strong><a href="https://github.com/dpashkovdenis"><strong>@dpashkov</strong></a></p><p>MIT licensed. Free to use. Free to love.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c7d1eec78cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Smarter RAG Systems with Semantic Kernel and SQL Memory]]></title>
            <link>https://medium.com/@pashkovdenis/building-smarter-rag-systems-with-semantic-kernel-and-sql-memory-4713f571f6da?source=rss-208a25d34c45------2</link>
            <guid isPermaLink="false">https://medium.com/p/4713f571f6da</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[semantic-kernel]]></category>
            <dc:creator><![CDATA[Denis Pashkov]]></dc:creator>
            <pubDate>Tue, 08 Apr 2025 17:56:06 GMT</pubDate>
            <atom:updated>2025-04-08T17:56:06.113Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9bw4PmLOTi_cxnJrFNmBkQ.png" /></figure><p>When it comes to Retrieval-Augmented Generation (RAG), there are several ways to provide external information to a chatbot.</p><p>The most straightforward method — useful for a small set of known facts — is to inject them directly into the system prompt. For example:</p><pre>###Context###<br>Username: James  <br>UserEmail: test@gmail.com</pre><p>But what happens when we have more data?</p><h3>The Vector Database Approach (And Its Limits)</h3><p>The classic approach is using a <strong>vector database</strong>. It stores information as vector embeddings, and the LLM retrieves the most relevant chunks by searching for semantic similarity.</p><p>It’s fine for basic use cases, but quickly hits bottlenecks:</p><ul><li><strong>The vector database isn’t smart</strong> — it only ranks by similarity. It doesn’t know that <em>The Matrix</em> and <em>The Lord of the Rings</em> are different genres, or even that they’re movies at all.</li><li><strong>Context blindness</strong> — retrieved chunks lack broader meaning, which can lead to irrelevant mashups or hallucinations.</li></ul><p>This is why naive RAG implementations often do more harm than good. Let’s say you want to analyze a long customer support transcript (which exceeds the model’s context window). You want to answer questions like:</p><ul><li>How long were the delays between responses?</li><li>Was the issue resolved?</li><li>Were there any unanswered questions?</li></ul><p>A vector DB alone can’t give you that level of structured insight.</p><h3>Knowledge Graphs Help, But…</h3><p>A knowledge graph can help extract entity relationships, which is useful. But it doesn’t give you full reports or behavioral analysis like:</p><ul><li>Longest delay in replies</li><li>Open vs resolved issues</li><li>Agent performance metrics</li></ul><p>Also, there’s no universal knowledge graph — you need to build it per use case. In this case: <strong>conversation analysis</strong>.</p><h3>Introducing the TagRAG Plugin for Semantic Kernel</h3><p>In this post, I’ll walk you through using the TagMemory plugin for <a href="https://github.com/microsoft/semantic-kernel">Semantic Kernel</a> to query structured data and maintain conversation history — enabling smarter and deeper insights.</p><p>Let’s build it step by step in C#.</p><h3>Step 1: Create a Console App</h3><p>First, install the required packages:</p><pre>dotnet add package Serina.TagMemory.Plugin<br>dotnet add package Serina.Semantic.Ai.Pipelines.SemanticKernel</pre><h3>Step 2: Prepare the Data</h3><p>We’ll simulate a long conversation transcript (e.g., from tech support) using a CSV file with at least 500 rows in this format:<br> <strong>date,user,message</strong></p><p>Load the data into an in-memory SQLite database:</p><pre>private async Task LoadData()<br>{<br>    string csvPath = &quot;conversations.csv&quot;;<br>foreach (var line in File.ReadLines(csvPath).Skip(1)) // skip header<br>    {<br>        var parts = line.Split(&#39;,&#39;, 3);<br>        if (parts.Length != 3) continue;<br>        var message = new Message<br>        {<br>            Date = DateTime.ParseExact(parts[0], &quot;yyyy-MM-dd HH:mm:ss&quot;, CultureInfo.InvariantCulture),<br>            User = parts[1],<br>            Content = parts[2]<br>        };<br>        db.Messages.Add(message);<br>    }<br>    db.SaveChanges();<br>}</pre><h3>Step 3: Configure the Pipeline</h3><p>Here’s how we configure the pipeline with the TagMemory plugin and Semantic Kernel:</p><pre>var plugin = new TagMemoryFactory(_serviceProvider)<br>    .WithMemoryConfig(new MemoryConfig<br>    {<br>        EngineType = EngineType.Azure,<br>        Endpoint = &quot;https://****.openai.azure.com&quot;,<br>        ModelName = &quot;gpt-4o-mini&quot;,<br>        Key = &quot;12345&quot;,<br>        EngineTypeDescription = &quot;SQLite database. Table: Messages (Id, Date, User, Context). Example query: select Id, Date, User, Context from Messages.&quot;,<br>        Examples = new List&lt;string&gt;<br>        {<br>            &quot;select * from Messages&quot;,<br>            &quot;select Id, Date, User, Context from Messages&quot;<br>        },<br>        ScanSchema = false,<br>    })<br>    .BuildPlugin();</pre><p>Then wire up the pipeline:</p><pre> PipelineBuilder.New()<br>    .SetNext(new SimpleChatStep())<br>    .WithKernel(new SemanticKernelOptions<br>    {<br>        Models = new List&lt;SemanticModelOption&gt;<br>        {<br>            new SemanticModelOption<br>            {<br>                Endpoint = &quot;https://***.openai.azure.com&quot;,<br>                Name = &quot;gpt-4o-mini&quot;,<br>                Key = &quot;123456&quot;,<br>                EngineType = 2<br>            }<br>        }<br>    })<br>    .AddFilter(new ClearTextFilter())<br>    .AddFilter(new TextChunkerFilter())<br>    .AddReducer(new PairedSlidingWindowReducer())<br>    .WithPlugin(plugin, name: &quot;memory&quot;)<br>    .AttachKernel()<br>    .WithName(&quot;SimpleChat&quot;)<br>    .Build();</pre><h3>Step 4: Running the Bot</h3><p>Now we run the loop and let the model interact with our SQL memory:</p><pre>protected override async Task ExecuteAsync(CancellationToken stoppingToken)<br>{<br>    Console.WriteLine(&quot;TagRAG Example&quot;);<br>   await LoadData();<br>    BuildPipeline();<br>    var pipe = PipelineRegistry.Get(&quot;SimpleChat&quot;);<br>    var contextId = Guid.NewGuid();<br>    var history = new List&lt;RequestMessage&gt;<br>    {<br>        new(&quot;Your task is to provide a short answer about user conversations. To get details, use the memory tool to query the database in natural language.&quot;, MessageRole.System, contextId)<br>    };<br>    while (true)<br>    {<br>        var input = Console.ReadLine();<br>        history.Add(new RequestMessage(input, MessageRole.User, Guid.NewGuid()));<br>        var context = new PipelineContext<br>        {<br>            RequestMessage = new RequestMessage(&quot;&quot;, MessageRole.User, Guid.NewGuid(), History: history.ToArray()),<br>            Response = new MessageResponse(),<br>            EnableFunctions = true,<br>        };<br>        await pipe.ExecuteStepAsync(context, default);<br>        var response = context.Response.Content;<br>        history.Add(new RequestMessage(response, MessageRole.Bot, Guid.NewGuid()));<br>        Console.WriteLine(&quot;Bot: &quot; + response);<br>    }<br>}</pre><p>Here, we instruct the model to use the memory tool to retrieve SQL data based on natural language questions.</p><h3>What You Can Analyze</h3><p>Once everything’s wired up, you can start asking questions like:</p><ul><li><strong>How many messages were exchanged?</strong></li><li><strong>Which users participated?</strong></li><li><strong>What issues were discussed?</strong></li><li><strong>Was the issue resolved?</strong></li><li><strong>What was the longest delay between replies?</strong></li></ul><p>💡 <em>The more detailed your system prompt, the more accurate your results.</em><br> Example: <em>“To determine if the issue is resolved, analyze the last N messages.”</em></p><p>The TagMemory plugin uses Polly under the hood to retry SQL calls and auto-adjust queries on failure.</p><h3>What’s Next?</h3><p>In upcoming posts, I’ll explore hybrid memory strategies — combining:</p><ul><li>SQL (structured data)</li><li>Vector DB (semantic search)</li><li>Graph DB (relationships)</li></ul><p>For example, using this open-source graph RAG project:<br> 👉 <a href="https://github.com/AIDotNet/GraphRag.Net">GraphRAG.Net GitHub</a></p><p>Example app: <a href="https://github.com/pashkovdenis/tag-rag">https://github.com/pashkovdenis/tag-rag</a></p><p>Stay tuned for deeper integration patterns!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4713f571f6da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build an AI Chat Pipeline Using Semantic Kernel and Serina Pipelines]]></title>
            <link>https://medium.com/@pashkovdenis/build-an-ai-chat-pipeline-using-semantic-kernel-and-serina-pipelines-2f24cf8b58f8?source=rss-208a25d34c45------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f24cf8b58f8</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[microsoft-semantic-kernel]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[semantic-kernel]]></category>
            <dc:creator><![CDATA[Denis Pashkov]]></dc:creator>
            <pubDate>Sun, 06 Apr 2025 19:33:33 GMT</pubDate>
            <atom:updated>2025-04-06T22:05:59.276Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eY2R8KlOZ6Bq6sW2.jpg" /></figure><p>In this article, we’ll walk through building a flexible AI pipeline using <a href="https://github.com/microsoft/semantic-kernel">Semantic Kernel</a> and the Serina.Semantic.Ai.Pipelines package. We’ll explore various pipeline configurations to power a local chat app with summarization, streaming responses, and even agent-based multi-role conversations.</p><h3>What is an AI Pipeline?</h3><p>An <strong>AI pipeline</strong> is a configurable series of steps, each containing its own logic, LLM models, plugins, filters, reducers, and more. These steps can be used to build complex processing flows for both conversational and non-conversational tasks.</p><p>By chaining and customizing these steps, you can create intelligent, context-aware bots or agents that process input in a smart and flexible way.</p><h3>What is Semantic Kernel?</h3><p><a href="https://github.com/microsoft/semantic-kernel">Semantic Kernel</a> is a lightweight, open-source SDK developed by Microsoft. It allows developers to easily integrate large language models (LLMs) like GPT, Mistral, or LLaMA into .NET applications. You can build agents, plug in your own logic, and define workflows for various AI use cases.</p><h3>What We’ll Build</h3><p>Using Semantic Kernel and the Serina.Semantic.Ai.Pipelines NuGet package, we’ll build:</p><ul><li>A <strong>simple local chat app</strong></li><li>A <strong>streaming chatbot</strong> with real-time response rendering</li><li>An <strong>agent-based conversation flow</strong> with roles like <em>Writer</em> and <em>Reviewer</em></li><li>A <strong>summarization pipeline step</strong> for summarizing the whole conversation</li></ul><p>We’ll use <strong>Ollama</strong> for local LLM models like LLaMA3 or Mixtral. So make sure you have the <a href="https://ollama.com/">Ollama server installed</a> and running locally.</p><h3>Getting Started</h3><p>First, create a new .NET Console App and add the required NuGet package:</p><pre>&lt;PackageReference Include=&quot;Serina.Semantic.Ai.Pipelines&quot; Version=&quot;1.0.0&quot; /&gt;</pre><h3>Basic Chat Example with SimpleChatStep</h3><p>Let’s begin with a simple chat example that reads user input from the console and responds using a local LLM.</p><p>We’ll use the built-in SimpleChatStep from the pipeline library.</p><pre>PipelineBuilder.New()<br>    .SetNext(new SimpleChatStep())<br>    .WithKernel(new SemanticKernelOptions<br>    {<br>        Models = new List&lt;SemanticModelOption&gt;<br>        {<br>            new SemanticModelOption<br>            {<br>                Endpoint = ollamaHost,<br>                Name = ModelName,<br>                Key = &quot;123456&quot;, // Ollama doesn&#39;t require it but the field is mandatory<br>                EngineType = 1<br>            }<br>        }<br>    }, serviceSelector: new RandomServiceSelector())<br>    .AddFilter(new ClearTextFilter())<br>    .AddFilter(new TextChunkerFilter())<br>    .AddReducer(new PairedSlidingWindowReducer())<br>    .WithModelSelectStrategy(new RandomServiceSelector())<br>    .WithName(&quot;SimpleChat&quot;)<br>    .AttachKernel()<br>    .Build()</pre><h3>Explanation:</h3><ul><li>SimpleChatStep: handles simple request/response logic.</li><li>Filters like ClearTextFilter and TextChunkerFilter clean and chunk messages.</li><li>PairedSlidingWindowReducer: reduces history by maintaining only recent relevant chunks.</li><li>.WithName(&quot;SimpleChat&quot;): adds the pipeline to a registry for easy access later.</li></ul><p>You can now retrieve the pipeline by name:</p><pre>var pipeline = PipelineRegistry.Get(&quot;SimpleChat&quot;);</pre><h3>Adding Summarization with DialogSummaryStep</h3><p>Let’s now extend the chat by summarizing the full conversation.</p><p>We’ll chain another step: DialogSummaryStep.</p><pre>PipelineBuilder.New()<br>    .SetNext(new SimpleChatStep())<br>    .WithKernel(...) // same as before<br>    .AddFilter(new ClearTextFilter())<br>    .AddFilter(new TextChunkerFilter())<br>    .AddReducer(new PairedSlidingWindowReducer())<br>    .WithModelSelectStrategy(new RandomServiceSelector())<br>    .AttachKernel()</pre><pre>    .SetNext(new DialogSummaryStep())<br>    .WithKernel(...) // another kernel instance<br>    .AttachKernel()<br>    <br>    .WithName(&quot;SimpleChat&quot;)<br>    .Build();</pre><p>Now, when you run the app, it’ll return the <strong>summary</strong> of the entire chat as part of the response.</p><h3>Streaming Chat with StreamingChatStep</h3><p>Now let’s upgrade the user experience with <strong>real-time response rendering</strong> using streaming.</p><pre>var stream = new PipelineChannelStream();</pre><pre>PipelineBuilder.New()<br>    .SetNext(new StreamingChatStep(stream))<br>    .WithKernel(...)<br>    .AddFilter(new ClearTextFilter())<br>    .AddFilter(new TextChunkerFilter())<br>    .AddReducer(new PairedSlidingWindowReducer())<br>    .AttachKernel()<br>    .WithName(&quot;StreamingChat&quot;)<br>    .Build();</pre><pre>// Reading the response:<br>await foreach (var message in stream.ReadResponses(context.Id))<br>{<br>    Console.Write(message);<br>}</pre><p>Instead of waiting for the whole message, you’ll now see tokens arriving in real time.</p><h3>Multi-Agent Chat with AgentStreamingChat</h3><p>Here’s where it gets more exciting. Let’s build a <strong>multi-agent chat system</strong> with two roles:</p><ul><li>Writer: rewrites content</li><li>Reviewer: gives feedback</li></ul><p>The conversation goes back and forth between these two until the content is approved.</p><pre>var config = new AgentChatConfiguration<br>{<br>    HistoryReducerLimit = 1,<br>    ResetOnInput = false,<br>    StrategySelectionFunction = AgentGroupChat.CreatePromptFunctionForStrategy( ... ),<br>    TerminationFunction = AgentGroupChat.CreatePromptFunctionForStrategy( ... )<br>};</pre><pre>config.AgentDefinition.Add(&quot;Reviewer&quot;, @&quot;Your responsibility is to review...&quot;);<br>config.AgentDefinition.Add(&quot;Writer&quot;, @&quot;Your responsibility is to rewrite...&quot;);</pre><pre>PipelineBuilder.New()<br>    .SetNext(new AgentStreamingChat(stream))<br>    .WithKernel(...)<br>    .AddFilter(new ClearTextFilter())<br>    .AddFilter(new TextChunkerFilter())<br>    .AddReducer(new PairedSlidingWindowReducer())<br>    .AddConfig(config)<br>    .AttachKernel()<br>    .WithName(&quot;AgentChat&quot;)<br>    .Build();</pre><p>The roles interact with each other based on the logic in the config. The bot will automatically switch between writer and reviewer based on the strategy functions.</p><p>This approach is powerful for content generation, editing workflows, or task delegation within bots.</p><h3>Recap</h3><p>Using the <strong>Serina.Semantic.Ai.Pipelines</strong> package with <strong>Semantic Kernel</strong>, we explored:</p><p>✅ Building a simple chat app<br> ✅ Adding filters and reducers<br> ✅ Implementing streaming chat<br> ✅ Creating summarization steps<br> ✅ Configuring multi-agent workflows with roles</p><p>All of this works locally with <a href="https://ollama.com/">Ollama</a> and open-source models.</p><p>References:</p><p><a href="https://github.com/pashkovdenis/serina-pipeline/tree/master">GitHub - pashkovdenis/serina-pipeline</a></p><p><a href="https://github.com/pashkovdenis/serinasamples">https://github.com/pashkovdenis/serinasamples</a></p><h3>Final Thoughts</h3><p>This pipeline architecture is <strong>flexible</strong>, <strong>composable</strong>, and <strong>powerful</strong>. You can easily add custom steps, plug-ins, cache layers, filters, or reducers to tailor your pipeline for any AI task — from chat to document processing, or even AI assistants.</p><p>Whether you’re building a bot for customer support, a writing assistant, or a research agent, this framework provides a strong foundation.</p><p>If you enjoyed this, give it a ❤️ or share it with a fellow AI developer!</p><p>Feel free to leave questions or suggestions in the comments — happy to help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f24cf8b58f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Voice Assistant in .NET C# with ChatGPT and local index]]></title>
            <link>https://medium.com/@pashkovdenis/creating-a-voice-assistant-in-net-c-with-chatgpt-and-local-index-aa93b8b5e45c?source=rss-208a25d34c45------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa93b8b5e45c</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[voice-assistant]]></category>
            <dc:creator><![CDATA[Denis Pashkov]]></dc:creator>
            <pubDate>Thu, 18 May 2023 16:43:44 GMT</pubDate>
            <atom:updated>2023-05-19T10:40:14.763Z</atom:updated>
            <content:encoded><![CDATA[<h3>Voice Assistant in .NET C# with ChatGPT</h3><p>In today’s rapidly advancing technological landscape, voice assistants have become ubiquitous, enhancing our daily lives with their ability to understand and respond to natural language queries. Behind the scenes, sophisticated conversational AI models power these voice assistants, providing accurate and context-aware responses. OpenAI’s GPT-3.5, with its deep learning capabilities, is one such powerful model that can be integrated into applications for creating voice assistants. In this article, we will explore how to leverage GPT-3.5 in a .NET C# environment to build a voice assistant that can understand and respond to user queries in natural language.</p><p>Before we get to chat GPT we need to solve two technical tasks.</p><p>1 We will need to implement hotkey spotting for the voice activation.</p><p>2 Transform voice to text and vice-versa.</p><p>For the first challenge, we can use “Picovoice” Nuget package, which contains free pre-trained models for key spottings such as “Alexa”, “Ok Google” etc.</p><p>In order to listen for the input stream we can use a combination of “Picovoice” and “PvRecorder”</p><pre>            using (Porcupine porcupine = Porcupine.FromBuiltInKeywords(apiKey, new List&lt;BuiltInKeyword&gt; { BuiltInKeyword.ALEXA }))<br>            {<br>                using PvRecorder recorder = PvRecorder.Create(deviceIndex: -1, frameLength: porcupine.FrameLength); <br><br>                recorder.Start();<br><br>                while (true)<br>                {<br>                    short[] pcm = recorder.Read();<br>                    int result = porcupine.Process(pcm);<br><br>                    if (result &gt;= 0)<br>                    {<br>                        Console.WriteLine($&quot;[{DateTime.Now.ToLongTimeString()}] Detected  &quot;);<br><br>                        Console.Beep();<br><br>                        recorder.Stop();<br><br>                        await StartListeningSentenceAsync();<br><br>                        break;<br>                    }<br><br>                    Thread.Yield();<br>                }<br>            }</pre><p>After a hot key has been spotted we can start our main routine with sentence recognition using Azure Cognetive services.</p><pre>    private async Task StartListeningSentenceAsync()<br>        {<br>            var speechConfig = SpeechConfig.FromSubscription(_settings.CognetiveKey, _settings.CognetiveRegion);<br>            <br>            using var cognitiveRecognizer = new SpeechRecognizer(speechConfig, &quot;en-us&quot;);<br><br>            var result = await cognitiveRecognizer.RecognizeOnceAsync();<br><br>            if (result.Reason == ResultReason.RecognizedSpeech)<br>            {<br>                var inputText = result.Text;<br><br>                var request = new GetAnswerRequest<br>                {<br>                     Input = inputText,<br>                     Client = Guid.Parse(_settings.DefaultUserName)<br>                }; <br><br>                var response = await _mediator.Send(request);<br><br>                speechConfig.SpeechSynthesisVoiceName = &quot;en-US-JennyNeural&quot;;<br><br>                using (var speechSynthesizer = new SpeechSynthesizer(speechConfig))<br>                {<br>                    await speechSynthesizer.SpeakTextAsync(response.Response);<br>                }<br>            }<br><br>            await KeySpottingStartAsync();<br>        }</pre><p>At this point, we have our sentence from the user transformed into text, which brings us to the fun part, finding the answer and speaking it back to the user.</p><p>We could make a call directly to the ChatGpt API using the OpenAI package but since OpenAI has a limitation (tokens) available for free usage it might be a good idea to store the answers in the local index for similar requests.</p><p>The idea behind it is to use a weighted search to find the answer, if no answer is found make a call to chatGPT Endpoint.</p><p>In this project, I used the “AuraSearch” package with a Mongo db as a local index storage which can create a new index for each new response (see GetAnswerHandler.cs).</p><p>The whole solution can be found on<strong> GitHub</strong></p><p><a href="https://github.com/pashkovdenis/.NET-Voice-assistant/tree/main">GitHub - pashkovdenis/.NET-Voice-assistant: .NET Voice assistant implementation using ChatGPT and Cognetive services</a></p><p>The quick start:</p><p>1 Setup local instance of MongoDB</p><p>2 Clone solution and edit appSettings.json</p><p>“ChatGptToken” : put your chat gpt api key</p><p>“CognetiveKey”: put your Azure cognitive services key</p><p>Default keyword “Alexa”</p><p>Clone it, Build it, Try it.</p><p>As the field of natural language processing and conversational AI continues to evolve, voice assistants have become an integral part of our daily lives. Whether it’s in customer service, smart homes, healthcare, or any other domain, voice assistants powered by ChatGPT can deliver exceptional user experiences and streamline interactions.</p><p>With the knowledge and tools at your disposal, you are now equipped to embark on your journey to create innovative voice assistants in .NET C#.</p><p>Go ahead, unleash your creativity, and bring your voice assistant ideas to life with .NET C# and ChatGPT.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa93b8b5e45c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving XOR problem using dynamic weights]]></title>
            <link>https://medium.com/@pashkovdenis/solving-xor-problem-using-dynamic-weights-ce1b56011e5f?source=rss-208a25d34c45------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce1b56011e5f</guid>
            <category><![CDATA[search]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[xor]]></category>
            <category><![CDATA[search-engines]]></category>
            <dc:creator><![CDATA[Denis Pashkov]]></dc:creator>
            <pubDate>Sun, 09 Jan 2022 22:59:58 GMT</pubDate>
            <atom:updated>2022-01-10T09:25:26.151Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p>There are many different approaches to solve the XOR problem</p><p>Some of them are based on declarative methods, some on imperative approaches like neural networks, etc…</p><p>In this short article, I would like to solve the XOR problem using a combination of both worlds with help of dynamic weights</p><p>First of all, we will define the desired result then we will use an algorithm to adjust the weights of each decision’s symbol to get the expected result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*in_Pt27iCId6X95rwW5KNA.png" /><figcaption>Define a thought with required decisions.</figcaption></figure><p>It’s very similar to a two-layer neural network but unlike NN it’s not a black box and it allows us to adjust algorithm on the fly.</p><p>Now lets define required data structures.</p><p>1 Symbol class contains two properties: word and weight</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*MYhIELfxpe-G50itCpGp4Q.png" /><figcaption>Symbol class holds word and weight</figcaption></figure><p>It will be used as the input gate. Weights are adjusted during the reinforcement phase.</p><p>2 Decision represents a single result with an answer it also contains its input “Symbols” collections and couple methods to randomize and update symbols weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*eZaiKS8ryboqcoIzmCXblg.png" /><figcaption>The decision class holds answers and attached symbols with weights.</figcaption></figure><p>3 Thought represents a logical container for a set of decisions. Also contains methods for search and decision reinforcements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XqQFDKisa9JdGAyKL0RuA.png" /><figcaption>The main thought class with reinforce method</figcaption></figure><p>Also, we’re gonna use some utility class called “MathUtils”. Its contents can be found in the repository.</p><p>Initially, we define weights as random normally distributed values.</p><p>First of all, let’s define our data set with desired answers and train the thought.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*LlIDAmjXaHreDor-Tq9x5A.png" /><figcaption>Reinforce thought until we get the expected decision Id.</figcaption></figure><p>During this step, we are going to define how many iterations we will gonna need.</p><p>Using heuristics let’s define a number of iteration as Count(Decisions) * 1300</p><p>On every iteration, we are going to calculate the error rate using desired and current result. After we calculate the delta that will be added to the weights.</p><p>Finally, we can test our trained thought with input values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*ivZQEyKN1UplpBOJfhWvOg.png" /><figcaption>Example output</figcaption></figure><p>Full source code of the example <a href="https://github.com/pashkovdenis/dynamicweightexample">https://github.com/pashkovdenis/dynamicweightexample</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce1b56011e5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>