KernelMemory如何操作向量数据库

使用QdrantMemory

官方其实给出了使用案例,参考Qdrant.TestApplication的Program类就可以获取基本的操作方法,这里我主要补充的几点注意事项。
CreateIndexAsync:创建一个长度固定的Index空间,且向量长度必须大于0。
UpsertAsync:插入或更新向量记录
- 插入的向量长度必须和创建时一致
- 更新时必须带向量
GetListAsync:获取Index空间limit条向量记录
GetSimilarListAsync:带query查询参数获取Index空间limit条向量记录
1. 在官方案例中定义了一个伪造的FakeEmbeddingGenerator类,但GetSimilarListAsync方法需要注册真实有效的EmbeddingGenerator才能使用,因为会需要向量化提示词。
2. withEmbeddings:是否携带向量
3. limit:查询的数量
4. filters:筛选器

var filters=new List<MemoryFilter> 
	{
		//颜色是蓝色&&类型为邮箱
		MemoryFilters.ByTag("color","blue").ByTag("type", "email"),
		//或者颜色是红色
		MemoryFilters.ByTag("color","red"),
	}

PipelineStepHandler

在管道中可以通过IPipelineOrchestrator获取需要配置信息,例如注入的向量数据库,Embedding模型处理引擎等。

private readonly IPipelineOrchestrator _orchestrator;
public YourPipelineStepHandler(string stepName,
IPipelineOrchestrator orchestrator,
ILogger<YourPipelineStepHandler>? log = null)
{
	//当前管道名称
	this.StepName = stepName;
	//是否启动EmbeddingGeneration
	this._embeddingGenerationEnabled = orchestrator.EmbeddingGenerationEnabled;
	
	this._orchestrator = orchestrator;
	//获取当前注入的所有向量数据库
	this._memoryDbs = orchestrator.GetMemoryDbs();
	//获取当前注入的所有Embedding模型处理引擎
	this._embeddingGenerators = orchestrator.GetEmbeddingGenerators();

	if (this._embeddingGenerationEnabled)
	{
		if (this._embeddingGenerators.Count < 1)
		{
			throw new Exception("处理程序" + stepName + "未就绪,未配置嵌入生成器");
		}
	}
	this._log = log ?? DefaultLogger<YourPipelineStepHandler>.Instance;
	this._log.LogInformation("Handler '{0}' ready", stepName);
}

public async Task<(bool success, DataPipeline updatedPipeline)> InvokeAsync(DataPipeline pipeline, CancellationToken cancellationToken = default)
{
	//...操作
	var isCreateIndex=true;
	foreach (IMemoryDb client in this._memoryDbs)
	{
		if (isCreateIndex)
		{
			//创建Index空间
			await client.CreateIndexAsync(pipeline.Index, record.Vector.Length, cancellationToken).ConfigureAwait(false);
			//创建一次即可
			isCreateIndex = false;
		}
		//插入或更新向量记录
		await client.UpsertAsync(pipeline.Index,record,cancellationToken).ConfigureAwait(false);
	}
	//...操作
}
posted @ 2024-04-02 13:23  FaceMan  阅读(37)  评论(0编辑  收藏  举报