77
88namespace Gulla . Episerver . Labs . LanguageManager . OpenAi
99{
10- public class OpenAiService
10+ public class LanguageManagerOpenAiService
1111 {
12- private readonly HttpClient _client ;
1312 private readonly IOptions < LanguageManagerOpenAiOptions > _options ;
1413 private readonly string _endpointCompletions = "https://api.openai.com/v1/chat/completions" ;
1514
16- public OpenAiService ( HttpClient httpClient , IOptions < LanguageManagerOpenAiOptions > options )
15+ public LanguageManagerOpenAiService ( IOptions < LanguageManagerOpenAiOptions > options )
1716 {
1817 if ( options . Value . OpenAiApiKey == null )
1918 {
2019 throw new ArgumentException ( "Missing OpenAI API Key for Gulla.Episerver.Labs.LanguageManager.OpenAi!" ) ;
2120 }
2221
23- _options = options ;
24- _client = httpClient ;
25- _client . DefaultRequestHeaders . Add ( "Authorization" , $ "Bearer { _options . Value . OpenAiApiKey } ") ;
22+ _options = options ;
2623 }
2724
2825 /// <summary>
@@ -34,6 +31,9 @@ public OpenAiService(HttpClient httpClient, IOptions<LanguageManagerOpenAiOption
3431 /// <returns></returns>
3532 public async Task < string > TranslateText ( string input , string fromLanguageName , string toLanguageName )
3633 {
34+ using var httpClient = new HttpClient ( ) ;
35+ httpClient . DefaultRequestHeaders . Add ( "Authorization" , $ "Bearer { _options . Value . OpenAiApiKey } ") ;
36+
3737 var prompt = $ "Translate the following content from { fromLanguageName } to { toLanguageName } .";
3838 if ( ! string . IsNullOrEmpty ( _options . Value . OpenAiExtraPrompt ) )
3939 {
@@ -46,7 +46,7 @@ public async Task<string> TranslateText(string input, string fromLanguageName, s
4646 var content = new StringContent ( JsonConvert . SerializeObject ( new { messages = messages , model = _options . Value . OpenAiModel , temperature = _options . Value . OpenAiTemperature } ) , Encoding . UTF8 , "application/json" ) ;
4747 request . Content = content ;
4848
49- var response = await _client . SendAsync ( request ) ;
49+ var response = await httpClient . SendAsync ( request ) ;
5050 var json = await response . Content . ReadAsStringAsync ( ) ;
5151 var data = JsonConvert . DeserializeObject < dynamic > ( json ) ;
5252
0 commit comments