105 lines
2.7 KiB
C#
105 lines
2.7 KiB
C#
using System;
|
|
using Newtonsoft.Json;
|
|
using Newtonsoft.Json.Linq;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace xAiService.Helpers
|
|
{
|
|
public static class XAiMcpResultExtractionHelper
|
|
{
|
|
/// <summary>
|
|
/// Extract Specified Object Result of Method Invoking ...
|
|
/// </summary>
|
|
/// <param name="raw"></param>
|
|
/// <param name="returnType"></param>
|
|
/// <returns></returns>
|
|
public static async Task<string> ExtractAsync(
|
|
object raw,
|
|
Type returnType
|
|
)
|
|
{
|
|
//
|
|
// Task / Task<T>
|
|
if (raw is Task task)
|
|
{
|
|
//
|
|
await task.ConfigureAwait(false);
|
|
if (returnType.IsGenericType &&
|
|
returnType.GetGenericTypeDefinition() == typeof(Task<>))
|
|
{
|
|
//
|
|
var value = returnType.GetProperty("Result").GetValue(task);
|
|
return Format(value);
|
|
}
|
|
|
|
//
|
|
return string.Empty;
|
|
}
|
|
|
|
//
|
|
// ValueTask (non-generic)
|
|
if (returnType == typeof(ValueTask))
|
|
{
|
|
//
|
|
await ((ValueTask)raw).ConfigureAwait(false);
|
|
return string.Empty;
|
|
}
|
|
|
|
//
|
|
// ValueTask<T> ...
|
|
if (returnType.IsGenericType &&
|
|
returnType.GetGenericTypeDefinition() == typeof(ValueTask<>))
|
|
{
|
|
//
|
|
var asTask = (Task)returnType.GetMethod("AsTask").Invoke(raw, null);
|
|
await asTask.ConfigureAwait(false);
|
|
var value = asTask.GetType().GetProperty("Result").GetValue(asTask);
|
|
|
|
//
|
|
return Format(value);
|
|
}
|
|
|
|
//
|
|
// void / T Syncron ...
|
|
return Format(raw);
|
|
}
|
|
|
|
//
|
|
#region Private ...
|
|
/// <summary>
|
|
/// Format Extracted Response ...
|
|
/// /// </summary>
|
|
/// <param name="value"></param>
|
|
/// <returns></returns>
|
|
private static string Format(object value)
|
|
{
|
|
//
|
|
if (value == null)
|
|
{
|
|
return string.Empty;
|
|
}
|
|
|
|
//
|
|
if (value is string s)
|
|
{
|
|
return s;
|
|
}
|
|
|
|
//
|
|
if (value is JToken jt)
|
|
{
|
|
return jt.ToString(Formatting.None);
|
|
}
|
|
|
|
//
|
|
if (value.GetType().IsPrimitive || value is decimal)
|
|
{
|
|
return value.ToString();
|
|
}
|
|
|
|
//
|
|
return JToken.FromObject(value).ToString(Formatting.None);
|
|
}
|
|
#endregion
|
|
}
|
|
} |