■ HttpClient 클래스를 사용해 네이버 HyperCLOVA X와 통신하는 방법을 보여준다.
▶ 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 } |
▶ 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 |
using System.Text; using System.Net.Http.Headers; using Newtonsoft.Json; namespace TestProject; /// <summary> /// API 클라이언트 /// </summary> public class APIClient : IDisposable { //////////////////////////////////////////////////////////////////////////////////////////////////// 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 채팅 요청하기 - RequestChat(requestMessage) /// <summary> /// 채팅 요청하기 /// </summary> /// <param name="requestMessage">요청 메시지</param> /// <returns>응답 메시지 태스크</returns> public async Task<ResponseMessage> RequestChat(RequestMessage requestMessage) { 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 StringContent(requestJSON, Encoding.UTF8, "application/json"); HttpResponseMessage responseMessage = await this.client.PostAsync(BASE_URL, content); responseMessage.EnsureSuccessStatusCode(); string responseString = await responseMessage.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<ResponseMessage>(responseString); } #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 } |
▶ 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 |
namespace TestProject; /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #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 APIClient(clovaStudioAPIKey, apiGatewayAPIKey); List<Message> messageList = [ new Message { Role = "system", Content = "당신은 서울 관광 전문 가이드 입니다." }, new Message { Role = "user" , Content = "서울 북촌에 있는 맛집을 3곳 추천해주세요."} ]; RequestMessage request = new RequestMessage(); request.MessageList = messageList; request.TopP = 0.8d; request.TopK = 0; request.MaximumTokenCount = 256; request.Temperature = 0.5d; request.RepeatPenalty = 5.0d; request.StopBefore = new List<string>(); request.IncludeAIFilters = true; request.Seed = 0; ResponseMessage responseMessage = await client.RequestChat(request); Console.WriteLine(responseMessage.Result.Message.Content); } #endregion } |