Skip to content

Commit

Permalink
Add support for filtering memories by tags in SK Plugin (#226)
Browse files Browse the repository at this point in the history
## Motivation and Context (Why the change? What's the scenario?)

Add support for filtering memories by tags in memory.search and
memory.ask methods.
  • Loading branch information
xbotter authored Jan 4, 2024
1 parent 939b2fd commit 30308f8
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion clients/dotnet/SemanticKernelPlugin/MemoryPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ namespace Microsoft.KernelMemory;
/// * memory.search
/// * memory.delete
///
/// TODO / not supported: filters on tags
/// </summary>
public class MemoryPlugin
{
Expand Down Expand Up @@ -338,12 +337,15 @@ public async Task<string> SearchAsync(
double minRelevance = 0,
[ /*SKName(LimitParam),*/ Description("Maximum number of memories to return"), DefaultValue(1)]
int limit = 1,
[ /*SKName(TagsParam),*/ Description("Memories tags to search for information"), DefaultValue(null)]
TagCollectionWrapper? tags = null,
CancellationToken cancellationToken = default)
{
SearchResult result = await this._memory
.SearchAsync(
query: query,
index: index ?? this._defaultIndex,
filter: TagsToMemoryFilter(tags ?? this._defaultRetrievalTags),
minRelevance: minRelevance,
limit: limit,
cancellationToken: cancellationToken).ConfigureAwait(false);
Expand Down Expand Up @@ -373,12 +375,15 @@ public async Task<string> AskAsync(
string? index = null,
[ /*SKName(MinRelevanceParam),*/ Description("Minimum relevance of the sources to consider"), DefaultValue(0d)]
double minRelevance = 0,
[ /*SKName(TagsParam),*/ Description("Memories tags to search for information"), DefaultValue(null)]
TagCollectionWrapper? tags = null,
ILoggerFactory? loggerFactory = null,
CancellationToken cancellationToken = default)
{
MemoryAnswer answer = await this._memory.AskAsync(
question: question,
index: index ?? this._defaultIndex,
filter: TagsToMemoryFilter(tags ?? this._defaultRetrievalTags),
minRelevance: minRelevance,
cancellationToken: cancellationToken).ConfigureAwait(false);
return answer.Result;
Expand Down Expand Up @@ -425,4 +430,21 @@ private async Task WaitForDocumentReadinessAsync(string documentId, Cancellation
// Nothing to do
}
}

private static MemoryFilter? TagsToMemoryFilter(TagCollection? tags)
{
if (tags == null)
{
return null;
}

var filters = new MemoryFilter();

foreach (var tag in tags)
{
filters.Add(tag.Key, tag.Value);
}

return filters;
}
}

0 comments on commit 30308f8

Please sign in to comment.