Webiant Logo Webiant Logo
  1. No results found.

    Try your search with a different keyword or use * as a wildcard.

ArtificialIntelligenceHttpClient.cs

using Nop.Core;
using Nop.Core.Domain.ArtificialIntelligence;

namespace Nop.Services.ArtificialIntelligence;

/// 
/// Represents the HTTP client to request artificial intelligence
/// 
public partial class ArtificialIntelligenceHttpClient
{
    #region Fields

    protected readonly ArtificialIntelligenceSettings _artificialIntelligenceSettings;
    protected readonly HttpClient _httpClient;
    protected readonly IArtificialIntelligenceHttpClientHelper _artificialIntelligenceHttpClientHelper;

    #endregion

    #region Ctor

    public ArtificialIntelligenceHttpClient(ArtificialIntelligenceSettings artificialIntelligenceSettings,
        HttpClient httpClient)
    {
        _artificialIntelligenceSettings = artificialIntelligenceSettings;
        _httpClient = httpClient;

        //configure client
        httpClient.Timeout = TimeSpan.FromSeconds(artificialIntelligenceSettings.RequestTimeout ??
            ArtificialIntelligenceDefaults.RequestTimeout);

        _artificialIntelligenceHttpClientHelper = _artificialIntelligenceSettings.ProviderType switch
        {
            ArtificialIntelligenceProviderType.Gemini => new GeminiHttpClientHelper(),
            ArtificialIntelligenceProviderType.ChatGpt => new ChatGptHttpClientHelper(),
            ArtificialIntelligenceProviderType.DeepSeek => new DeepSeekHttpClientHelper(),
            _ => throw new ArgumentOutOfRangeException()
        };

        _artificialIntelligenceHttpClientHelper.ConfigureClient(httpClient);
    }

    #endregion

    #region Methods

    /// 
    /// Send query to artificial intelligence host
    /// 
    /// Query to artificial intelligence host
    /// 
    /// A task that represents the asynchronous operation
    /// The task result contains the response from the artificial intelligence host
    /// 
    public virtual async Task SendQueryAsync(string query)
    {
        var request = _artificialIntelligenceHttpClientHelper.CreateRequest(_artificialIntelligenceSettings, query);

        var httpResponse = await _httpClient.SendAsync(request);
        var response = await httpResponse.Content.ReadAsStringAsync();

        if (!httpResponse.IsSuccessStatusCode)
            throw new NopException(httpResponse.ReasonPhrase, innerException: new Exception(response));

        var result = _artificialIntelligenceHttpClientHelper.ParseResponse(response);

        return result;
    }

    #endregion
}