Прием данных в векторное хранилище с помощью семантического ядра (предварительная версия)
Предупреждение
Функции хранилища векторов семантического ядра доступны в предварительной версии и улучшения, требующие критических изменений, могут по-прежнему возникать в ограниченных обстоятельствах перед выпуском.
В этой статье показано, как создать приложение для
- Извлечение текста из каждого абзаца в документе Microsoft Word
- Создание внедрения для каждого абзаца
- Upsert текст, внедрение и ссылка на исходное расположение в экземпляр Redis.
Необходимые компоненты
Для этого примера потребуется
- Модель внедрения поколения, размещенная в Azure или другом поставщике.
- Экземпляр Redis или Docker Desktop, позволяющий локально запускать Redis.
- Документ Word для анализа и загрузки. Ниже приведен zip-файл, содержащий пример документа Word, который можно скачать и использовать: vector-store-data-ingestion-input.zip.
Настройка Redis
Если у вас уже есть экземпляр Redis, его можно использовать. Если вы предпочитаете протестировать проект локально, можно легко запустить контейнер Redis с помощью docker.
docker run -d --name redis-stack -p 6379:6379 -p 8001:8001 redis/redis-stack:latest
Чтобы убедиться, что она выполняется успешно, посетите http://localhost:8001/redis-stack/browser браузер.
В остальных инструкциях предполагается, что вы используете этот контейнер с помощью приведенных выше параметров.
Создание проекта
Создайте проект и добавьте ссылки на пакеты nuget для соединителя Redis из семантического ядра, открытый xml-пакет для чтения документа word и соединителя OpenAI из семантического ядра для создания внедрения.
dotnet new console --framework net8.0 --name SKVectorIngest
cd SKVectorIngest
dotnet add package Microsoft.SemanticKernel.Connectors.AzureOpenAI
dotnet add package Microsoft.SemanticKernel.Connectors.Redis --prerelease
dotnet add package DocumentFormat.OpenXml
Добавление модели данных
Чтобы передать данные, необходимо сначала описать формат данных в базе данных. Это можно сделать, создав модель данных с атрибутами, описывающими функцию каждого свойства.
Добавьте в проект TextParagraph.cs
новый файл и добавьте в него следующую модель.
using Microsoft.Extensions.VectorData;
namespace SKVectorIngest;
internal class TextParagraph
{
/// <summary>A unique key for the text paragraph.</summary>
[VectorStoreRecordKey]
public required string Key { get; init; }
/// <summary>A uri that points at the original location of the document containing the text.</summary>
[VectorStoreRecordData]
public required string DocumentUri { get; init; }
/// <summary>The id of the paragraph from the document containing the text.</summary>
[VectorStoreRecordData]
public required string ParagraphId { get; init; }
/// <summary>The text of the paragraph.</summary>
[VectorStoreRecordData]
public required string Text { get; init; }
/// <summary>The embedding generated from the Text.</summary>
[VectorStoreRecordVector(1536)]
public ReadOnlyMemory<float> TextEmbedding { get; set; }
}
Обратите внимание, что мы передаваем значение 1536
VectorStoreRecordVectorAttribute
в . Это размер вектора и должен соответствовать размеру вектора, который создает выбранный генератор внедрения.
Совет
Дополнительные сведения о том, как инотировать модель данных и какие дополнительные параметры доступны для каждого атрибута, см . в определении модели данных.
Чтение абзацев в документе
Нам нужен код для чтения документа word и поиска текста каждого абзаца в нем.
Добавьте новый файл в проект, который вызывается DocumentReader.cs
, и добавьте следующий класс, чтобы прочитать абзацы из документа.
using System.Text;
using System.Xml;
using DocumentFormat.OpenXml.Packaging;
namespace SKVectorIngest;
internal class DocumentReader
{
public static IEnumerable<TextParagraph> ReadParagraphs(Stream documentContents, string documentUri)
{
// Open the document.
using WordprocessingDocument wordDoc = WordprocessingDocument.Open(documentContents, false);
if (wordDoc.MainDocumentPart == null)
{
yield break;
}
// Create an XmlDocument to hold the document contents and load the document contents into the XmlDocument.
XmlDocument xmlDoc = new XmlDocument();
XmlNamespaceManager nsManager = new XmlNamespaceManager(xmlDoc.NameTable);
nsManager.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
nsManager.AddNamespace("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
xmlDoc.Load(wordDoc.MainDocumentPart.GetStream());
// Select all paragraphs in the document and break if none found.
XmlNodeList? paragraphs = xmlDoc.SelectNodes("//w:p", nsManager);
if (paragraphs == null)
{
yield break;
}
// Iterate over each paragraph.
foreach (XmlNode paragraph in paragraphs)
{
// Select all text nodes in the paragraph and continue if none found.
XmlNodeList? texts = paragraph.SelectNodes(".//w:t", nsManager);
if (texts == null)
{
continue;
}
// Combine all non-empty text nodes into a single string.
var textBuilder = new StringBuilder();
foreach (XmlNode text in texts)
{
if (!string.IsNullOrWhiteSpace(text.InnerText))
{
textBuilder.Append(text.InnerText);
}
}
// Yield a new TextParagraph if the combined text is not empty.
var combinedText = textBuilder.ToString();
if (!string.IsNullOrWhiteSpace(combinedText))
{
Console.WriteLine("Found paragraph:");
Console.WriteLine(combinedText);
Console.WriteLine();
yield return new TextParagraph
{
Key = Guid.NewGuid().ToString(),
DocumentUri = documentUri,
ParagraphId = paragraph.Attributes?["w14:paraId"]?.Value ?? string.Empty,
Text = combinedText
};
}
}
}
}
Создание внедрения и отправка данных
Нам потребуется код для создания внедрения и отправки абзацев в Redis. Давайте сделаем это в отдельном классе.
Добавьте в него новый файл DataUploader.cs
и добавьте в него следующий класс.
#pragma warning disable SKEXP0001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
using Microsoft.Extensions.VectorData;
using Microsoft.SemanticKernel.Embeddings;
namespace SKVectorIngest;
internal class DataUploader(IVectorStore vectorStore, ITextEmbeddingGenerationService textEmbeddingGenerationService)
{
/// <summary>
/// Generate an embedding for each text paragraph and upload it to the specified collection.
/// </summary>
/// <param name="collectionName">The name of the collection to upload the text paragraphs to.</param>
/// <param name="textParagraphs">The text paragraphs to upload.</param>
/// <returns>An async task.</returns>
public async Task GenerateEmbeddingsAndUpload(string collectionName, IEnumerable<TextParagraph> textParagraphs)
{
var collection = vectorStore.GetCollection<string, TextParagraph>(collectionName);
await collection.CreateCollectionIfNotExistsAsync();
foreach (var paragraph in textParagraphs)
{
// Generate the text embedding.
Console.WriteLine($"Generating embedding for paragraph: {paragraph.ParagraphId}");
paragraph.TextEmbedding = await textEmbeddingGenerationService.GenerateEmbeddingAsync(paragraph.Text);
// Upload the text paragraph.
Console.WriteLine($"Upserting paragraph: {paragraph.ParagraphId}");
await collection.UpsertAsync(paragraph);
Console.WriteLine();
}
}
}
Сборка
Наконец, нам нужно объединить различные части.
В этом примере мы будем использовать контейнер внедрения зависимостей семантического ядра, но также можно использовать любой IServiceCollection
контейнер на основе.
Добавьте следующий код в Program.cs
файл для создания контейнера, зарегистрируйте векторное хранилище Redis и зарегистрируйте службу внедрения.
Обязательно замените параметры создания текста, встраивая их собственными значениями.
#pragma warning disable SKEXP0010 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
#pragma warning disable SKEXP0020 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
using Microsoft.Extensions.DependencyInjection;
using Microsoft.SemanticKernel;
using SKVectorIngest;
// Replace with your values.
var deploymentName = "text-embedding-ada-002";
var endpoint = "https://sksample.openai.azure.com/";
var apiKey = "your-api-key";
// Register Azure OpenAI text embedding generation service and Redis vector store.
var builder = Kernel.CreateBuilder()
.AddAzureOpenAITextEmbeddingGeneration(deploymentName, endpoint, apiKey)
.AddRedisVectorStore("localhost:6379");
// Register the data uploader.
builder.Services.AddSingleton<DataUploader>();
// Build the kernel and get the data uploader.
var kernel = builder.Build();
var dataUploader = kernel.Services.GetRequiredService<DataUploader>();
В качестве последнего шага мы хотим прочитать абзацы из нашего документа word и вызвать средство отправки данных для создания внедрения и отправки абзацев.
// Load the data.
var textParagraphs = DocumentReader.ReadParagraphs(
new FileStream(
"vector-store-data-ingestion-input.docx",
FileMode.Open),
"file:///c:/vector-store-data-ingestion-input.docx");
await dataUploader.GenerateEmbeddingsAndUpload(
"sk-documentation",
textParagraphs);
Просмотр данных в Redis
Перейдите в браузер стека Redis, например http://localhost:8001/redis-stack/browser , где теперь можно просмотреть отправленные абзацы. Ниже приведен пример того, что вы должны увидеть для одного из отправленных абзацев.
{
"DocumentUri" : "file:///c:/vector-store-data-ingestion-input.docx",
"ParagraphId" : "14CA7304",
"Text" : "Version 1.0+ support across C#, Python, and Java means it’s reliable, committed to non breaking changes. Any existing chat-based APIs are easily expanded to support additional modalities like voice and video.",
"TextEmbedding" : [...]
}
Скоро
Дальнейшие инструкции в ближайшее время
Скоро
Дальнейшие инструкции в ближайшее время