add all requirements for implementing XAiMcpClient ...
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using xCommons.Extensions;
|
||||
using xHttpService.Constants;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace xAiModels.Helpers
|
||||
{
|
||||
public static class XAiMcpSseReader
|
||||
{
|
||||
/// <summary>
|
||||
/// Read an SSE Event ...
|
||||
/// </summary>
|
||||
/// <param name="stream"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public static async IAsyncEnumerable<string> ReadAsync(
|
||||
Stream stream,
|
||||
[EnumeratorCancellation]
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
using var reader = new StreamReader(stream, Encoding.UTF8);
|
||||
var dataBuffer = new StringBuilder();
|
||||
while (!reader.EndOfStream)
|
||||
{
|
||||
//
|
||||
var line = await reader.ReadLineAsync();
|
||||
if (line is null)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
//
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
//
|
||||
// Empty Line equals End of an Event ...
|
||||
if (line.IsNullOrEmpty())
|
||||
{
|
||||
//
|
||||
if (dataBuffer.Length > 0)
|
||||
{
|
||||
//
|
||||
yield return dataBuffer.ToString();
|
||||
dataBuffer.Clear();
|
||||
}
|
||||
|
||||
//
|
||||
continue;
|
||||
}
|
||||
|
||||
//
|
||||
if (line.StartsWith(XSSEConstants.DataIdentifier, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
//
|
||||
var data = line
|
||||
.Substring(XSSEConstants.DataIdentifier.Length)
|
||||
.TrimStart();
|
||||
|
||||
//
|
||||
if (dataBuffer.Length > 0)
|
||||
{
|
||||
dataBuffer.Append('\n');
|
||||
}
|
||||
|
||||
//
|
||||
dataBuffer.Append(data);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
if (dataBuffer.Length > 0)
|
||||
{
|
||||
yield return dataBuffer.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user