■ HttpClient 클래스를 사용해 네이버 HyperCLOVA X와 통신하는 방법을 보여준다. (IAsyncEnumerable<T> 객체)
▶ AIFilter.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
using Newtonsoft.Json; namespace TestProject; /// <summary> /// AI 필터 /// </summary> public class AIFilter { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 그룹명 - GroupName /// <summary> /// 그룹명 /// </summary> [JsonProperty("groupName")] public string GroupName { get; set; } #endregion #region 명칭 - Name /// <summary> /// 명칭 /// </summary> [JsonProperty("name")] public string Name { get; set; } #endregion #region 점수 - Score /// <summary> /// 점수 /// </summary> [JsonProperty("score")] public string Score { get; set; } #endregion #region 결과 - Result /// <summary> /// 결과 /// </summary> [JsonProperty("result")] public string Result { get; set; } #endregion } |
▶ Message.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
using Newtonsoft.Json; namespace TestProject; /// <summary> /// 메시지 /// </summary> public class Message { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 역할 - Role /// <summary> /// 역할 /// </summary> [JsonProperty("role")] public string Role { get; set; } #endregion #region 내용 - Content /// <summary> /// 내용 /// </summary> [JsonProperty("content")] public string Content { get; set; } #endregion } |
▶ RequestMessage.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
using Newtonsoft.Json; namespace TestProject; /// <summary> /// 요청 메시지 /// </summary> public class RequestMessage { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 메시지 리스트 - MessageList /// <summary> /// 메시지 리스트 /// </summary> [JsonProperty("messages")] public List<Message> MessageList { get; set; } #endregion #region Top P - TopP /// <summary> /// TopP /// </summary> [JsonProperty("topP")] public double TopP { get; set; } #endregion #region Top K - TopK /// <summary> /// TopK /// </summary> [JsonProperty("topK")] public int TopK { get; set; } #endregion #region 최대 토큰 카운트 - MaximumTokenCount /// <summary> /// 최대 토큰 카운트 /// </summary> [JsonProperty("maxTokens")] public int MaximumTokenCount { get; set; } #endregion #region 온도 - Temperature /// <summary> /// 온도 /// </summary> [JsonProperty("temperature")] public double Temperature { get; set; } #endregion #region 반복 패널티 - RepeatPenalty /// <summary> /// 반복 패널티 /// </summary> [JsonProperty("repeatPenalty")] public double RepeatPenalty { get; set; } #endregion #region Stop Before - StopBefore /// <summary> /// Stop Before /// </summary> [JsonProperty("stopBefore")] public List<string> StopBefore { get; set; } #endregion #region AI 필터 포함 여부 - IncludeAIFilters /// <summary> /// AI 필터 포함 여부 /// </summary> [JsonProperty("includeAiFilters")] public bool IncludeAIFilters { get; set; } #endregion #region 시드 - Seed /// <summary> /// 시드 /// </summary> [JsonProperty("seed")] public int Seed { get; set; } #endregion } |
▶ ResponseMessage.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
using Newtonsoft.Json; namespace TestProject; /// <summary> /// 응답 메시지 /// </summary> public class ResponseMessage { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 상태 - Status /// <summary> /// 상태 /// </summary> [JsonProperty("status")] public ResponseStatus Status { get; set; } #endregion #region 결과 - Result /// <summary> /// 결과 /// </summary> [JsonProperty("result")] public ResponseResult Result { get; set; } #endregion } |
▶ ResponseResult.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
using Newtonsoft.Json; namespace TestProject; /// <summary> /// 응답 결과 /// </summary> public class ResponseResult { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 메시지 - Message /// <summary> /// 메시지 /// </summary> [JsonProperty("message")] public Message Message { get; set; } #endregion #region 입력 길이 - InputLength /// <summary> /// 입력 길이 /// </summary> [JsonProperty("inputLength")] public int InputLength { get; set; } #endregion #region 출력 길이 - OutputLength /// <summary> /// 출력 길이 /// </summary> [JsonProperty("outputLength")] public int OutputLength { get; set; } #endregion #region 중단 사유 - StopReason /// <summary> /// 중단 사유 /// </summary> [JsonProperty("stopReason")] public string StopReason { get; set; } #endregion #region 시드 - Seed /// <summary> /// 시드 /// </summary> [JsonProperty("seed")] public long Seed { get; set; } #endregion #region AI 필터 리스트 - AIFilterList /// <summary> /// AI 필터 리스트 /// </summary> [JsonProperty("aiFilter")] public List<AIFilter> AIFilterList { get; set; } #endregion } |
▶ ResponseStatus.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
using Newtonsoft.Json; namespace TestProject; /// <summary> /// 응답 상태 /// </summary> public class ResponseStatus { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 코드 - Code /// <summary> /// 코드 /// </summary> [JsonProperty("code")] public string Code { get; set; } #endregion #region 메시지 - Message /// <summary> /// 메시지 /// </summary> [JsonProperty("message")] public string Message { get; set; } #endregion } |
▶ StreamingDataBase.cs
1 2 3 4 5 6 7 8 9 10 |
namespace TestProject; /// <summary> /// 스트리밍 데이터 베이스 /// </summary> public class StreamingDataBase { } |
▶ StreamingDataResult.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
using Newtonsoft.Json; namespace TestProject; /// <summary> /// 스트리밍 데이터 결과 /// </summary> public class StreamingDataResult : StreamingDataBase { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 메시지 - Message /// <summary> /// 메시지 /// </summary> [JsonProperty("message")] public Message Message { get; set; } #endregion #region 입력 길이 - InputLength /// <summary> /// 입력 길이 /// </summary> [JsonProperty("inputLength")] public long InputLength { get; set; } #endregion #region 출력 길이 - OutputLength /// <summary> /// 출력 길이 /// </summary> [JsonProperty("outputLength")] public long OutputLength { get; set; } #endregion #region 중단 사유 - StopReason /// <summary> /// 중단 사유 /// </summary> [JsonProperty("stopReason")] public string StopReason { get; set; } #endregion #region 시드 - Seed /// <summary> /// 시드 /// </summary> [JsonProperty("seed")] public long Seed { get; set; } #endregion #region AI 필터 리스트 - AIFilterList /// <summary> /// AI 필터 리스트 /// </summary> [JsonProperty("aiFilter")] public List<AIFilter> AIFilterList { get; set; } #endregion } |
▶ StreamingDataSignal.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using Newtonsoft.Json; namespace TestProject; /// <summary> /// 스트리밍 데이터 시그널 /// </summary> public class StreamingDataSignal : StreamingDataBase { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 데이터 - Data /// <summary> /// 데이터 /// </summary> [JsonProperty("data")] public string Data { get; set; } #endregion } |
▶ StreamingDataToken.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
using Newtonsoft.Json; namespace TestProject; /// <summary> /// 스트리밍 데이터 토큰 /// </summary> public class StreamingDataToken : StreamingDataBase { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 메시지 - Message /// <summary> /// 메시지 /// </summary> [JsonProperty("message")] public Message Message { get; set; } #endregion #region 인덱스 - Index /// <summary> /// 인덱스 /// </summary> [JsonProperty("index")] public long Index { get; set; } #endregion #region 입력 길이 - InputLength /// <summary> /// 입력 길이 /// </summary> [JsonProperty("inputLength")] public long InputLength { get; set; } #endregion #region 출력 길이 - OutputLength /// <summary> /// 출력 길이 /// </summary> [JsonProperty("outputLength")] public long OutputLength { get; set; } #endregion #region 중단 사유 - StopReason /// <summary> /// 중단 사유 /// </summary> [JsonProperty("stopReason")] public string StopReason { get; set; } #endregion } |
▶ StreamingMessage.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
namespace TestProject; /// <summary> /// 스트리밍 메시지 /// </summary> public class StreamingMessage { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public string ID { get; set; } #endregion #region 이벤트 - Event /// <summary> /// 이벤트 /// </summary> public string Event { get; set; } #endregion #region 데이터 - Data /// <summary> /// 데이터 /// </summary> public StreamingDataBase Data { get; set; } #endregion } |
▶ APIClient.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 |
using System.Text; using System.Net.Http.Headers; using Newtonsoft.Json; namespace TestProject; /// <summary> /// API 클라이언트 /// </summary> public class APIClient : IDisposable { //////////////////////////////////////////////////////////////////////////////////////////////////// Event ////////////////////////////////////////////////////////////////////////////////////////// Public #region 메시지 도착시 이벤트 - MessageArrived /// <summary> /// 메시지 도착시 이벤트 /// </summary> public event EventHandler<StreamingMessage> MessageArrived; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 리소스 해제 여부 /// </summary> private bool disposed = false; /// <summary> /// BASE URL /// </summary> private const string BASE_URL = "https://clovastudio.stream.ntruss.com/testapp/v1/chat-completions/HCX-DASH-001"; /// <summary> /// 클로바 스튜디오 API 키 /// </summary> private string clovaStudioAPIKey; /// <summary> /// API 게이트웨이 API 키 /// </summary> private string apiGatewayAPIKey; /// <summary> /// HTTP 클라이언트 /// </summary> private HttpClient client; /// <summary> /// 품질을 갖는 스트림 미디어 타입 헤더 값 /// </summary> private MediaTypeWithQualityHeaderValue streamMediaTypeWithQualityHeaderValue; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 클로바 스튜디오 API 키 - ClovaStudioAPIKey /// <summary> /// 클로바 스튜디오 API 키 /// </summary> public string ClovaStudioAPIKey { get { return this.clovaStudioAPIKey; } } #endregion #region API 게이트웨이 API 키 - APIGatewayAPIKey /// <summary> /// API 게이트웨이 API 키 /// </summary> public string APIGatewayAPIKey { get { return this.apiGatewayAPIKey; } } #endregion #region HTTP 클라이언트 - Client /// <summary> /// HTTP 클라이언트 /// </summary> public HttpClient Client { get { return this.client; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region API 클라이언트 - APIClient(clovaStudioAPIKey, apiGatewayAPIKey) /// <summary> /// API 클라이언트 /// </summary> /// <param name="clovaStudioAPIKey">클로바 스튜디오 API 키</param> /// <param name="apiGatewayAPIKey">API 게이트웨이 API 키</param> public APIClient(string clovaStudioAPIKey, string apiGatewayAPIKey) { this.clovaStudioAPIKey = clovaStudioAPIKey; this.apiGatewayAPIKey = apiGatewayAPIKey; this.client = new HttpClient(); this.client.DefaultRequestHeaders.Add("X-NCP-CLOVASTUDIO-API-KEY", this.clovaStudioAPIKey); this.client.DefaultRequestHeaders.Add("X-NCP-APIGW-API-KEY" , this.apiGatewayAPIKey ); this.streamMediaTypeWithQualityHeaderValue = new MediaTypeWithQualityHeaderValue("text/event-stream"); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 응답 메시지 요청하기 (비동기) - RequestResponseMessageAsync(requestMessage) /// <summary> /// 응답 메시지 요청하기 (비동기) /// </summary> /// <param name="requestMessage">요청 메시지</param> /// <returns>응답 메시지 태스크</returns> public async Task<ResponseMessage> RequestResponseMessageAsync(RequestMessage requestMessage) { if(this.client.DefaultRequestHeaders.Accept.Contains(this.streamMediaTypeWithQualityHeaderValue)) { this.client.DefaultRequestHeaders.Accept.Remove(this.streamMediaTypeWithQualityHeaderValue); } if(this.client.DefaultRequestHeaders.Contains("X-NCP-CLOVASTUDIO-REQUEST-ID")) { this.client.DefaultRequestHeaders.Remove("X-NCP-CLOVASTUDIO-REQUEST-ID"); } string clovaStudioRequestID = Guid.NewGuid().ToString(); this.client.DefaultRequestHeaders.Add("X-NCP-CLOVASTUDIO-REQUEST-ID", clovaStudioRequestID); string requestJSON = JsonConvert.SerializeObject(requestMessage); StringContent stringContent = new(requestJSON, Encoding.UTF8, "application/json"); HttpResponseMessage httpResponseMessage = await this.client.PostAsync(BASE_URL, stringContent); httpResponseMessage.EnsureSuccessStatusCode(); string responseString = await httpResponseMessage.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<ResponseMessage>(responseString); } #endregion #region 스트리밍 메시지 리스트 요청하기 (비동기) - RequestStreamingMessageListAsync(requestMessage) /// <summary> /// 스트리밍 메시지 리스트 요청하기 (비동기) /// </summary> /// <param name="requestMessage">요청 메시지</param> /// <returns>스트리밍 메시지 리스트 태스크</returns> public async Task<List<StreamingMessage>> RequestStreamingMessageListAsync(RequestMessage requestMessage) { if(!this.client.DefaultRequestHeaders.Accept.Contains(this.streamMediaTypeWithQualityHeaderValue)) { this.client.DefaultRequestHeaders.Accept.Add(this.streamMediaTypeWithQualityHeaderValue); } if(this.client.DefaultRequestHeaders.Contains("X-NCP-CLOVASTUDIO-REQUEST-ID")) { this.client.DefaultRequestHeaders.Remove("X-NCP-CLOVASTUDIO-REQUEST-ID"); } string clovaStudioRequestID = Guid.NewGuid().ToString(); this.client.DefaultRequestHeaders.Add("X-NCP-CLOVASTUDIO-REQUEST-ID", clovaStudioRequestID); string requestJSON = JsonConvert.SerializeObject(requestMessage); StringContent stringContent = new(requestJSON, Encoding.UTF8, "application/json"); using HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, BASE_URL); httpRequestMessage.Content = stringContent; using HttpResponseMessage httpResponseMessage = await client.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseHeadersRead); httpResponseMessage.EnsureSuccessStatusCode(); using Stream stream = await httpResponseMessage.Content.ReadAsStreamAsync(); using StreamReader streamReader = new StreamReader(stream); List<StreamingMessage> streamingMessageList = new List<StreamingMessage>(); StreamingMessage currentStreamingMessage = null; while(!streamReader.EndOfStream) { string line = await streamReader.ReadLineAsync(); if(string.IsNullOrWhiteSpace(line)) { continue; } if(currentStreamingMessage == null) { if(line.StartsWith("id:")) { currentStreamingMessage = new StreamingMessage { ID = line[3..].Trim() }; continue; } if(line.StartsWith("event:")) { continue; } if(line.StartsWith("data:")) { continue; } } else { if(line.StartsWith("id:")) { continue; } if(line.StartsWith("event:")) { currentStreamingMessage.Event = line.Substring(6).Trim(); } if(line.StartsWith("data:")) { string dataJSON = line.Substring(5).Trim(); if(currentStreamingMessage.Event == "token") { StreamingDataToken streamingDataToken = JsonConvert.DeserializeObject<StreamingDataToken>(dataJSON); currentStreamingMessage.Data = streamingDataToken; } else if(currentStreamingMessage.Event == "result") { StreamingDataResult streamingDataResult = JsonConvert.DeserializeObject<StreamingDataResult>(dataJSON); currentStreamingMessage.Data = streamingDataResult; } else if(currentStreamingMessage.Event == "signal") { StreamingDataSignal streamingDataSignal = JsonConvert.DeserializeObject<StreamingDataSignal>(dataJSON); currentStreamingMessage.Data = streamingDataSignal; } streamingMessageList.Add(currentStreamingMessage); MessageArrived?.Invoke(this, currentStreamingMessage); currentStreamingMessage = null; continue; } } } return streamingMessageList; } #endregion #region 스트리밍 메시지 비동기 열거 가능형 요청하기 (비동기) - RequestStreamingMessageAsyncEnumerableAsync(requestMessage) /// <summary> /// 스트리밍 메시지 열거 가능형 요청하기 (비동기) /// </summary> /// <param name="requestMessage">요청 메시지</param> /// <returns>스트리밍 메시지 비동기 열거 가능형</returns> public async IAsyncEnumerable<StreamingMessage> RequestStreamingMessageAsyncEnumerableAsync(RequestMessage requestMessage) { if(!this.client.DefaultRequestHeaders.Accept.Contains(this.streamMediaTypeWithQualityHeaderValue)) { this.client.DefaultRequestHeaders.Accept.Add(this.streamMediaTypeWithQualityHeaderValue); } if(this.client.DefaultRequestHeaders.Contains("X-NCP-CLOVASTUDIO-REQUEST-ID")) { this.client.DefaultRequestHeaders.Remove("X-NCP-CLOVASTUDIO-REQUEST-ID"); } string clovaStudioRequestID = Guid.NewGuid().ToString(); this.client.DefaultRequestHeaders.Add("X-NCP-CLOVASTUDIO-REQUEST-ID", clovaStudioRequestID); string requestJSON = JsonConvert.SerializeObject(requestMessage); StringContent content = new(requestJSON, Encoding.UTF8, "application/json"); using HttpRequestMessage httpRequestMessage = new(HttpMethod.Post, BASE_URL); httpRequestMessage.Content = content; using HttpResponseMessage httpResponseMessage = await client.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseHeadersRead); httpResponseMessage.EnsureSuccessStatusCode(); using Stream stream = await httpResponseMessage.Content.ReadAsStreamAsync(); using StreamReader streamReader = new(stream); StreamingMessage currentStreamingMessage = null; while(!streamReader.EndOfStream) { string line = await streamReader.ReadLineAsync(); if(string.IsNullOrWhiteSpace(line)) { continue; } if(currentStreamingMessage == null) { if(line.StartsWith("id:")) { currentStreamingMessage = new StreamingMessage { ID = line.Substring(3).Trim() }; } } else { if (line.StartsWith("event:")) { currentStreamingMessage.Event = line.Substring(6).Trim(); } else if (line.StartsWith("data:")) { string dataJSON = line.Substring(5).Trim(); currentStreamingMessage.Data = DeserializeData(currentStreamingMessage.Event, dataJSON); yield return currentStreamingMessage; currentStreamingMessage = null; } } } } #endregion #region 리소스 해제하기 - Dispose() /// <summary> /// 리소스 해제하기 /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 리소스 해제하기 - Dispose(disposing) /// <summary> /// 리소스 해제하기 /// </summary> /// <param name="disposing">리소스 해제 여부</param> protected virtual void Dispose(bool disposing) { if(!this.disposed) { if(disposing) { if(this.client != null) { this.client.Dispose(); } this.client = null; this.disposed = true; } } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 데이터 역직렬화하기 - DeserializeData(eventType, dataJSON) /// <summary> /// 데이터 역직렬화하기 /// </summary> /// <param name="eventType">이벤트 타입</param> /// <param name="dataJSON">데이터 JSON</param> /// <returns>스트리밍 데이터 베이스</returns> private StreamingDataBase DeserializeData(string eventType, string dataJSON) { switch(eventType) { case "token" : return JsonConvert.DeserializeObject<StreamingDataToken >(dataJSON); case "result" : return JsonConvert.DeserializeObject<StreamingDataResult>(dataJSON); case "signal" : return JsonConvert.DeserializeObject<StreamingDataSignal>(dataJSON); default : return null; } } #endregion } |
▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
namespace TestProject; /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private ////////////////////////////////////////////////////////////////////// Event #region 클라이언트 메시지 도착시 처리하기 - client_MessageArrived(sender, message) /// <summary> /// 클라이언트 메시지 도착시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="message">이벤트 인자</param> private static void client_MessageArrived(object sender, StreamingMessage message) { if(message.Data is StreamingDataToken token) { Console.Write(token.Message.Content); } } #endregion ////////////////////////////////////////////////////////////////////// Function #region 스트리밍 메시지 리스트 요청하기 (비동기) - RequestStreamingMessageListAsync(client) /// <summary> /// 스트리밍 메시지 리스트 요청하기 (비동기) /// </summary> /// <param name="client">API 클라이언트</param> /// <returns>태스크</returns> private static async Task RequestStreamingMessageListAsync(APIClient client) { client.MessageArrived += client_MessageArrived; List<Message> messageList = [ new Message { Role = "system", Content = "당신은 서울 관광 전문 가이드 입니다." }, new Message { Role = "user" , Content = "서울 북촌에 있는 맛집을 3곳 추천해주세요."} ]; RequestMessage requestMessage = new RequestMessage(); requestMessage.MessageList = messageList; requestMessage.TopP = 0.8d; requestMessage.TopK = 0; requestMessage.MaximumTokenCount = 256; requestMessage.Temperature = 0.5d; requestMessage.RepeatPenalty = 5.0d; requestMessage.StopBefore = new List<string>(); requestMessage.IncludeAIFilters = true; requestMessage.Seed = 0; Console.WriteLine(messageList[1].Content); Console.WriteLine(); List<StreamingMessage> streamingMessageList = await client.RequestStreamingMessageListAsync(requestMessage); } #endregion #region 스트리밍 메시지 비동기 열거 가능형 요청하기 (비동기) - RequestStreamingMessageAsyncEnumerableAsync(client) /// <summary> /// 스트리밍 메시지 비동기 열거 가능형 요청하기 (비동기) /// </summary> /// <param name="client">API 클라이언트</param> /// <returns>태스크</returns> private static async Task RequestStreamingMessageAsyncEnumerableAsync(APIClient client) { List<Message> messageList = [ new Message { Role = "system", Content = "당신은 서울 관광 전문 가이드 입니다." }, new Message { Role = "user" , Content = "서울 북촌에 있는 맛집을 3곳 추천해주세요."} ]; RequestMessage requestMessage = new RequestMessage(); requestMessage.MessageList = messageList; requestMessage.TopP = 0.8d; requestMessage.TopK = 0; requestMessage.MaximumTokenCount = 256; requestMessage.Temperature = 0.5d; requestMessage.RepeatPenalty = 5.0d; requestMessage.StopBefore = new List<string>(); requestMessage.IncludeAIFilters = true; requestMessage.Seed = 0; Console.WriteLine(messageList[1].Content); Console.WriteLine(); await foreach(StreamingMessage message in client.RequestStreamingMessageAsyncEnumerableAsync(requestMessage)) { if(message.Data is StreamingDataToken token) { Console.Write(token.Message.Content); } } } #endregion #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> static async Task Main() { string clovaStudioAPIKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; // X-NCP-CLOVASTUDIO-API-KEY string apiGatewayAPIKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; // X-NCP-APIGW-API-KEY using APIClient client = new(clovaStudioAPIKey, apiGatewayAPIKey); //await RequestStreamingMessageListAsync(client); await RequestStreamingMessageAsyncEnumerableAsync(client); } #endregion } |