Fix typos and code style (#741)

* Fix filename containing a space (`ApiKeyAuthenticationHandler .cs`)
* Fix typos
* Fix code style
* Add missing rule for local constants
* Add commented code to automate code style checks. These don't work
with .NET Standard 2.0, so we'll need some extra research.
* Fix one incorrect ILogger naming
* Add some TODOs about unused code
* Fix xmldocs
This commit is contained in:
Devis Lucato
2023-05-01 17:45:35 +00:00
committed by GitHub
parent 57cbc93d05
commit e8dced1f7c
42 changed files with 208 additions and 180 deletions
+15 -2
View File
@@ -131,12 +131,17 @@ dotnet_diagnostic.CA2201.severity = warning # Exception type System.Exception is
dotnet_naming_style.pascal_case_style.capitalization = pascal_case
dotnet_naming_style.camel_case_style.capitalization = camel_case
dotnet_naming_style.static_underscored.capitalization = camel_case
dotnet_naming_style.static_underscored.required_prefix = s_
dotnet_naming_style.underscored.capitalization = camel_case
dotnet_naming_style.underscored.required_prefix = _
dotnet_naming_style.uppercase_with_underscore_separator.capitalization = all_upper
dotnet_naming_style.uppercase_with_underscore_separator.word_separator = _
dotnet_naming_style.end_in_async.required_prefix =
dotnet_naming_style.end_in_async.required_suffix = Async
dotnet_naming_style.end_in_async.capitalization = pascal_case
@@ -148,6 +153,10 @@ dotnet_naming_symbols.constant_fields.applicable_kinds = field
dotnet_naming_symbols.constant_fields.applicable_accessibilities = *
dotnet_naming_symbols.constant_fields.required_modifiers = const
dotnet_naming_symbols.local_constant.applicable_kinds = local
dotnet_naming_symbols.local_constant.applicable_accessibilities = *
dotnet_naming_symbols.local_constant.required_modifiers = const
dotnet_naming_symbols.private_static_fields.applicable_kinds = field
dotnet_naming_symbols.private_static_fields.applicable_accessibilities = private
dotnet_naming_symbols.private_static_fields.required_modifiers = static
@@ -161,9 +170,13 @@ dotnet_naming_symbols.any_async_methods.required_modifiers = async
# Rules
dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = error
dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields
dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields
dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style
dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = error
dotnet_naming_rule.local_constant_should_be_pascal_case.symbols = local_constant
dotnet_naming_rule.local_constant_should_be_pascal_case.style = pascal_case_style
dotnet_naming_rule.local_constant_should_be_pascal_case.severity = error
dotnet_naming_rule.private_static_fields_underscored.symbols = private_static_fields
dotnet_naming_rule.private_static_fields_underscored.style = static_underscored
+17 -1
View File
@@ -42,23 +42,39 @@
<!-- Symbols -->
<PackageVersion Include="Microsoft.SourceLink.GitHub" Version="1.1.1" />
<!-- Analyzers -->
<!-- TODO: Not working with .NET Standard 2.0
<PackageVersion Include="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" Version="4.1.0" />
<PackageReference Include="Microsoft.CodeDom.Providers.DotNetCompilerPlatform">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.CodeStyle" Version="4.5.0" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.CodeStyle">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
-->
<PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageVersion Include="Microsoft.VisualStudio.Threading.Analyzers" Version="17.5.22" />
<PackageReference Include="Microsoft.VisualStudio.Threading.Analyzers">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageVersion Include="xunit.analyzers" Version="1.1.0" />
<PackageReference Include="xunit.analyzers">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageVersion Include="Moq.Analyzers" Version="0.0.9" />
<PackageReference Include="Moq.Analyzers">
<PrivateAssets>all</PrivateAssets>
+3
View File
@@ -112,6 +112,7 @@
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=UI/@EntryIndexedValue">UI</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=UID/@EntryIndexedValue">UID</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=URL/@EntryIndexedValue">URL</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=XML/@EntryIndexedValue">XML</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=YAML/@EntryIndexedValue">YAML</s:String>
<s:Boolean x:Key="/Default/CodeStyle/Naming/CSharpNaming/ApplyAutoDetectedRules/@EntryValue">False</s:Boolean>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=Constants/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /&gt;</s:String>
@@ -183,6 +184,7 @@ public void It$SOMENAME$()
<s:Boolean x:Key="/Default/UserDictionary/Words/=CHATGPT/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=childrens/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Chunker/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Ctors/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=davinci/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=greaterthan/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Joinable/@EntryIndexedValue">True</s:Boolean>
@@ -192,6 +194,7 @@ public void It$SOMENAME$()
<s:Boolean x:Key="/Default/UserDictionary/Words/=myfile/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Notegen/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Qdrant/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Roundtrips/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=sandboxing/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=SK/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=SKHTTP/@EntryIndexedValue">True</s:Boolean>
@@ -32,13 +32,13 @@ public class HuggingFaceTextCompletionTests : IDisposable
public async Task ItReturnsCompletionCorrectlyAsync()
{
// Arrange
const string prompt = "This is test";
const string Prompt = "This is test";
CompleteRequestSettings requestSettings = new();
using var service = this.CreateService(HuggingFaceTestHelper.GetTestResponse("completion_test_response.json"));
// Act
var completion = await service.CompleteAsync(prompt, requestSettings);
var completion = await service.CompleteAsync(Prompt, requestSettings);
// Assert
Assert.Equal("This is test completion response", completion);
@@ -32,8 +32,8 @@ public class HuggingFaceEmbeddingGenerationTests : IDisposable
public async Task ItReturnsEmbeddingsCorrectlyAsync()
{
// Arrange
const int expectedEmbeddingCount = 1;
const int expectedVectorCount = 8;
const int ExpectedEmbeddingCount = 1;
const int ExpectedVectorCount = 8;
List<string> data = new() { "test_string_1", "test_string_2", "test_string_3" };
using var service = this.CreateService(HuggingFaceTestHelper.GetTestResponse("embeddings_test_response.json"));
@@ -43,8 +43,8 @@ public class HuggingFaceEmbeddingGenerationTests : IDisposable
// Assert
Assert.NotNull(embeddings);
Assert.Equal(expectedEmbeddingCount, embeddings.Count);
Assert.Equal(expectedVectorCount, embeddings.First().Count);
Assert.Equal(ExpectedEmbeddingCount, embeddings.Count);
Assert.Equal(ExpectedVectorCount, embeddings.First().Count);
}
/// <summary>
@@ -98,13 +98,13 @@ más pequeñas de los programas informáticos", 68)]
public void ItDoesntTimeOutForABigText()
{
// Arrange
const int oneMb = 1000 * 1000;
const int OneMb = 1000 * 1000;
var watch = new Stopwatch();
Random rnd = new();
StringBuilder text = new();
watch.Start();
var count = 0;
while (text.Length < oneMb)
while (text.Length < OneMb)
{
text.Append(GenerateWord(rnd, count++));
}
@@ -33,17 +33,17 @@ public sealed class SequentialPlannerConfig
/// <summary>
/// A list of skills to exclude from the plan creation request.
/// </summary>
public HashSet<string> ExcludedSkills { get; } = new() { };
public HashSet<string> ExcludedSkills { get; } = new();
/// <summary>
/// A list of functions to exclude from the plan creation request.
/// </summary>
public HashSet<string> ExcludedFunctions { get; } = new() { };
public HashSet<string> ExcludedFunctions { get; } = new();
/// <summary>
/// A list of functions to include in the plan creation request.
/// </summary>
public HashSet<string> IncludedFunctions { get; } = new() { };
public HashSet<string> IncludedFunctions { get; } = new();
/// <summary>
/// The maximum number of tokens to allow in a plan.
@@ -33,21 +33,21 @@ public sealed class HuggingFaceTextCompletionTests
public async Task HuggingFaceLocalAndRemoteTextCompletionAsync()
{
// Arrange
const string input = "This is test";
const string Input = "This is test";
using var huggingFaceLocal = new HuggingFaceTextCompletion(new Uri(Endpoint), Model);
using var huggingFaceRemote = new HuggingFaceTextCompletion(this.GetApiKey(), Model);
// Act
var localResponse = await huggingFaceLocal.CompleteAsync(input, new CompleteRequestSettings());
var remoteResponse = await huggingFaceRemote.CompleteAsync(input, new CompleteRequestSettings());
var localResponse = await huggingFaceLocal.CompleteAsync(Input, new CompleteRequestSettings());
var remoteResponse = await huggingFaceRemote.CompleteAsync(Input, new CompleteRequestSettings());
// Assert
Assert.NotNull(localResponse);
Assert.NotNull(remoteResponse);
Assert.StartsWith(input, localResponse, StringComparison.Ordinal);
Assert.StartsWith(input, remoteResponse, StringComparison.Ordinal);
Assert.StartsWith(Input, localResponse, StringComparison.Ordinal);
Assert.StartsWith(Input, remoteResponse, StringComparison.Ordinal);
}
private string GetApiKey()
@@ -194,7 +194,7 @@ public sealed class OpenAICompletionTests : IDisposable
$"Put the result in between <result></result> tags{lineEnding}" +
$"Input:{lineEnding}{{\"name\": \"John\", \"age\": 30}}{lineEnding}{lineEnding}Request:{lineEnding}name";
const string expectedAnswerContains = "<result>John</result>";
const string ExpectedAnswerContains = "<result>John</result>";
IKernel target = Kernel.Builder.WithLogger(this._logger).Build();
@@ -206,7 +206,7 @@ public sealed class OpenAICompletionTests : IDisposable
SKContext actual = await target.RunAsync(prompt, skill["Chat"]);
// Assert
Assert.Contains(expectedAnswerContains, actual.Result, StringComparison.OrdinalIgnoreCase);
Assert.Contains(ExpectedAnswerContains, actual.Result, StringComparison.OrdinalIgnoreCase);
}
#region internals
@@ -27,22 +27,22 @@ public sealed class PromptTemplateEngineTests : IDisposable
public async Task ItSupportsVariablesAsync()
{
// Arrange
const string input = "template tests";
const string winner = "SK";
const string template = "And the winner\n of {{$input}} \nis: {{ $winner }}!";
const string Input = "template tests";
const string Winner = "SK";
const string Template = "And the winner\n of {{$input}} \nis: {{ $winner }}!";
var kernel = Kernel.Builder.Build();
var context = kernel.CreateNewContext();
context["input"] = input;
context["winner"] = winner;
context["input"] = Input;
context["winner"] = Winner;
// Act
var result = await this._target.RenderAsync(template, context);
var result = await this._target.RenderAsync(Template, context);
// Assert
var expected = template
.Replace("{{$input}}", input, StringComparison.OrdinalIgnoreCase)
.Replace("{{ $winner }}", winner, StringComparison.OrdinalIgnoreCase);
var expected = Template
.Replace("{{$input}}", Input, StringComparison.OrdinalIgnoreCase)
.Replace("{{ $winner }}", Winner, StringComparison.OrdinalIgnoreCase);
Assert.Equal(expected, result);
}
@@ -50,31 +50,31 @@ public sealed class PromptTemplateEngineTests : IDisposable
public async Task ItSupportsValuesAsync()
{
// Arrange
const string template = "And the winner\n of {{'template\ntests'}} \nis: {{ \"SK\" }}!";
const string expected = "And the winner\n of template\ntests \nis: SK!";
const string Template = "And the winner\n of {{'template\ntests'}} \nis: {{ \"SK\" }}!";
const string Expected = "And the winner\n of template\ntests \nis: SK!";
var kernel = Kernel.Builder.Build();
var context = kernel.CreateNewContext();
// Act
var result = await this._target.RenderAsync(template, context);
var result = await this._target.RenderAsync(Template, context);
// Assert
Assert.Equal(expected, result);
Assert.Equal(Expected, result);
}
[Fact]
public async Task ItAllowsToPassVariablesToFunctionsAsync()
{
// Arrange
const string template = "== {{my.check123 $call}} ==";
const string Template = "== {{my.check123 $call}} ==";
var kernel = Kernel.Builder.Build();
kernel.ImportSkill(new MySkill(), "my");
var context = kernel.CreateNewContext();
context["call"] = "123";
// Act
var result = await this._target.RenderAsync(template, context);
var result = await this._target.RenderAsync(Template, context);
// Assert
Assert.Equal("== 123 ok ==", result);
@@ -84,13 +84,13 @@ public sealed class PromptTemplateEngineTests : IDisposable
public async Task ItAllowsToPassValuesToFunctionsAsync()
{
// Arrange
const string template = "== {{my.check123 '234'}} ==";
const string Template = "== {{my.check123 '234'}} ==";
var kernel = Kernel.Builder.Build();
kernel.ImportSkill(new MySkill(), "my");
var context = kernel.CreateNewContext();
// Act
var result = await this._target.RenderAsync(template, context);
var result = await this._target.RenderAsync(Template, context);
// Assert
Assert.Equal("== 234 != 123 ==", result);
@@ -100,8 +100,8 @@ public sealed class PromptTemplateEngineTests : IDisposable
public async Task ItAllowsToPassEscapedValues1ToFunctionsAsync()
{
// Arrange
const char ESC = '\\';
string template = "== {{my.check123 'a" + ESC + "'b'}} ==";
const char Esc = '\\';
string template = "== {{my.check123 'a" + Esc + "'b'}} ==";
var kernel = Kernel.Builder.Build();
kernel.ImportSkill(new MySkill(), "my");
var context = kernel.CreateNewContext();
@@ -117,8 +117,8 @@ public sealed class PromptTemplateEngineTests : IDisposable
public async Task ItAllowsToPassEscapedValues2ToFunctionsAsync()
{
// Arrange
const char ESC = '\\';
string template = "== {{my.check123 \"a" + ESC + "\"b\"}} ==";
const char Esc = '\\';
string template = "== {{my.check123 \"a" + Esc + "\"b\"}} ==";
var kernel = Kernel.Builder.Build();
kernel.ImportSkill(new MySkill(), "my");
var context = kernel.CreateNewContext();
@@ -19,11 +19,11 @@ public class MinHeapTests
public void ItThrowsExceptionWhenCapacityIsInvalid()
{
// Arrange
const int invalidCapacity = -1;
const int InvalidCapacity = -1;
var action = () =>
{
var minHeap = new MinHeap<int>(MinValue, invalidCapacity);
var minHeap = new MinHeap<int>(MinValue, InvalidCapacity);
};
// Act
@@ -37,36 +37,36 @@ public class MinHeapTests
public void ItAddsItemsInCorrectOrder()
{
// Arrange
const int expectedTopItem = 1;
const int expectedCount = 3;
const int ExpectedTopItem = 1;
const int ExpectedCount = 3;
// Act
var minHeap = new MinHeap<int>(MinValue) { 3, 1, 2 };
// Assert
Assert.Equal(expectedTopItem, minHeap.Top);
Assert.Equal(expectedCount, minHeap.Count);
Assert.Equal(ExpectedTopItem, minHeap.Top);
Assert.Equal(ExpectedCount, minHeap.Count);
}
[Fact]
public void ItErasesItemsCorrectly()
{
// Arrange
const int expectedCount = 0;
const int ExpectedCount = 0;
var minHeap = new MinHeap<int>(MinValue) { 3, 1, 2 };
// Act
minHeap.Erase();
// Assert
Assert.Equal(expectedCount, minHeap.Count);
Assert.Equal(ExpectedCount, minHeap.Count);
}
[Fact]
public void ItReturnsItemsOnBufferDetaching()
{
// Arrange
const int expectedHeapCount = 0;
const int ExpectedHeapCount = 0;
var minHeap = new MinHeap<int>(MinValue) { 3, 1, 2 };
@@ -75,33 +75,33 @@ public class MinHeapTests
// Assert
Assert.True(items.Length > 0);
Assert.Equal(expectedHeapCount, minHeap.Count);
Assert.Equal(ExpectedHeapCount, minHeap.Count);
}
[Fact]
public void ItThrowsExceptionOnAddingItemsAtInvalidIndex()
{
// Arrange
const int startIndex = 4;
const int StartIndex = 4;
var items = new List<int> { 3, 1, 2 };
var minHeap = new MinHeap<int>(MinValue);
var action = () => { minHeap.Add(items, startIndex); };
var action = () => { minHeap.Add(items, StartIndex); };
// Act
var exception = Assert.Throws<ArgumentOutOfRangeException>("startAt", () => action());
// Assert
Assert.Equal(startIndex, exception.ActualValue);
Assert.Equal(StartIndex, exception.ActualValue);
}
[Fact]
public void ItRemovesTopItemCorrectly()
{
// Arrange
const int expectedTopItem = 2;
const int expectedHeapCount = 2;
const int ExpectedTopItem = 2;
const int ExpectedHeapCount = 2;
var minHeap = new MinHeap<int>(MinValue) { 3, 1, 2 };
@@ -109,15 +109,15 @@ public class MinHeapTests
minHeap.RemoveTop();
// Assert
Assert.Equal(expectedTopItem, minHeap.Top);
Assert.Equal(expectedHeapCount, minHeap.Count);
Assert.Equal(ExpectedTopItem, minHeap.Top);
Assert.Equal(ExpectedHeapCount, minHeap.Count);
}
[Fact]
public void ItRemovesAllItemsCorrectly()
{
// Arrange
const int expectedHeapCount = 0;
const int ExpectedHeapCount = 0;
var minHeap = new MinHeap<int>(MinValue) { 3, 1, 2 };
@@ -129,21 +129,21 @@ public class MinHeapTests
Assert.Equal(2, items[1]);
Assert.Equal(3, items[2]);
Assert.Equal(expectedHeapCount, minHeap.Count);
Assert.Equal(ExpectedHeapCount, minHeap.Count);
}
[Fact]
public void ItEnsuresCapacityToExpectedValue()
{
// Arrange
const int expectedCapacity = 16;
const int ExpectedCapacity = 16;
var minHeap = new MinHeap<int>(MinValue);
// Act
minHeap.EnsureCapacity(expectedCapacity);
minHeap.EnsureCapacity(ExpectedCapacity);
// Assert
Assert.Equal(expectedCapacity, minHeap.Capacity);
Assert.Equal(ExpectedCapacity, minHeap.Capacity);
}
}
@@ -16,7 +16,7 @@ public class TopNCollectionTests
public void ItResetsCollectionCorrectly()
{
// Arrange
const int expectedItemsCount = 0;
const int ExpectedItemsCount = 0;
var topNCollection = this.GetTestCollection(MaxItemsCount);
@@ -24,20 +24,20 @@ public class TopNCollectionTests
topNCollection.Reset();
// Assert
Assert.Equal(expectedItemsCount, topNCollection.Count);
Assert.Equal(ExpectedItemsCount, topNCollection.Count);
}
[Fact]
public void ItKeepsMaxItemsCountWhenMoreItemsWereAdded()
{
// Arrange
const int expectedCollectionCount = 5;
const int ExpectedCollectionCount = 5;
// Act
var topNCollection = this.GetTestCollection(expectedCollectionCount);
var topNCollection = this.GetTestCollection(ExpectedCollectionCount);
// Assert
Assert.Equal(expectedCollectionCount, topNCollection.Count);
Assert.Equal(ExpectedCollectionCount, topNCollection.Count);
}
[Fact]
@@ -186,11 +186,11 @@ public class CodeBlockTests
public async Task ItInvokesFunctionCloningAllVariablesAsync()
{
// Arrange
const string FUNC = "funcName";
const string Func = "funcName";
var variables = new ContextVariables { ["input"] = "zero", ["var1"] = "uno", ["var2"] = "due" };
var context = new SKContext(variables, NullMemory.Instance, this._skills.Object, NullLogger.Instance);
var funcId = new FunctionIdBlock(FUNC);
var funcId = new FunctionIdBlock(Func);
var canary0 = string.Empty;
var canary1 = string.Empty;
@@ -209,8 +209,8 @@ public class CodeBlockTests
ctx["var2"] = "overridden";
});
this._skills.Setup(x => x.HasFunction(FUNC)).Returns(true);
this._skills.Setup(x => x.GetFunction(FUNC)).Returns(function.Object);
this._skills.Setup(x => x.HasFunction(Func)).Returns(true);
this._skills.Setup(x => x.GetFunction(Func)).Returns(function.Object);
// Act
var codeBlock = new CodeBlock(new List<Block> { funcId }, "", NullLogger.Instance);
@@ -231,14 +231,14 @@ public class CodeBlockTests
public async Task ItInvokesFunctionWithCustomVariableAsync()
{
// Arrange
const string FUNC = "funcName";
const string VAR = "varName";
const string VAR_VALUE = "varValue";
const string Func = "funcName";
const string Var = "varName";
const string VarValue = "varValue";
var variables = new ContextVariables { [VAR] = VAR_VALUE };
var variables = new ContextVariables { [Var] = VarValue };
var context = new SKContext(variables, NullMemory.Instance, this._skills.Object, NullLogger.Instance);
var funcId = new FunctionIdBlock(FUNC);
var varBlock = new VarBlock($"${VAR}");
var funcId = new FunctionIdBlock(Func);
var varBlock = new VarBlock($"${Var}");
var canary = string.Empty;
var function = new Mock<ISKFunction>();
@@ -249,28 +249,28 @@ public class CodeBlockTests
canary = ctx!["input"];
});
this._skills.Setup(x => x.HasFunction(FUNC)).Returns(true);
this._skills.Setup(x => x.GetFunction(FUNC)).Returns(function.Object);
this._skills.Setup(x => x.HasFunction(Func)).Returns(true);
this._skills.Setup(x => x.GetFunction(Func)).Returns(function.Object);
// Act
var codeBlock = new CodeBlock(new List<Block> { funcId, varBlock }, "", NullLogger.Instance);
string result = await codeBlock.RenderCodeAsync(context);
// Assert
Assert.Equal(VAR_VALUE, result);
Assert.Equal(VAR_VALUE, canary);
Assert.Equal(VarValue, result);
Assert.Equal(VarValue, canary);
}
[Fact]
public async Task ItInvokesFunctionWithCustomValueAsync()
{
// Arrange
const string FUNC = "funcName";
const string VALUE = "value";
const string Func = "funcName";
const string Value = "value";
var context = new SKContext(new ContextVariables(), NullMemory.Instance, this._skills.Object, NullLogger.Instance);
var funcId = new FunctionIdBlock(FUNC);
var valBlock = new ValBlock($"'{VALUE}'");
var funcId = new FunctionIdBlock(Func);
var valBlock = new ValBlock($"'{Value}'");
var canary = string.Empty;
var function = new Mock<ISKFunction>();
@@ -281,15 +281,15 @@ public class CodeBlockTests
canary = ctx!["input"];
});
this._skills.Setup(x => x.HasFunction(FUNC)).Returns(true);
this._skills.Setup(x => x.GetFunction(FUNC)).Returns(function.Object);
this._skills.Setup(x => x.HasFunction(Func)).Returns(true);
this._skills.Setup(x => x.GetFunction(Func)).Returns(function.Object);
// Act
var codeBlock = new CodeBlock(new List<Block> { funcId, valBlock }, "", NullLogger.Instance);
string result = await codeBlock.RenderCodeAsync(context);
// Assert
Assert.Equal(VALUE, result);
Assert.Equal(VALUE, canary);
Assert.Equal(Value, result);
Assert.Equal(Value, canary);
}
}
@@ -12,14 +12,14 @@ public sealed class TextChunkerTests
[Fact]
public void CanSplitPlainTextLines()
{
const string input = "This is a test of the emergency broadcast system. This is only a test.";
const string Input = "This is a test of the emergency broadcast system. This is only a test.";
var expected = new[]
{
"This is a test of the emergency broadcast system.",
"This is only a test."
};
var result = TextChunker.SplitPlainTextLines(input, 15);
var result = TextChunker.SplitPlainTextLines(Input, 15);
Assert.Equal(expected, result);
}
@@ -68,14 +68,14 @@ public sealed class TextChunkerTests
[Fact]
public void CanSplitMarkDownLines()
{
const string input = "This is a test of the emergency broadcast system. This is only a test.";
const string Input = "This is a test of the emergency broadcast system. This is only a test.";
var expected = new[]
{
"This is a test of the emergency broadcast system.",
"This is only a test."
};
var result = TextChunker.SplitMarkDownLines(input, 15);
var result = TextChunker.SplitMarkDownLines(Input, 15);
Assert.Equal(expected, result);
}
@@ -20,8 +20,8 @@ Install this package manually only if you are selecting individual Semantic Kern
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.SemanticKernel.Planning.ActionPlanner" PublicKey="$(StongNamePublicKey)"/>
<InternalsVisibleTo Include="Microsoft.SemanticKernel.Planning.SequentialPlanner" PublicKey="$(StongNamePublicKey)"/>
<InternalsVisibleTo Include="Microsoft.SemanticKernel.Planning.ActionPlanner" PublicKey="$(StongNamePublicKey)"/>
<InternalsVisibleTo Include="Microsoft.SemanticKernel.Planning.SequentialPlanner" PublicKey="$(StongNamePublicKey)"/>
<InternalsVisibleTo Include="Microsoft.SemanticKernel.Connectors.AI.OpenAI" PublicKey="$(StongNamePublicKey)"/>
<InternalsVisibleTo Include="Microsoft.SemanticKernel.Skills.OpenAPI" PublicKey="$(StongNamePublicKey)"/>
<InternalsVisibleTo Include="SemanticKernel.UnitTests" PublicKey="$(StongNamePublicKey)"/>
@@ -61,8 +61,8 @@ public static class ImportSemanticSkillFromDirectoryExtension
public static IDictionary<string, ISKFunction> ImportSemanticSkillFromDirectory(
this IKernel kernel, string parentDirectory, params string[] skillDirectoryNames)
{
const string CONFIG_FILE = "config.json";
const string PROMPT_FILE = "skprompt.txt";
const string ConfigFile = "config.json";
const string PromptFile = "skprompt.txt";
var skill = new Dictionary<string, ISKFunction>();
@@ -78,12 +78,12 @@ public static class ImportSemanticSkillFromDirectoryExtension
var functionName = Path.GetFileName(dir);
// Continue only if prompt template exists
var promptPath = Path.Combine(dir, PROMPT_FILE);
var promptPath = Path.Combine(dir, PromptFile);
if (!File.Exists(promptPath)) { continue; }
// Load prompt configuration. Note: the configuration is optional.
var config = new PromptTemplateConfig();
var configPath = Path.Combine(dir, CONFIG_FILE);
var configPath = Path.Combine(dir, ConfigFile);
if (File.Exists(configPath))
{
config = PromptTemplateConfig.FromJson(File.ReadAllText(configPath));
@@ -115,14 +115,14 @@ public sealed class SKFunction : ISKFunction, IDisposable
}
catch (AIException ex)
{
const string message = "Something went wrong while rendering the semantic function or while executing the text completion. Function: {0}.{1}. Error: {2}. Details: {3}";
log?.LogError(ex, message, skillName, functionName, ex.Message, ex.Detail);
const string Message = "Something went wrong while rendering the semantic function or while executing the text completion. Function: {0}.{1}. Error: {2}. Details: {3}";
log?.LogError(ex, Message, skillName, functionName, ex.Message, ex.Detail);
context.Fail(ex.Message, ex);
}
catch (Exception ex) when (!ex.IsCriticalException())
{
const string message = "Something went wrong while rendering the semantic function or while executing the text completion. Function: {0}.{1}. Error: {2}";
log?.LogError(ex, message, skillName, functionName, ex.Message);
const string Message = "Something went wrong while rendering the semantic function or while executing the text completion. Function: {0}.{1}. Error: {2}";
log?.LogError(ex, Message, skillName, functionName, ex.Message);
context.Fail(ex.Message, ex);
}
@@ -68,9 +68,9 @@ internal sealed class VarBlock : Block, ITextRendering
if (string.IsNullOrEmpty(this.Name))
{
const string errMsg = "Variable rendering failed, the variable name is empty";
this.Log.LogError(errMsg);
throw new TemplateException(TemplateException.ErrorCodes.SyntaxError, errMsg);
const string ErrMsg = "Variable rendering failed, the variable name is empty";
this.Log.LogError(ErrMsg);
throw new TemplateException(TemplateException.ErrorCodes.SyntaxError, ErrMsg);
}
var exists = variables.Get(this.Name, out string value);
@@ -79,9 +79,9 @@ public class PromptTemplateEngine : IPromptTemplateEngine
break;
default:
const string error = "Unexpected block type, the block doesn't have a rendering method";
this._log.LogError(error);
throw new TemplateException(TemplateException.ErrorCodes.UnexpectedBlockType, error);
const string Error = "Unexpected block type, the block doesn't have a rendering method";
this._log.LogError(Error);
throw new TemplateException(TemplateException.ErrorCodes.UnexpectedBlockType, Error);
}
}
@@ -52,9 +52,9 @@ internal sealed class TemplateTokenizer
public IList<Block> Tokenize(string? text)
{
// An empty block consists of 4 chars: "{{}}"
const int EMPTY_CODE_BLOCK_LENGTH = 4;
const int EmptyCodeBlockLength = 4;
// A block shorter than 5 chars is either empty or invalid, e.g. "{{ }}" and "{{$}}"
const int MIN_CODE_BLOCK_LENGTH = EMPTY_CODE_BLOCK_LENGTH + 1;
const int MinCodeBlockLength = EmptyCodeBlockLength + 1;
// Render NULL to ""
if (text.IsNullOrEmpty())
@@ -63,7 +63,7 @@ internal sealed class TemplateTokenizer
}
// If the template is "empty" return the content as a text block
if (text.Length < MIN_CODE_BLOCK_LENGTH)
if (text.Length < MinCodeBlockLength)
{
return new List<Block> { new TextBlock(text, this._log) };
}
@@ -141,7 +141,7 @@ internal sealed class TemplateTokenizer
// Remove "{{" and "}}" delimiters and trim empty chars
var contentWithoutDelimiters = contentWithDelimiters
.Substring(2, contentWithDelimiters.Length - EMPTY_CODE_BLOCK_LENGTH)
.Substring(2, contentWithDelimiters.Length - EmptyCodeBlockLength)
.Trim();
if (contentWithoutDelimiters.Length == 0)
@@ -87,9 +87,9 @@ public class CloudDriveSkill
public async Task<string> CreateLinkAsync(string filePath, SKContext context)
{
this._logger.LogDebug("Creating link for '{0}'", filePath);
const string type = "view"; // TODO expose this as an SK variable
const string scope = "anonymous"; // TODO expose this as an SK variable
const string Type = "view"; // TODO expose this as an SK variable
const string Scope = "anonymous"; // TODO expose this as an SK variable
return await this._connector.CreateShareLinkAsync(filePath, type, scope, context.CancellationToken).ConfigureAwait(false);
return await this._connector.CreateShareLinkAsync(filePath, Type, Scope, context.CancellationToken).ConfigureAwait(false);
}
}
@@ -49,14 +49,14 @@ public class LocalUserMSALCredentialManager
public static async Task<LocalUserMSALCredentialManager> CreateAsync()
{
// Initialize persistent storage for the token cache
const string cacheSchemaName = "com.microsoft.semantickernel.tokencache";
const string CacheSchemaName = "com.microsoft.semantickernel.tokencache";
var storage = new StorageCreationPropertiesBuilder("sk.msal.cache", MsalCacheHelper.UserRootDirectory)
.WithMacKeyChain(
serviceName: $"{cacheSchemaName}.service",
accountName: $"{cacheSchemaName}.account")
serviceName: $"{CacheSchemaName}.service",
accountName: $"{CacheSchemaName}.account")
.WithLinuxKeyring(
schemaName: cacheSchemaName,
schemaName: CacheSchemaName,
collection: MsalCacheHelper.LinuxKeyRingDefaultCollection,
secretLabel: "MSAL token cache for Semantic Kernel skills.",
attribute1: new KeyValuePair<string, string>("Version", "1"),
@@ -39,21 +39,18 @@ public class OneDriveConnector : ICloudDriveConnector
.Request().GetAsync(cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc/>
/// <exception cref="NotImplementedException">This method is not yet supported for <see cref="OneDriveConnector"/>.</exception>
public Task<Stream> GetWriteableFileStreamAsync(string filePath, CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
/// <inheritdoc/>
/// <exception cref="NotImplementedException">This method is not yet supported for <see cref="OneDriveConnector"/>.</exception>
public Task<Stream> CreateFileAsync(string filePath, CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
/// <inheritdoc/>
public async Task<bool> FileExistsAsync(string filePath, CancellationToken cancellationToken = default)
{
Ensure.NotNullOrWhitespace(filePath, nameof(filePath));
@@ -134,14 +134,14 @@ public static class KernelChatGptPluginExtensions
AuthenticateRequestAsyncCallback? authCallback = null,
CancellationToken cancellationToken = default)
{
const string CHATGPT_PLUGIN_FILE = "ai-plugin.json";
const string ChatGptPluginFile = "ai-plugin.json";
Verify.ValidSkillName(skillDirectoryName);
var skillDir = Path.Combine(parentDirectory, skillDirectoryName);
Verify.DirectoryExists(skillDir);
var chatGptPluginPath = Path.Combine(skillDir, CHATGPT_PLUGIN_FILE);
var chatGptPluginPath = Path.Combine(skillDir, ChatGptPluginFile);
if (!File.Exists(chatGptPluginPath))
{
throw new FileNotFoundException($"No ChatGPT plugin for the specified path - {chatGptPluginPath} is found");
@@ -129,14 +129,14 @@ public static class KernelOpenApiExtensions
AuthenticateRequestAsyncCallback? authCallback = null,
CancellationToken cancellationToken = default)
{
const string OPENAPI_FILE = "openapi.json";
const string OpenAPIFile = "openapi.json";
Verify.ValidSkillName(skillDirectoryName);
var skillDir = Path.Combine(parentDirectory, skillDirectoryName);
Verify.DirectoryExists(skillDir);
var openApiDocumentPath = Path.Combine(skillDir, OPENAPI_FILE);
var openApiDocumentPath = Path.Combine(skillDir, OpenAPIFile);
if (!File.Exists(openApiDocumentPath))
{
throw new FileNotFoundException($"No OpenApi document for the specified path - {openApiDocumentPath} is found.");
@@ -16,6 +16,7 @@ public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthentic
public const string AuthenticationScheme = "ApiKey";
public const string ApiKeyHeaderName = "x-api-key";
// TODO: not used?
private readonly IOptionsMonitor<ApiKeyAuthenticationSchemeOptions> _options;
/// <summary>
@@ -35,17 +35,17 @@ public class PlannerOptions
/// <summary>
/// A list of skills to exclude from the plan creation request.
/// </summary>
public HashSet<string> ExcludedSkills { get; set; } = new() { };
public HashSet<string> ExcludedSkills { get; set; } = new();
/// <summary>
/// A list of functions to exclude from the plan creation request.
/// </summary>
public HashSet<string> ExcludedFunctions { get; set; } = new() { };
public HashSet<string> ExcludedFunctions { get; set; } = new();
/// <summary>
/// A list of functions to include in the plan creation request.
/// </summary>
public HashSet<string> IncludedFunctions { get; set; } = new() { };
public HashSet<string> IncludedFunctions { get; set; } = new();
/// <summary>
/// The maximum number of tokens to allow in a plan.
@@ -8,7 +8,6 @@ using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Memory;
using SemanticKernel.Service.Config;
using SemanticKernel.Service.Model;
using SemanticKernel.Service.Skills;
using SemanticKernel.Service.Storage;
namespace SemanticKernel.Service.Controllers;
@@ -16,7 +15,7 @@ namespace SemanticKernel.Service.Controllers;
[ApiController]
public class BotController : ControllerBase
{
private readonly ILogger<SemanticKernelController> _logger;
private readonly ILogger<BotController> _logger;
private readonly IMemoryStore _memoryStore;
private readonly ChatSessionRepository _chatRepository;
private readonly ChatMessageRepository _chatMessageRepository;
@@ -32,7 +31,7 @@ public class BotController : ControllerBase
IMemoryStore memoryStore,
ChatSessionRepository chatRepository,
ChatMessageRepository chatMessageRepository,
ILogger<SemanticKernelController> logger)
ILogger<BotController> logger)
{
this._logger = logger;
this._memoryStore = memoryStore;
@@ -177,7 +176,7 @@ public class BotController : ControllerBase
private async Task<Bot> CreateBotAsync(
IKernel kernel,
ChatSessionRepository chatRepository,
ChatMessageRepository chatMessageRepository,
ChatMessageRepository chatMessageRepository, // TODO: unused
BotSchemaOptions botSchemaOptions,
AIServiceOptions embeddingOptions,
Guid chatId)
@@ -63,7 +63,7 @@ public class ChatHistoryController : ControllerBase
var initialBotMessage = this._promptSettings.InitialBotMessage;
await this.SaveResponseAsync(initialBotMessage, newChat.Id);
this._logger.LogDebug("Created chat session with id {0} for user {1}.", newChat.Id, userId);
this._logger.LogDebug("Created chat session with id {0} for user {1}", newChat.Id, userId);
return this.CreatedAtAction(nameof(this.GetChatSessionByIdAsync), new { chatId = newChat.Id }, newChat);
}
@@ -91,7 +91,7 @@ public class ChatHistoryController : ControllerBase
/// <summary>
/// Get all chat sessions associated with a user. Return an empty list if no chats are found.
/// The regex pattern that is used to match the user id will match the following format:
/// - 2 period separated groups of one or more hyphen-delimitated alphanumeric strings.
/// - 2 period separated groups of one or more hyphen-delimited alphanumeric strings.
/// The pattern matches two GUIDs in canonical textual representation separated by a period.
/// </summary>
/// <param name="userId">The user id.</param>
@@ -160,9 +160,9 @@ public class ChatHistoryController : ControllerBase
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> EditChatSessionAsync([FromBody] ChatSession chatParameters)
{
var chatId = chatParameters.Id;
string chatId = chatParameters.Id;
var chat = await this._chatSessionRepository.FindByIdAsync(chatId.ToString());
ChatSession? chat = await this._chatSessionRepository.FindByIdAsync(chatId);
if (chat == null)
{
return this.NotFound($"Chat of id {chatId} not found.");
@@ -35,9 +35,9 @@ public class DocumentImportController : ControllerBase
Pdf,
};
private readonly IServiceProvider _serviceProvider;
private readonly IServiceProvider _serviceProvider; // TODO: unused
private readonly ILogger<DocumentImportController> _logger;
private readonly PromptSettings _promptSettings;
private readonly PromptSettings _promptSettings; // TODO: unused
private readonly DocumentMemoryOptions _options;
/// <summary>
@@ -2,7 +2,6 @@
using Microsoft.SemanticKernel.Memory;
using SemanticKernel.Service.Config;
using SemanticKernel.Service.Skills;
namespace SemanticKernel.Service.Model;
@@ -387,7 +387,7 @@ public class ChatSkill
catch (JsonException)
{
// Expected if not valid JSON.
this._logger.LogDebug("Unable to extract JSON from planner response. It is likely not JSON formatted.");
this._logger.LogDebug("Unable to extract JSON from planner response, it is likely not JSON formatted");
}
json = string.Empty;
@@ -71,9 +71,9 @@ public class FileCompressionSkill
if (!context.Variables.Get(Parameters.DestinationFilePath, out string destinationFilePath))
{
const string errorMessage = $"Missing context variable {Parameters.DestinationFilePath} in {nameof(this.CompressFileAsync)}";
this._logger.LogError(errorMessage);
context.Fail(errorMessage);
const string ErrorMessage = $"Missing context variable {Parameters.DestinationFilePath} in {nameof(this.CompressFileAsync)}";
this._logger.LogError(ErrorMessage);
context.Fail(ErrorMessage);
return null;
}
@@ -101,9 +101,9 @@ public class FileCompressionSkill
if (!context.Variables.Get(Parameters.DestinationFilePath, out string destinationFilePath))
{
const string errorMessage = $"Missing context variable {Parameters.DestinationFilePath} in {nameof(this.CompressDirectoryAsync)}";
this._logger.LogError(errorMessage);
context.Fail(errorMessage);
const string ErrorMessage = $"Missing context variable {Parameters.DestinationFilePath} in {nameof(this.CompressDirectoryAsync)}";
this._logger.LogError(ErrorMessage);
context.Fail(ErrorMessage);
return null;
}
@@ -131,9 +131,9 @@ public class FileCompressionSkill
if (!context.Variables.Get(Parameters.DestinationDirectoryPath, out string destinationDirectoryPath))
{
const string errorMessage = $"Missing context variable {Parameters.DestinationDirectoryPath} in {nameof(this.DecompressFileAsync)}";
this._logger.LogError(errorMessage);
context.Fail(errorMessage);
const string ErrorMessage = $"Missing context variable {Parameters.DestinationDirectoryPath} in {nameof(this.DecompressFileAsync)}";
this._logger.LogError(ErrorMessage);
context.Fail(ErrorMessage);
return null;
}
@@ -13,8 +13,8 @@ internal static class RepoFiles
/// <returns>The full path to samples/skills</returns>
internal static string SampleSkillsPath()
{
const string PARENT = "samples";
const string FOLDER = "skills";
const string Parent = "samples";
const string Folder = "skills";
bool SearchPath(string pathToFind, out string result, int maxAttempts = 10)
{
@@ -30,8 +30,8 @@ internal static class RepoFiles
return found;
}
if (!SearchPath(PARENT + Path.DirectorySeparatorChar + FOLDER, out string path)
&& !SearchPath(FOLDER, out path))
if (!SearchPath(Parent + Path.DirectorySeparatorChar + Folder, out string path)
&& !SearchPath(Folder, out path))
{
throw new YourAppException("Skills directory not found. The app needs the skills from the repo to work.");
}
@@ -24,7 +24,7 @@ public static class Example05_InlineFunctionDefinition
kernel.Config.AddOpenAITextCompletionService("text-davinci-003", Env.Var("OPENAI_API_KEY"));
// Function defined using few-shot design pattern
const string FUNCTION_DEFINITION = @"
const string FunctionDefinition = @"
Generate a creative reason or excuse for the given event.
Be creative and be funny. Let your imagination run wild.
@@ -37,7 +37,7 @@ Excuse: I've been too busy training my pet dragon.
Event: {{$input}}
";
var excuseFunction = kernel.CreateSemanticFunction(FUNCTION_DEFINITION, maxTokens: 100, temperature: 0.4, topP: 1);
var excuseFunction = kernel.CreateSemanticFunction(FunctionDefinition, maxTokens: 100, temperature: 0.4, topP: 1);
var result = await excuseFunction.InvokeAsync("I missed the F1 final race");
Console.WriteLine(result);
@@ -26,7 +26,7 @@ public static class Example06_TemplateLanguage
kernel.ImportSkill(new TimeSkill(), "time");
// Semantic Function invoking time.Date and time.Time native functions
const string FUNCTION_DEFINITION = @"
const string FunctionDefinition = @"
Today is: {{time.Date}}
Current time is: {{time.Time}}
@@ -38,11 +38,11 @@ Is it weekend time (weekend/not weekend)?
// This allows to see the prompt before it's sent to OpenAI
Console.WriteLine("--- Rendered Prompt");
var promptRenderer = new PromptTemplateEngine();
var renderedPrompt = await promptRenderer.RenderAsync(FUNCTION_DEFINITION, kernel.CreateNewContext());
var renderedPrompt = await promptRenderer.RenderAsync(FunctionDefinition, kernel.CreateNewContext());
Console.WriteLine(renderedPrompt);
// Run the prompt / semantic function
var kindOfDay = kernel.CreateSemanticFunction(FUNCTION_DEFINITION, maxTokens: 150);
var kindOfDay = kernel.CreateSemanticFunction(FunctionDefinition, maxTokens: 150);
// Show the result
Console.WriteLine("--- Semantic Function result");
@@ -68,7 +68,7 @@ public static class Example07_BingAndGoogleSkills
{
Console.WriteLine("======== Use Search Skill to answer user questions ========");
const string SEMANTIC_FUNCTION = @"Answer questions only when you know the facts or the information is provided.
const string SemanticFunction = @"Answer questions only when you know the facts or the information is provided.
When you don't have sufficient information you reply with a list of commands to find the information needed.
When answering multiple questions, use a bullet point list.
Note: make sure single and double quotes are escaped using a backslash char.
@@ -104,7 +104,7 @@ Answer: ";
var questions = "Who is the most followed person on TikTok right now? What's the exchange rate EUR:USD?";
Console.WriteLine(questions);
var oracle = kernel.CreateSemanticFunction(SEMANTIC_FUNCTION, maxTokens: 200, temperature: 0, topP: 1);
var oracle = kernel.CreateSemanticFunction(SemanticFunction, maxTokens: 200, temperature: 0, topP: 1);
var context = kernel.CreateNewContext();
context["externalInformation"] = "";
@@ -12,7 +12,7 @@ public static class Example14_Memory
{
public static async Task RunAsync()
{
const string memoryCollectionName = "SKGitHub";
const string MemoryCollectionName = "SKGitHub";
var githubFiles = new Dictionary<string, string>()
{
@@ -45,7 +45,7 @@ public static class Example14_Memory
foreach (var entry in githubFiles)
{
await kernel.Memory.SaveReferenceAsync(
collection: memoryCollectionName,
collection: MemoryCollectionName,
description: entry.Value,
text: entry.Value,
externalId: entry.Key,
@@ -76,7 +76,7 @@ public static class Example14_Memory
Console.WriteLine("===========================\n" +
"Query: " + ask + "\n");
var memories = kernel.Memory.SearchAsync(memoryCollectionName, ask, limit: 5, minRelevanceScore: 0.77);
var memories = kernel.Memory.SearchAsync(MemoryCollectionName, ask, limit: 5, minRelevanceScore: 0.77);
i = 0;
await foreach (MemoryQueryResult memory in memories)
@@ -111,7 +111,7 @@ public static class Example14_Memory
Console.WriteLine("===========================\n" +
"Query: " + ask + "\n");
memories = kernel.Memory.SearchAsync(memoryCollectionName, ask, limit: 5, minRelevanceScore: 0.77);
memories = kernel.Memory.SearchAsync(MemoryCollectionName, ask, limit: 5, minRelevanceScore: 0.77);
i = 0;
await foreach (MemoryQueryResult memory in memories)
@@ -38,8 +38,8 @@ public static class Example15_MemorySkill
kernel.ImportSkill(new TextMemorySkill());
// Build a semantic function that saves info to memory
const string SAVE_FUNCTION_DEFINITION = @"{{save $info}}";
var memorySaver = kernel.CreateSemanticFunction(SAVE_FUNCTION_DEFINITION);
const string SaveFunctionDefinition = @"{{save $info}}";
var memorySaver = kernel.CreateSemanticFunction(SaveFunctionDefinition);
var context = kernel.CreateNewContext();
context[TextMemorySkill.CollectionParam] = MemoryCollectionName;
@@ -88,7 +88,7 @@ public static class Example15_MemorySkill
Console.WriteLine("========= Example: Using Recall in a Semantic Function =========");
// Build a semantic function that uses memory to find facts
const string RECALL_FUNCTION_DEFINITION = @"
const string RecallFunctionDefinition = @"
Consider only the facts below when answering questions.
About me: {{recall 'where did I grow up?'}}
@@ -99,7 +99,7 @@ Question: {{$query}}
Answer:
";
var aboutMeOracle = kernel.CreateSemanticFunction(RECALL_FUNCTION_DEFINITION, maxTokens: 100);
var aboutMeOracle = kernel.CreateSemanticFunction(RecallFunctionDefinition, maxTokens: 100);
context["query"] = "Do I live in the same town where I grew up?";
context[TextMemorySkill.RelevanceParam] = "0.8";
@@ -46,9 +46,9 @@ public static class Example16_CustomLLM
// Add your text completion service
kernel.Config.AddTextCompletionService(Factory);
const string FUNCTION_DEFINITION = "Does the text contain grammar errors (Y/N)? Text: {{$input}}";
const string FunctionDefinition = "Does the text contain grammar errors (Y/N)? Text: {{$input}}";
var textValidationFunction = kernel.CreateSemanticFunction(FUNCTION_DEFINITION);
var textValidationFunction = kernel.CreateSemanticFunction(FunctionDefinition);
var result = await textValidationFunction.InvokeAsync("I mised the training sesion this morning");
Console.WriteLine(result);
@@ -22,9 +22,9 @@ public static class Example20_HuggingFace
// Add HuggingFace text completion service
kernel.Config.AddTextCompletionService(_ => new HuggingFaceTextCompletion(Env.Var("HF_API_KEY"), model: "gpt2"));
const string FUNCTION_DEFINITION = "Question: {{$input}}; Answer:";
const string FunctionDefinition = "Question: {{$input}}; Answer:";
var questionAnswerFunction = kernel.CreateSemanticFunction(FUNCTION_DEFINITION);
var questionAnswerFunction = kernel.CreateSemanticFunction(FunctionDefinition);
var result = await questionAnswerFunction.InvokeAsync("What is New York?");
@@ -13,8 +13,8 @@ internal static class RepoFiles
/// <returns>The full path to samples/skills</returns>
internal static string SampleSkillsPath()
{
const string PARENT = "samples";
const string FOLDER = "skills";
const string Parent = "samples";
const string Folder = "skills";
bool SearchPath(string pathToFind, out string result, int maxAttempts = 10)
{
@@ -30,8 +30,8 @@ internal static class RepoFiles
return found;
}
if (!SearchPath(PARENT + Path.DirectorySeparatorChar + FOLDER, out string path)
&& !SearchPath(FOLDER, out path))
if (!SearchPath(Parent + Path.DirectorySeparatorChar + Folder, out string path)
&& !SearchPath(Folder, out path))
{
throw new YourAppException("Skills directory not found. The app needs the skills from the repo to work.");
}