1+ using System . Net . Http . Headers ;
2+ using System . Text . Json ;
3+ using Microsoft . AspNetCore . Mvc ;
4+ using Microsoft . Extensions . Options ;
5+ using chatui . Configuration ;
6+ using chatui . Models ;
7+
8+ namespace chatui . Controllers ;
9+
10+ [ ApiController ]
11+ [ Route ( "[controller]/[action]" ) ]
12+
13+ public class ChatController (
14+ IHttpClientFactory httpClientFactory ,
15+ IOptionsMonitor < ChatApiOptions > options ,
16+ ILogger < ChatController > logger ) : ControllerBase
17+ {
18+ private readonly HttpClient _client = httpClientFactory . CreateClient ( "ChatClient" ) ;
19+ private readonly IOptionsMonitor < ChatApiOptions > _options = options ;
20+ private readonly ILogger < ChatController > _logger = logger ;
21+
22+ [ HttpPost ]
23+ public async Task < IActionResult > Completions ( [ FromBody ] string prompt )
24+ {
25+ if ( string . IsNullOrWhiteSpace ( prompt ) )
26+ throw new ArgumentException ( "Prompt cannot be null, empty, or whitespace." , nameof ( prompt ) ) ;
27+
28+ _logger . LogDebug ( "Prompt received {Prompt}" , prompt ) ;
29+
30+ var _config = _options . CurrentValue ;
31+
32+ var requestBody = JsonSerializer . Serialize ( new Dictionary < string , string >
33+ {
34+ [ _config . ChatInputName ] = prompt
35+ } ) ;
36+
37+ using var request = new HttpRequestMessage ( HttpMethod . Post , _config . ChatApiEndpoint )
38+ {
39+ Content = new StringContent ( requestBody , System . Text . Encoding . UTF8 , "application/json" ) ,
40+ } ;
41+ request . Headers . Authorization = new AuthenticationHeaderValue ( "Bearer" , _config . ChatApiKey ) ;
42+
43+ var response = await _client . SendAsync ( request ) ;
44+ var responseContent = await response . Content . ReadAsStringAsync ( ) ;
45+
46+ _logger . LogInformation ( "HTTP status code: {StatusCode}" , response . StatusCode ) ;
47+
48+ if ( ! response . IsSuccessStatusCode )
49+ {
50+ _logger . LogError ( "Error response: {Content}" , responseContent ) ;
51+
52+ foreach ( var ( key , value ) in response . Headers )
53+ _logger . LogDebug ( "Header {Key}: {Value}" , key , string . Join ( ", " , value ) ) ;
54+
55+ foreach ( var ( key , value ) in response . Content . Headers )
56+ _logger . LogDebug ( "Content-Header {Key}: {Value}" , key , string . Join ( ", " , value ) ) ;
57+
58+ return BadRequest ( responseContent ) ;
59+ }
60+
61+ _logger . LogInformation ( "Successful response: {Content}" , responseContent ) ;
62+
63+ var result = JsonSerializer . Deserialize < Dictionary < string , string > > ( responseContent ) ;
64+ var output = result ? . GetValueOrDefault ( _config . ChatOutputName ) ?? string . Empty ;
65+
66+ return Ok ( new HttpChatResponse ( true , output ) ) ;
67+ }
68+ }
0 commit comments