33using System . Net . Http ;
44using System . Text . Json ;
55using System . Text . Json . Serialization ;
6+ using System . Threading ;
67
78namespace SourceGit . Models
89{
@@ -97,7 +98,7 @@ public static bool IsValid
9798 get => ! string . IsNullOrEmpty ( Server ) && ! string . IsNullOrEmpty ( ApiKey ) && ! string . IsNullOrEmpty ( Model ) ;
9899 }
99100
100- public static OpenAIChatResponse Chat ( string prompt , string question )
101+ public static OpenAIChatResponse Chat ( string prompt , string question , CancellationToken cancellation )
101102 {
102103 var chat = new OpenAIChatRequest ( ) { Model = Model } ;
103104 chat . AddMessage ( "system" , prompt ) ;
@@ -107,17 +108,27 @@ public static OpenAIChatResponse Chat(string prompt, string question)
107108 client . DefaultRequestHeaders . Add ( "Authorization" , $ "Bearer { ApiKey } ") ;
108109
109110 var req = new StringContent ( JsonSerializer . Serialize ( chat , JsonCodeGen . Default . OpenAIChatRequest ) ) ;
110- var task = client . PostAsync ( Server , req ) ;
111- task . Wait ( ) ;
112-
113- var rsp = task . Result ;
114- if ( ! rsp . IsSuccessStatusCode )
115- throw new Exception ( $ "AI service returns error code { rsp . StatusCode } ") ;
116-
117- var reader = rsp . Content . ReadAsStringAsync ( ) ;
118- reader . Wait ( ) ;
119-
120- return JsonSerializer . Deserialize ( reader . Result , JsonCodeGen . Default . OpenAIChatResponse ) ;
111+ try
112+ {
113+ var task = client . PostAsync ( Server , req , cancellation ) ;
114+ task . Wait ( ) ;
115+
116+ var rsp = task . Result ;
117+ if ( ! rsp . IsSuccessStatusCode )
118+ throw new Exception ( $ "AI service returns error code { rsp . StatusCode } ") ;
119+
120+ var reader = rsp . Content . ReadAsStringAsync ( cancellation ) ;
121+ reader . Wait ( ) ;
122+
123+ return JsonSerializer . Deserialize ( reader . Result , JsonCodeGen . Default . OpenAIChatResponse ) ;
124+ }
125+ catch
126+ {
127+ if ( cancellation . IsCancellationRequested )
128+ return null ;
129+
130+ throw ;
131+ }
121132 }
122133 }
123134}
0 commit comments