using AIAssistantModule.Core.Interfaces.SPI; using AIAssistantModule.Core.Options; using Microsoft.Extensions.Options; using OpenAI; using OpenAI.Chat; namespace AIAssistantModule.Infrastructure.Services { public class OpenAILLMService : ILLMService { private readonly ChatClient _chatClient; private readonly OpenAIOptions _options; public OpenAILLMService(IOptions options) { _options = options.Value; var openAiClient = new OpenAIClient(_options.ApiKey); _chatClient = openAiClient.GetChatClient(_options.Model); } public async Task CallAsync( string prompt, string? schema = null, CancellationToken cancellationToken = default) { var messages = new List { ChatMessage.CreateSystemMessage("You are a precise and structured AI assistant."), ChatMessage.CreateUserMessage(prompt) }; var request = new ChatCompletionOptions { Temperature = (float)_options.Temperature, MaxOutputTokenCount = _options.MaxTokens }; // If schema provided → enforce structured JSON output if (!string.IsNullOrWhiteSpace(schema)) { request.ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat( "structured_output", BinaryData.FromString(schema)); } var response = await _chatClient.CompleteChatAsync( messages, request, cancellationToken); return response.Value.Content[0].Text; } } }