86 lines
2.3 KiB
C#
86 lines
2.3 KiB
C#
using System.Text.Json;
|
|
using System.Threading;
|
|
using xAiModels.Models;
|
|
using xCommons.Extensions;
|
|
using xExceptions.Constants;
|
|
using System.Text.Json.Nodes;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.AI;
|
|
|
|
namespace xAiService.Services
|
|
{
|
|
/// <summary>
|
|
/// a Customized AIFunction Implementation ...
|
|
/// </summary>
|
|
public class XAiMcpAIFunction : AIFunction
|
|
{
|
|
//
|
|
private readonly XAiMcpClient client;
|
|
private readonly JsonElement jsonSchema;
|
|
private readonly XAiMcpToolDefinition definition;
|
|
|
|
public XAiMcpAIFunction(
|
|
XAiMcpClient client,
|
|
XAiMcpToolDefinition definition
|
|
)
|
|
{
|
|
//
|
|
if (client.IsNull() || definition.IsNull())
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
|
|
//
|
|
this.client = client;
|
|
this.definition = definition;
|
|
|
|
//
|
|
jsonSchema = definition.InputSchema.Clone();
|
|
}
|
|
|
|
//
|
|
public override string Name => definition.Name;
|
|
public override JsonElement JsonSchema => jsonSchema;
|
|
public override string Description => definition.Description;
|
|
|
|
/// <summary>
|
|
/// Invoke Tool ...
|
|
/// </summary>
|
|
/// <param name="arguments"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
protected override async ValueTask<object> InvokeCoreAsync(
|
|
AIFunctionArguments arguments,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
var jsonArgs = ToJsonObject(arguments);
|
|
return await client.CallToolAsync(
|
|
definition.Name,
|
|
jsonArgs,
|
|
cancellationToken
|
|
);
|
|
}
|
|
|
|
private JsonObject ToJsonObject(AIFunctionArguments arguments)
|
|
{
|
|
//
|
|
var result = new JsonObject();
|
|
if (arguments.IsNull() ||
|
|
arguments is null)
|
|
{
|
|
return result;
|
|
}
|
|
|
|
//
|
|
foreach (var kvp in arguments)
|
|
{
|
|
result[kvp.Key] = JsonSerializer.SerializeToNode(kvp.Value);
|
|
}
|
|
|
|
//
|
|
return result;
|
|
}
|
|
}
|
|
} |