namespace AIStudio.Chat;
public static class StringExtensions
{
/// The text.
extension(string text)
{
public string RemoveThinkTags()
{
const string OPEN_TAG = "";
const string CLOSE_TAG = "";
if (string.IsNullOrWhiteSpace(text) || !text.StartsWith(OPEN_TAG, StringComparison.Ordinal))
return text;
var endIndex = text.IndexOf(CLOSE_TAG, StringComparison.Ordinal);
if (endIndex == -1)
return string.Empty;
return text[(endIndex + CLOSE_TAG.Length)..];
}
///
/// Shortens a text to the given number of characters, and marks the cut with three dots.
///
///
/// Never cuts between the two halves of a surrogate pair, which no JSON writer takes.
/// Takes and returns a string rather than a span on purpose: most texts are short enough, and
/// those come back as the very same instance. Only a text which is cut costs one new string.
///
/// How many characters of the text to keep at most, the dots not counted.
/// The text as it was when it is short enough, otherwise its beginning followed by three dots.
public string Shorten(int maxCharacters)
{
if (text.Length <= maxCharacters)
return text;
var end = char.IsHighSurrogate(text[maxCharacters - 1]) ? maxCharacters - 1 : maxCharacters;
return string.Concat(text.AsSpan(0, end).TrimEnd(), "...");
}
}
}