This commit is contained in:
2026-04-09 17:02:13 +03:30
parent 843aff3879
commit 523ad16b3c
10 changed files with 706 additions and 0 deletions
+27
View File
@@ -0,0 +1,27 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using xAiApi.AI.Interfaces;
using xAiApi.AI.Services;
namespace xAiApi.AI.DI
{
public static class AIExtensions
{
/// <summary>
/// Register AI Services ...
/// </summary>
/// <param name="services"></param>
public static void AddXAIServices(this IServiceCollection services)
{
//
services.AddSingleton<IXAIService, XAIService>();
}
/// <summary>
/// Use AI Service Middlewares ...
/// </summary>
/// <param name="builder"></param>
public static void UseXAIServices(this IApplicationBuilder builder)
{ }
}
}
+28
View File
@@ -0,0 +1,28 @@
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
namespace xAiApi.AI.Interfaces
{
public interface IXAIService
{
IChatClient TextGenreatorClient { get; }
IChatClient ImageGenreatorClient { get; }
//
#region Actions ...
/// <summary>
/// Generated Text ...
/// </summary>
/// <param name="prompt"></param>
/// <returns></returns>
Task<string> GetTextResponseAsync(string prompt);
/// <summary>
/// Generated Response ...
/// </summary>
/// <param name="prompt"></param>
/// <returns></returns>
Task<ChatResponse> GetResponseAsync(string prompt);
#endregion
}
}
+66
View File
@@ -0,0 +1,66 @@
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using OllamaSharp;
using xAiApi.AI.Interfaces;
using xCommons.Extensions;
using xExceptions.Constants;
namespace xAiApi.AI.Services
{
public class XAIService : IXAIService
{
//
public IChatClient TextGenreatorClient { get; }
public IChatClient ImageGenreatorClient { get; }
public XAIService()
{
//
// here we are Initialize Text Generator Model ...
TextGenreatorClient = new OllamaApiClient(
new Uri("http://localhost:11434"),
"gemma3:1b"
);
}
//
#region Actions ...
/// <summary>
/// Generated Response ...
/// </summary>
/// <param name="prompt"></param>
/// <returns></returns>
public async Task<ChatResponse> GetResponseAsync(string prompt)
{
//
// Validate ...
var isValid = !prompt.IsNullOrEmpty();
if (!isValid)
{
XException.InvalidArgs.Throw();
}
//
// Generate Response ...
var result = await TextGenreatorClient
.GetResponseAsync(prompt);
//
return result;
}
/// <summary>
/// Generated Text ...
/// </summary>
/// <param name="prompt"></param>
/// <returns></returns>
public async Task<string> GetTextResponseAsync(string prompt)
{
//
var response = await GetResponseAsync(prompt);
return response.Text;
}
#endregion
}
}
+84
View File
@@ -0,0 +1,84 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using xAiApi.Helpers;
using xCommons.Configurations;
using xCommons.Controllers;
using xCommons.Extensions;
using xCommons.Providers;
using xIdentityHelper;
namespace xAiApi.Controllers
{
public class OSController : XBaseController
{
public OSController(
ILogger<OSController> logger,
XAppConfiguration appConfiguration,
XValidationProvider validationProvider
) : base(
logger,
appConfiguration,
validationProvider
)
{ }
//
#region Actions ...
/// <summary>
/// Get OS Type ...
/// </summary>
/// <returns></returns>
[HttpGet("OSType")]
[Authorize(Policy = XPolicies.Admin)]
public ActionResult<string> GetOSType()
{
//
// Do ...
try
{
//
var osType = XOsHelper.GetOSType();
var result = osType.GetStringValue();
//
return Ok(result);
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// Get OS Description ...
/// </summary>
/// <returns></returns>
[HttpGet("OSDescription")]
[Authorize(Policy = XPolicies.Admin)]
public ActionResult<string> GetOSDescription()
{
//
// Do ...
try
{
//
var result = XOsHelper.GetOSDescription();
//
return Ok(result);
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
#endregion
}
}
+62
View File
@@ -0,0 +1,62 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using xAiApi.AI.Interfaces;
using xAiApi.Base;
using xCommons.Configurations;
using xCommons.Providers;
using xIdentityService.Interfaces;
namespace xAiApi.Controllers.V1
{
public class AIController : XIBaseV1Controller
{
private readonly IXAIService aiService;
public AIController(
IXAIService aiService,
ILogger<XIBaseV1Controller> logger,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
XValidationProvider validationProvider
) : base(
logger,
appConfiguration,
identityProvider,
validationProvider
)
{
this.aiService = aiService;
}
//
#region Actions ...
[AllowAnonymous]
[HttpGet("AskAI")]
public async Task<ActionResult<string>> AskAI(
[FromQuery] string prompt
)
{
//
// Do ...
try
{
//
var result = await aiService
.GetTextResponseAsync(prompt);
//
return Ok(result);
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
#endregion
}
}
+115
View File
@@ -0,0 +1,115 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using xAiApi.Base;
using xAiApi.Helpers;
using xCommons.Configurations;
using xCommons.Providers;
using xIdentityHelper;
using xIdentityService.Interfaces;
namespace xAiApi.Controllers.V1
{
public class OllamaController : XIBaseV1Controller
{
public OllamaController(
ILogger<XIBaseV1Controller> logger,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
XValidationProvider validationProvider
) : base(
logger,
appConfiguration,
identityProvider,
validationProvider
)
{ }
//
#region Actions ...
/// <summary>
/// Retrieve Ollama Version ...
/// </summary>
/// <returns></returns>
[HttpGet("Version")]
[Authorize(Policy = XPolicies.Admin)]
public async Task<ActionResult<string>> GetVersion()
{
//
// Do ...
try
{
//
var result = await XOllamaHelper.GetVersion();
//
return Ok(result);
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// Retrieve a List of Available models ...
/// </summary>
/// <returns></returns>
[HttpGet("Models")]
[Authorize(Policy = XPolicies.Admin)]
public async Task<ActionResult<IEnumerable<string>>> GetModels()
{
//
// Do ...
try
{
//
var result = await XOllamaHelper.GetModels();
//
return Ok(result);
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// Find a model ...
/// </summary>
/// <returns></returns>
[HttpGet("FindModel")]
[Authorize(Policy = XPolicies.Admin)]
public async Task<ActionResult<IEnumerable<string>>> FindModel(
[FromQuery]
string model
)
{
//
// Do ...
try
{
//
var result = await XOllamaHelper.FindModel(model);
//
return Ok(result);
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
#endregion
}
}
+145
View File
@@ -0,0 +1,145 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using xCommons.Extensions;
namespace xAiApi.Helpers
{
public class XOllamaHelper
{
/// <summary>
/// Get Version ...
/// </summary>
/// <returns></returns>
public static async Task<string> GetVersion()
{
//
var cmd = "ollama";
var args = "--version";
var cmdResult = await XOsHelper.Execute(cmd, args);
//
var result =
cmdResult.Error.IsNullOrEmpty()
? cmdResult.Result
: cmdResult.Error;
//
result = result.Replace("\n", "");
//
return result;
}
/// <summary>
/// Get Exists Models ...
/// </summary>
/// <returns></returns>
public static async Task<IEnumerable<string>> GetModels()
{
//
var cmd = "ollama";
var args = "list";
var cmdResult = await XOsHelper.Execute(cmd, args);
//
var cmdResultText =
cmdResult.Error.IsNullOrEmpty()
? cmdResult.Result
: cmdResult.Error;
//
var cmdResultList = cmdResultText
.Split("\n")
.ToList();
if (cmdResultList.Count > 0)
{
cmdResultList.RemoveAt(0);
}
//
var result = new List<string>();
if (cmdResultList.Count > 0)
{
//
cmdResultList
.ForEach(i =>
{
//
if (!i.IsNullOrEmpty())
{
//
var d = i.Split(" ");
if (d.Length > 0)
{
result.Add(d[0]);
}
}
});
}
//
return result;
}
/// <summary>
/// Check Specified Model Exists ...
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static async Task<bool> HasModel(string model)
{
//
var result = !model.IsNullOrEmpty();
if (!result)
{
return result;
}
//
var models = await GetModels();
result = models.HasChild();
if (!result)
{
return result;
}
//
result = models
.Any(n => n == model || n.ToNormalString().Contains(model.ToNormalString()));
return result;
}
/// <summary>
/// Search Available Models ...
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static async Task<IEnumerable<string>> FindModel(string model)
{
//
var result = new List<string>();
//
if (model.IsNullOrEmpty())
{
return result;
}
//
var models = await GetModels();
if (!models.HasChild())
{
return result;
}
//
result = models
.Where(n => n == model || n.ToNormalString().Contains(model.ToNormalString()))
.ToList();
//
return result;
}
}
}
+168
View File
@@ -0,0 +1,168 @@
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using xCommons.Extensions;
using xExceptions.Attributes;
using xExceptions.Constants;
namespace xAiApi.Helpers
{
/// <summary>
/// Several OS Type ...
/// </summary>
public enum XOSType
{
[StringValue("Unknown")]
XUnknown,
[StringValue("Mac")]
XMacOs,
[StringValue("Linux")]
XLinux,
[StringValue("Windows")]
XWindows,
[StringValue("FreeBSD")]
XFreeBSD,
}
/// <summary>
/// OS Command Execution Result ...
/// </summary>
public class XOSCMDResult
{
/// <summary>
/// Execution Result ...
/// </summary>
/// <value></value>
public string Result { get; set; }
/// <summary>
/// Execution Error ...
/// </summary>
/// <value></value>
public string Error { get; set; }
}
public static class XOsHelper
{
/// <summary>
/// Retrieve OS Type ...
/// </summary>
/// <returns></returns>
public static XOSType GetOSType()
{
//
XOSType result = XOSType.XUnknown;
//
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
result = XOSType.XMacOs;
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
result = XOSType.XLinux;
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
result = XOSType.XWindows;
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD))
{
result = XOSType.XFreeBSD;
}
//
return result;
}
/// <summary>
/// Retrieve OS Description ...
/// </summary>
/// <returns></returns>
public static string GetOSDescription()
{
//
var result = RuntimeInformation.OSDescription;
return result;
}
/// <summary>
/// Execute an Specified Command ...
/// </summary>
/// <param name="cmd">Specified Command</param>
/// <param name="args">Command Arguments</param>
/// <returns></returns>
public static async Task<XOSCMDResult> Execute(
string cmd,
string args
)
{
//
var result = new XOSCMDResult
{
Error = "Unknown",
};
//
try
{
//
// Validate CMD ...
var isValid = !cmd.IsNullOrEmpty();
if (!isValid)
{
XException.InvalidArgs.Throw();
}
//
// Validate OS Type ...
XOSType osType = GetOSType();
isValid = osType != XOSType.XUnknown;
if (!isValid)
{
XException.InvalidArgs.Throw();
}
//
ProcessStartInfo psi = new ProcessStartInfo();
//
psi.FileName = cmd;
psi.Arguments = args;
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
//
Process process = Process.Start(psi);
//
// Read the output
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
//
await process.WaitForExitAsync();
//
result = new XOSCMDResult
{
Error = error,
Result = output,
};
}
catch (Exception ex)
{
result.Error = ex.Message;
}
//
return result;
}
}
}
+9
View File
@@ -27,6 +27,7 @@ using xAiApi.DI;
using xAiApi.Data.Helpers;
using xAiApi.Data;
using xAiApi.Data.Seeder;
using xAiApi.AI.DI;
// using xApi.Extensions;
// using xDataHelper;
// using xDataHelper.DbSeeder;
@@ -201,6 +202,10 @@ namespace xAiApi
};
});
#endregion
//
// Register AI Service ...
services.AddXAIServices();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
@@ -263,6 +268,10 @@ namespace xAiApi
//
// Use xGraphQL Middleware ...
app.UseXGraphQL(withPlayground: withPlayground);
//
// Use AI Services ...
app.UseXAIServices();
}
}
}
+2
View File
@@ -29,6 +29,8 @@
<!-- Dependencies -->
<ItemGroup>
<PackageReference Include="OllamaSharp" Version="5.4.25" />
<PackageReference Include="Microsoft.Extensions.AI" Version="10.4.1" />
<PackageReference Include="Microsoft.SemanticKernel" Version="1.65.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="5.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.11" />