3
3
using System . Net . Http ;
4
4
using System . Text . Json ;
5
5
using System . Text . Json . Serialization ;
6
+ using System . Threading ;
6
7
7
8
namespace SourceGit . Models
8
9
{
@@ -97,7 +98,7 @@ public static bool IsValid
97
98
get => ! string . IsNullOrEmpty ( Server ) && ! string . IsNullOrEmpty ( ApiKey ) && ! string . IsNullOrEmpty ( Model ) ;
98
99
}
99
100
100
- public static OpenAIChatResponse Chat ( string prompt , string question )
101
+ public static OpenAIChatResponse Chat ( string prompt , string question , CancellationToken cancellation )
101
102
{
102
103
var chat = new OpenAIChatRequest ( ) { Model = Model } ;
103
104
chat . AddMessage ( "system" , prompt ) ;
@@ -107,17 +108,27 @@ public static OpenAIChatResponse Chat(string prompt, string question)
107
108
client . DefaultRequestHeaders . Add ( "Authorization" , $ "Bearer { ApiKey } ") ;
108
109
109
110
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
+ }
121
132
}
122
133
}
123
134
}
0 commit comments