Skip to content

Add support for streaming responses from Kernel Memory #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 1, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using System.Runtime.CompilerServices;
using KernelMemory.Ecommerce.Sample.Api.Application.Configuration;
using MediatR;
using Microsoft.Extensions.Options;
using Microsoft.KernelMemory;

namespace KernelMemory.Ecommerce.Sample.Api.Application.ProductStreaming;

public sealed record ProductRagSearchStreamRequest(string SearchQuery) : IStreamRequest<string>;

public class ProductRagSearchStreamingRequestHandler(IKernelMemory memory, IOptions<ProductSearchOptions> options)
: IStreamRequestHandler<ProductRagSearchStreamRequest, string>
{
public async IAsyncEnumerable<string> Handle(
ProductRagSearchStreamRequest request,
[EnumeratorCancellation] CancellationToken cancellationToken)
{
var answerStream = memory.AskStreamingAsync(
request.SearchQuery,
minRelevance: options.Value.MinSearchResultsRelevance,
options: new SearchOptions { Stream = true },
cancellationToken: cancellationToken);

await foreach (var answer in answerStream)
{
yield return answer.Result;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using KernelMemory.Ecommerce.Sample.Api.Application.ProductStreaming;
using MediatR;

namespace KernelMemory.Ecommerce.Sample.Api.Presentation;

public class ProductRagStreamingSearch : IEndpoint
{
public void MapEndpoint(IEndpointRouteBuilder app)
{
app.MapGet("api/products/search/rag/streaming", async (
string searchQuery,
ISender sender,
HttpResponse response,
CancellationToken cancellationToken) =>
{
response.ContentType = "text/event-stream";

var request = new ProductRagSearchStreamRequest(searchQuery);

var resultStream = sender.CreateStream(request, cancellationToken);

await foreach (var result in resultStream)
{
await response.WriteAsync(result, cancellationToken);
await response.Body.FlushAsync(cancellationToken);
}
});
}
}
242 changes: 190 additions & 52 deletions src/KernelMemory.Ecommerce.Sample.Api/wwwroot/index.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Expand Down Expand Up @@ -148,6 +149,18 @@
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.json-output {
background-color: #f9f9f9;
border: 1px solid #ddd;
padding: 10px;
font-family: monospace;
white-space: pre-wrap;
max-height: 300px;
max-width: 100%;
overflow-y: auto;
margin-top: 20px;
}

.user-hints h3 {
margin-top: 0;
color: #00d1b2;
Expand All @@ -159,6 +172,7 @@
}
</style>
</head>

<body>

<header class="header">
Expand All @@ -170,8 +184,14 @@ <h1 class="title">Product Ingestion & Search</h1>
<h3>How to Use:</h3>
<ul>
<li>Upload a CSV file for product ingestion. After uploading, the product IDs will be displayed.</li>
<li>Use the Vector Search section to search for products by category or search query. Click the category buttons or enter a custom query.</li>
<li>Use RAG (Retrieval Augmented Generation Search) to get smarter, context-driven results by blending search data with generated insights.</li>
<li>
Use the Vector Search section to search for products by category or search query. Click the category
buttons or enter a custom query.
</li>
<li>
Use RAG (Retrieval Augmented Generation Search) to get smarter, context-driven results by blending
search data with generated insights.
</li>
</ul>
</section>

Expand Down Expand Up @@ -242,6 +262,29 @@ <h2 class="subtitle">RAG Search</h2>
<div id="ragSearchResult" class="mt-4"></div>
</section>

<!-- RAG Streaming Search Section -->
<section class="box" id="ragStreamingSearchSection">
<h2 class="subtitle">RAG Streaming Search</h2>
<div class="field">
<div class="control">
<input class="input" type="text" id="ragStreamingSearchQuery" placeholder="Enter search query">
</div>
</div>
<button id="ragStreamingSearchButton" class="button is-unified" onclick="ragStreamingSearch()">Search</button>

<!-- RAG Streaming Search Category Buttons -->
<div class="category-buttons">
<button class="button is-info" onclick="ragStreamingSearch('Gaming Console')">Gaming Console</button>
<button class="button is-info" onclick="ragStreamingSearch('Smartphone')">Smartphone</button>
<button class="button is-info" onclick="ragStreamingSearch('Laptop')">Laptop</button>
<button class="button is-info" onclick="ragStreamingSearch('Headphones')">Headphones</button>
</div>

<div id="ragStreamingJsonOutput" class="json-output"></div>
<div id="ragStreamingSearchResult" class="mt-4"></div>

</section>

<script>
function displayFileName() {
const fileInput = document.getElementById('csvFile');
Expand Down Expand Up @@ -306,26 +349,26 @@ <h2 class="subtitle">RAG Search</h2>
function displaySuccess(result) {
const resultContainer = document.getElementById('uploadResult');
resultContainer.innerHTML = `
<div class="notification is-success">
<button class="delete" onclick="closeNotification(this)"></button>
<strong>File uploaded successfully. Returned IDs:</strong>
<div class="id-list-container">
<ul class="id-list">
${result.map(id => `<li>${id}</li>`).join('')}
</ul>
</div>
</div>
`;
<div class="notification is-success">
<button class="delete" onclick="closeNotification(this)"></button>
<strong>File uploaded successfully. Returned IDs:</strong>
<div class="id-list-container">
<ul class="id-list">
${result.map(id => `<li>${id}</li>`).join('')}
</ul>
</div>
</div>
`;
}

function displayError(message) {
const resultContainer = document.getElementById('uploadResult');
resultContainer.innerHTML = `
<div class="notification is-danger">
<button class="delete" onclick="closeNotification(this)"></button>
<strong>Error:</strong> ${message}
</div>
`;
<div class="notification is-danger">
<button class="delete" onclick="closeNotification(this)"></button>
<strong>Error:</strong> ${message}
</div>
`;
}

function closeNotification(button) {
Expand Down Expand Up @@ -353,23 +396,23 @@ <h2 class="subtitle">RAG Search</h2>
resultContainer.innerHTML = '<div class="notification is-danger"><strong>No results found</strong></div>';
} else {
resultContainer.innerHTML = `
<div>
<p><strong>Min Relevance:</strong> ${result.minRelevance}</p>
<p><strong>Relevant Sources Count:</strong> ${result.relevantSourcesCount}</p>
<p><strong>Request Duration:</strong> ${duration.toFixed(2)} seconds</p>
</div>
<div class="products-container">
${result.products.map(product => `
<div class="product-card">
<h3>${product.name}</h3>
<p class="description">${product.description}</p>
<p class="price">${product.price} ${product.priceCurrency}</p>
<p>Supply Ability: ${product.supplyAbility}</p>
<p>Minimum Order: ${product.minimumOrder}</p>
</div>
`).join('')}
</div>
`;
<div>
<p><strong>Min Relevance:</strong> ${result.minRelevance}</p>
<p><strong>Relevant Sources Count:</strong> ${result.relevantSourcesCount}</p>
<p><strong>Request Duration:</strong> ${duration.toFixed(2)} seconds</p>
</div>
<div class="products-container">
${result.products.map(product => `
<div class="product-card">
<h3>${product.name}</h3>
<p class="description">${product.description}</p>
<p class="price">${product.price} ${product.priceCurrency}</p>
<p>Supply Ability: ${product.supplyAbility}</p>
<p>Minimum Order: ${product.minimumOrder}</p>
</div>
`).join('')}
</div>
`;
}
} catch (error) {
resultContainer.innerHTML = '<div class="notification is-danger"><strong>Error occurred while searching.</strong></div>';
Expand Down Expand Up @@ -399,23 +442,23 @@ <h3>${product.name}</h3>
resultContainer.innerHTML = '<div class="notification is-danger"><strong>No results found</strong></div>';
} else {
resultContainer.innerHTML = `
<div>
<p><strong>Min Relevance:</strong> ${result.minRelevance}</p>
<p><strong>Relevant Sources Count:</strong> ${result.relevantSourcesCount}</p>
<p><strong>Request Duration:</strong> ${duration.toFixed(2)} seconds</p>
</div>
<div class="products-container">
${result.products.map(product => `
<div class="product-card">
<h3>${product.name}</h3>
<p class="description">${product.description}</p>
<p class="price">${product.price} ${product.priceCurrency}</p>
<p>Supply Ability: ${product.supplyAbility}</p>
<p>Minimum Order: ${product.minimumOrder}</p>
</div>
`).join('')}
</div>
`;
<div>
<p><strong>Min Relevance:</strong> ${result.minRelevance}</p>
<p><strong>Relevant Sources Count:</strong> ${result.relevantSourcesCount}</p>
<p><strong>Request Duration:</strong> ${duration.toFixed(2)} seconds</p>
</div>
<div class="products-container">
${result.products.map(product => `
<div class="product-card">
<h3>${product.name}</h3>
<p class="description">${product.description}</p>
<p class="price">${product.price} ${product.priceCurrency}</p>
<p>Supply Ability: ${product.supplyAbility}</p>
<p>Minimum Order: ${product.minimumOrder}</p>
</div>
`).join('')}
</div>
`;
}
} catch (error) {
resultContainer.innerHTML = '<div class="notification is-danger"><strong>Error occurred while searching.</strong></div>';
Expand All @@ -424,6 +467,101 @@ <h3>${product.name}</h3>
unlockSectionButtons('ragSearchSection');
}
}

async function ragStreamingSearch(category) {
const query = category || document.getElementById('ragStreamingSearchQuery').value;
const searchButton = document.getElementById('ragStreamingSearchButton');
const resultContainer = document.getElementById('ragStreamingSearchResult');
const jsonOutputContainer = document.getElementById('ragStreamingJsonOutput');

resetUI(resultContainer, jsonOutputContainer, searchButton);
lockSectionButtons('ragStreamingSearchSection');

const startTime = Date.now();
let result = '';

try {
const response = await fetch(`/api/products/search/rag/streaming?searchQuery=${encodeURIComponent(query)}`);
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8");

result = await processStream(reader, decoder, jsonOutputContainer, result);

displayResults(result, resultContainer, startTime);
} catch (error) {
console.error(error);
resultContainer.innerHTML = '<div class="notification is-danger"><strong>Error occurred while searching.</strong></div>';
} finally {
searchButton.classList.remove('is-loading');
unlockSectionButtons('ragStreamingSearchSection');
}
}

function resetUI(resultContainer, jsonOutputContainer, searchButton) {
resultContainer.innerHTML = '';
jsonOutputContainer.textContent = '';
searchButton.classList.add('is-loading');
}

async function processStream(reader, decoder, jsonOutputContainer) {
let streamContent = '';

while (true) {
const { done, value } = await reader.read();
if (done) break;

const chunk = decoder.decode(value, { stream: true });
jsonOutputContainer.textContent += chunk;
streamContent += chunk;
}

return streamContent;
}

function displayResults(result, resultContainer, startTime) {
const duration = ((Date.now() - startTime) / 1000).toFixed(2);

if (result.length === 0) {
resultContainer.innerHTML = '<div class="notification is-danger"><strong>No results found</strong></div>';
return;
}

const products = JSON.parse(result);
const transformedResult = {
noResult: false,
minRelevance: 0.8,
relevantSourcesCount: products.length,
products: products.map(product => ({
id: product.Id,
name: product.Name,
description: product.Description,
price: product.Price,
priceCurrency: product.PriceCurrency,
supplyAbility: product.SupplyAbility,
minimumOrder: product.MinimumOrder
}))
};

resultContainer.innerHTML = `
<div>
<p><strong>Min Relevance:</strong> ${transformedResult.minRelevance}</p>
<p><strong>Relevant Sources Count:</strong> ${transformedResult.relevantSourcesCount}</p>
<p><strong>Request Duration:</strong> ${duration} seconds</p>
</div>
<div class="products-container">
${transformedResult.products.map(product => `
<div class="product-card">
<h3>${product.name}</h3>
<p class="description">${product.description}</p>
<p class="price">${product.price} ${product.priceCurrency}</p>
<p>Supply Ability: ${product.supplyAbility}</p>
<p>Minimum Order: ${product.minimumOrder}</p>
</div>
`).join('')}
</div>`;
}

</script>
</body>
</html>

</html>