Skip to content

Commit

Permalink
Reorganize sample code
Browse files Browse the repository at this point in the history
  • Loading branch information
dluc committed Aug 4, 2023
1 parent 0e14a22 commit 213afd7
Show file tree
Hide file tree
Showing 103 changed files with 268 additions and 33 deletions.
48 changes: 24 additions & 24 deletions SemanticMemory.sln
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@

Microsoft Visual Studio Solution File, Format Version 12.00








Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "root", "root", "{6EF76FD8-4C35-4370-8539-5DDF45357A50}"
ProjectSection(SolutionItems) = preProject
README.md = README.md
Expand All @@ -27,6 +20,24 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{0A43
samples\README.md = samples\README.md
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "001-dotnet-Serverless", "samples\001-dotnet-Serverless\001-dotnet-Serverless.csproj", "{CF55CAED-81D1-4748-8172-AE678047B760}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "002-dotnet-WebClient", "samples\002-dotnet-WebClient\002-dotnet-WebClient.csproj", "{925ADAF0-FB59-49AA-AB5C-97415EFD9D41}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "003-curl-calling-webservice", "003-curl-calling-webservice", "{CA1D9162-D4C5-490D-AAD5-7A9A23092C28}"
ProjectSection(SolutionItems) = preProject
samples\curl\test.pdf = samples\003-curl-calling-webservice\test.pdf
samples\curl\README.md = samples\003-curl-calling-webservice\README.md
samples\curl\ask-example.sh = samples\003-curl-calling-webservice\ask-example.sh
samples\curl\upload-example.sh = samples\003-curl-calling-webservice\upload-example.sh
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "004-dotnet-ServerlessCustomPipeline", "samples\004-dotnet-ServerlessCustomPipeline\004-dotnet-ServerlessCustomPipeline.csproj", "{795302A5-9006-46A6-886F-7932F6A1D8C1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "005-dotnet-ExtractTextFromDocs", "samples\005-dotnet-ExtractTextFromDocs\005-dotnet-ExtractTextFromDocs.csproj", "{375A8841-9C49-46B1-8F26-2F80C70D3A32}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "006-dotnet-CustomHandler", "samples\006-dotnet-CustomHandler\006-dotnet-CustomHandler.csproj", "{BEFD2475-7B33-4D0E-B17D-2EFC796466EC}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{CA49F1A1-C3FA-4E99-ACB3-D7FF33D47976}"
ProjectSection(SolutionItems) = preProject
tools\run-rabbitmq.sh = tools\run-rabbitmq.sh
Expand All @@ -43,23 +54,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Service", "dotnet\Service\S
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InteractiveSetup", "dotnet\InteractiveSetup\InteractiveSetup.csproj", "{2C252647-50A5-49B9-9E5F-A32C3DB22218}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dotnet-CustomHandler", "samples\dotnet-CustomHandler\dotnet-CustomHandler.csproj", "{BEFD2475-7B33-4D0E-B17D-2EFC796466EC}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dotnet-WebClient", "samples\dotnet-WebClient\dotnet-WebClient.csproj", "{925ADAF0-FB59-49AA-AB5C-97415EFD9D41}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dotnet-ExtractTextFromDocs", "samples\dotnet-ExtractTextFromDocs\dotnet-ExtractTextFromDocs.csproj", "{375A8841-9C49-46B1-8F26-2F80C70D3A32}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "curl", "curl", "{CA1D9162-D4C5-490D-AAD5-7A9A23092C28}"
ProjectSection(SolutionItems) = preProject
samples\curl\test.pdf = samples\curl\test.pdf
samples\curl\README.md = samples\curl\README.md
samples\curl\ask-example.sh = samples\curl\ask-example.sh
samples\curl\upload-example.sh = samples\curl\upload-example.sh
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dotnet-Serverless", "samples\dotnet-Serverless\dotnet-Serverless.csproj", "{CF55CAED-81D1-4748-8172-AE678047B760}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dotnet-ServerlessCustomPipeline", "samples\dotnet-ServerlessCustomPipeline\dotnet-ServerlessCustomPipeline.csproj", "{795302A5-9006-46A6-886F-7932F6A1D8C1}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "007-using-azure-cognitive-search", "samples\007-using-azure-cognitive-search\007-using-azure-cognitive-search.csproj", "{4A56D84B-1D8B-447B-9D9A-E36A2AE44806}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand All @@ -73,6 +68,7 @@ Global
{CA1D9162-D4C5-490D-AAD5-7A9A23092C28} = {0A43C65C-6007-4BB4-B3FE-8D439FC91841}
{CF55CAED-81D1-4748-8172-AE678047B760} = {0A43C65C-6007-4BB4-B3FE-8D439FC91841}
{795302A5-9006-46A6-886F-7932F6A1D8C1} = {0A43C65C-6007-4BB4-B3FE-8D439FC91841}
{4A56D84B-1D8B-447B-9D9A-E36A2AE44806} = {0A43C65C-6007-4BB4-B3FE-8D439FC91841}
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{8A9FA587-7EBA-4D43-BE47-38D798B1C74C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
Expand Down Expand Up @@ -111,5 +107,9 @@ Global
{795302A5-9006-46A6-886F-7932F6A1D8C1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{795302A5-9006-46A6-886F-7932F6A1D8C1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{795302A5-9006-46A6-886F-7932F6A1D8C1}.Release|Any CPU.Build.0 = Release|Any CPU
{4A56D84B-1D8B-447B-9D9A-E36A2AE44806}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4A56D84B-1D8B-447B-9D9A-E36A2AE44806}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4A56D84B-1D8B-447B-9D9A-E36A2AE44806}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4A56D84B-1D8B-447B-9D9A-E36A2AE44806}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
16 changes: 8 additions & 8 deletions dotnet/CoreLib/AppBuilders/DependencyInjection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,14 +122,14 @@ public static IServiceCollection UseKernel(this IServiceCollection services)

case OpenAIConfig cfg:
var textModels = new List<string>
{
"text-ada-001",
"text-babbage-001",
"text-curie-001",
"text-davinci-001",
"text-davinci-002",
"text-davinci-003",
};
{
"text-ada-001",
"text-babbage-001",
"text-curie-001",
"text-davinci-001",
"text-davinci-002",
"text-davinci-003",
};

if (textModels.Contains(cfg.Model.ToLowerInvariant()))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
namespace Microsoft.SemanticMemory.Core.MemoryStorage.AzureCognitiveSearch;

// TODO: support bring your own index schema
internal sealed class AzureCognitiveSearchMemoryRecord
public sealed class AzureCognitiveSearchMemoryRecord
{
private const string IdField = "id";
internal const string VectorField = "embedding";
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Azure.Search.Documents" Version="11.5.0-beta.3" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\dotnet\CoreLib\CoreLib.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.CodeStyle" Version="4.6.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="7.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Threading.Analyzers" Version="17.6.40">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Roslynator.CodeAnalysis.Analyzers" Version="4.4.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Roslynator.Formatting.Analyzers" Version="4.4.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

</Project>
190 changes: 190 additions & 0 deletions samples/007-using-azure-cognitive-search/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
// Copyright (c) Microsoft. All rights reserved.

// ReSharper disable InconsistentNaming

/* launchSettings.json
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"DeleteVectors": {
"commandName": "Project",
"environmentVariables": {
"SEARCH_ENDPOINT": "...",
"SEARCH_KEY": "..."
}
}
}
}
*/

using Azure;
using Azure.Search.Documents;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;
using Azure.Search.Documents.Models;
using Microsoft.SemanticKernel.AI.Embeddings;
using Microsoft.SemanticMemory.Client.Models;

public class Program
{
// Azure Search Index name
private const string IndexName = "test01";

// A Memory ID example. This value is later serialized.
private const string ExternalRecordId = "usr=user2//ppl=f05//prt=7b9bad8968804121bb9b1264104608ac";

// Size of the vectors
private const int EmbeddingSize = 3;

private static SearchIndexClient adminClient = null!;
private static readonly string Endpoint = Environment.GetEnvironmentVariable("SEARCH_ENDPOINT")!;
private static readonly string APIKey = Environment.GetEnvironmentVariable("SEARCH_KEY")!;

public static async Task Main(string[] args)
{
// Azure Cognitive Search service client
adminClient = new SearchIndexClient(new Uri(Endpoint), new AzureKeyCredential(APIKey),
new SearchClientOptions { Diagnostics = { IsTelemetryEnabled = true, ApplicationId = "SemanticMemory" } });

// Create an index (if doesn't exist)
await CreateIndexAsync(IndexName);

// Insert a record
var recordId = await InsertRecordAsync(IndexName,
ExternalRecordId,
new Dictionary<string, object> { { "text", "a b c" } },
new TagCollection(),
new Embedding<float>(new[] { 0f, 0.5f, 1 }));

// Delete the record
await DeleteRecordAsync(IndexName,
recordId,
ExternalRecordId,
new Dictionary<string, object> { { "text", "a b c" } },
new TagCollection(),
new Embedding<float>(new[] { 0f, 0.5f, 1 }));
}

// ===============================================================================================
private static async Task CreateIndexAsync(string name)
{
Console.WriteLine("\n== CREATE INDEX ==\n");

const string VectorSearchConfigName = "SemanticMemoryDefaultCosine";

var indexSchema = new SearchIndex(name)
{
Fields = new List<SearchField>(),
VectorSearch = new VectorSearch
{
AlgorithmConfigurations =
{
new HnswVectorSearchAlgorithmConfiguration(VectorSearchConfigName)
{
Parameters = new HnswParameters { Metric = VectorSearchAlgorithmMetric.Cosine }
}
}
}
};

indexSchema.Fields.Add(new SearchField("id", SearchFieldDataType.String)
{
IsKey = true,
IsFilterable = true,
IsFacetable = false,
IsSortable = false,
IsSearchable = true,
});

indexSchema.Fields.Add(new SimpleField("tags", SearchFieldDataType.Collection(SearchFieldDataType.String))
{
IsKey = false,
IsFilterable = true,
IsFacetable = false,
IsSortable = false,
});

indexSchema.Fields.Add(new SearchField("metadata", SearchFieldDataType.String)
{
IsKey = false,
IsFilterable = true,
IsFacetable = false,
IsSortable = false,
IsSearchable = true,
});

indexSchema.Fields.Add(new SearchField("embedding", SearchFieldDataType.Collection(SearchFieldDataType.Single))
{
IsKey = false,
IsFilterable = false,
IsSearchable = true,
IsFacetable = false,
IsSortable = false,
VectorSearchDimensions = EmbeddingSize,
VectorSearchConfiguration = VectorSearchConfigName,
});

try
{
await adminClient.CreateIndexAsync(indexSchema);
}
catch (RequestFailedException e) when (e.Message.Contains("already exists"))
{
Console.WriteLine("Index already exists");
}
}

// ===============================================================================================
private static async Task<string> InsertRecordAsync(string indexName,
string externalId, Dictionary<string, object> metadata, TagCollection tags, Embedding<float> embedding)
{
Console.WriteLine("\n== INSERT ==\n");
var client = adminClient.GetSearchClient(indexName);

var record = new Microsoft.SemanticMemory.Core.MemoryStorage.MemoryRecord
{
Id = externalId,
Vector = embedding,
Owner = "userAB",
Tags = tags,
Metadata = metadata
};

Microsoft.SemanticMemory.Core.MemoryStorage.AzureCognitiveSearch.AzureCognitiveSearchMemoryRecord localRecord = Microsoft.SemanticMemory.Core.MemoryStorage.AzureCognitiveSearch.AzureCognitiveSearchMemoryRecord.FromMemoryRecord(record);

Console.WriteLine($"CREATING {localRecord.Id}\n");

var response = await client.IndexDocumentsAsync(
IndexDocumentsBatch.Upload(new[] { localRecord }),
new IndexDocumentsOptions { ThrowOnAnyError = true });

Console.WriteLine("Status: " + response.Value.Results.FirstOrDefault()?.Status);
Console.WriteLine("Key: " + response.Value.Results.FirstOrDefault()?.Key);
Console.WriteLine("Succeeded: " + (response.Value.Results.FirstOrDefault()?.Succeeded ?? false ? "true" : "false"));
Console.WriteLine("ErrorMessage: " + response.Value.Results.FirstOrDefault()?.ErrorMessage);
Console.WriteLine("Status: " + response.GetRawResponse().Status);
Console.WriteLine("Content: " + response.GetRawResponse().Content);

return response.Value.Results.FirstOrDefault()?.Key ?? string.Empty;
}

// ===============================================================================================
private static async Task DeleteRecordAsync(string indexName,
string recordId, string externalId, Dictionary<string, object> metadata, TagCollection tags, Embedding<float> embedding)
{
Console.WriteLine("\n== DELETE ==\n");

var client = adminClient.GetSearchClient(indexName);

Console.WriteLine($"DELETING {recordId}\n");

Response<IndexDocumentsResult>? response = await client.DeleteDocumentsAsync("id", new List<string> { recordId });

Console.WriteLine("Status: " + response.Value.Results.FirstOrDefault()?.Status);
Console.WriteLine("Key: " + response.Value.Results.FirstOrDefault()?.Key);
Console.WriteLine("Succeeded: " + (response.Value.Results.FirstOrDefault()?.Succeeded ?? false ? "true" : "false"));
Console.WriteLine("ErrorMessage: " + response.Value.Results.FirstOrDefault()?.ErrorMessage);
Console.WriteLine("Status: " + response.GetRawResponse().Status);
Console.WriteLine("Content: " + response.GetRawResponse().Content);
}
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

0 comments on commit 213afd7

Please sign in to comment.