Search code examples
artificial-intelligencelarge-language-modelsemantic-kernel

Is there a generic way to escape special characters in prompts when using Semantic Kernel?


This is my prompt invocation in C#:

var result = await kernel.InvokePromptAsync(prompt, new(executionSettings));        

It works like a charm, except if the prompt contains something like this:

{ bla } {{ bla }} { $bla } {{ bla }} {{request}} {{choices.[0]}}

I get a

Unhandled exception. Microsoft.SemanticKernel.KernelException: The function 
identifier is empty

This is apparently because {{}} is used for injecting values or functions.

This document suggest to escape curley braces https://learn.microsoft.com/en-us/semantic-kernel/concepts/prompts/prompt-template-syntax#prompts-needing-double-curly-braces and here is something about single and double quotes https://learn.microsoft.com/en-us/semantic-kernel/concepts/prompts/prompt-template-syntax#values-that-include-quotes-and-escaping

Is there a build-in way in Semantic Kernel to do the character escaping so I don't wave to write my own? I would prefer not to write my, own because I might get it wrong.


Solution

  • I've not found an "out of the box" solution, so this is what I do, until I find a better way.

    prompt = prompt
        .Replace("{{", "{{ \"{{\" }}")
        .Replace("}}", "{{ \"}}\" }}");