了解的运作原理之后,就可以开始使用Semantic Kernel来制作应用了。
Semantic Kernel将embedding的功能封装到了Memory中,用来存储上下文信息,就好像电脑的内存一样,而LLM就像是CPU一样,我们所需要做的就是从内存中取出相关的信息交给CPU处理就好了。
内存配置
使用Memory需要注册 embedding
模型,目前使用的就是 text-embedding-ada-002
。同时需要为Kernel添加MemoryStore,用于存储更多的信息,这里Semantic Kernel提供了一个 VolatileMemoryStore
,就是一个普通的内存存储的MemoryStore。
var kernel = Kernel.Builder.Configure(c => |
|
{
|
|
c.AddOpenAITextCompletionService("openai", "text-davinci-003", Environment.GetEnvironmentVariable("MY_OPEN_AI_API_KEY")); |
|
c.AddOpenAIEmbeddingGenerationService("openai", "text-embedding-ada-002", Environment.GetEnvironmentVariable("MY_OPEN_AI_API_KEY")); |
|
}) |
|
.WithMemoryStorage(new VolatileMemoryStore()) |
|
.Build(); |
信息存储
完成了基础信息的注册后,就可以往Memroy中存储信息了。
const string MemoryCollectionName = "aboutMe"; |
|
await kernel.Memory.SaveInformationAsync(MemoryCollectionName, id: "info1", text: "My name is Andrea"); |
|
await kernel.Memory.SaveInformationAsync(MemoryCollectionName, id: "info2", text: "I currently work as a tourist operator"); |
|
await kernel.Memory.SaveInformationAsync(MemoryCollectionName, id: "info3", text: "I currently live in Seattle and have been living there since 2005"); |
|
await kernel.Memory.SaveInformationAsync(MemoryCollectionName, id: "info4", text: "I visited France and Italy five times since 2015"); |
|
await kernel.Memory.SaveInformationAsync(MemoryCollectionName, id: "info5", text: "My family is from New York"); |
SaveInformationAsync
会将text的内容通过 embedding
模型转化为对应的文本向量,存放在的MemoryStore中。其中CollectionName如同数据库的表名,Id就是Id。
语义搜索
完成信息的存储之后,就可以用来语义搜索了。
直接使用Memory.SearchAsync
方法,指定对应的Collection,同时提供相应的查询问题,查询问题也会被转化为embedding,再在MemoryStore中计算查找最相似的信息。
var questions = new[] |
|
{
|
|
"what is my name?", |
|
"where do I live?", |
|
"where is my family from?", |
|