## `config` 작성 `ChatGPTClient` API 요청과 응답 처리 작업만 하기 때문에 따로 추가할 `Config`가 없다. ## `ChatGPTClientTest` 작성 ### 클래스 생성 ```java @SpringBootTest @TestPropertySource(locations = "classpath:test.properties") @Import(PromptTemplateTestConfig.class) public class ChatGPTClientTest { } ``` ### 의존성 주입 ```java @SpringBootTest @TestPropertySource(locations = "classpath:test.properties") @Import(PromptTemplateTestConfig.class) public class ChatGPTClientTest { @Autowired private ChatGPTClient client; @Autowired private PromptTemplateService service; } ``` - `ChatGPTClient` 인스턴스와 `PromptTemplateService` 인스턴스를 주입한다. `ChatGPTClient`는 테스트 대상이니 당연하고, `PromptTemplateService`는 템플릿 생성 기능을 사용하기 위해 주입한다. ### 메서드 작성 #### 주입 여부 확인 ```java @Test public void testServiceExistence(){ assertNotNull(service); } @Test public void testClientExistence(){ assertNotNull(client); } ``` #### ChatGPT API 요청 기능 테스트 ```java @Test public void testChat() throws JsonProcessingException { //Given String answer = "OBSIDIAN"; String content = "Say '%s'. Only say answer. Do not say anything else.".formatted(answer); //When String reply = client.chat(content); System.out.println(reply); //Then assertEquals(answer, reply); } ``` - **프롬프트** : `Say 'OBSIDIAN'. Only say answer. Do not say anything else.` - **예상 답변** : `OBSIDIAN` - `PromptTemplateService::chat`은 프롬프트를 문자열로 받고 ChatGPT API로 이를 요청한 다음, 응답에서 답변만 뽑아 문자열로 리턴하는 함수로 작성할 것이다. #### 템플릿을 통한 ChatGPT API 요청 기능 테스트 ```java @Test public void testChatByTemplate() throws TemplateException, IOException { //Given String content = "Say '${word1} is ${word2}!'. Only say answer. Do not say anything else."; PromptTemplate promptTemplate = PromptTemplate.builder() .id("temp") .content(content) .modifiedTime(LocalDateTime.now()) .build(); Map<String, String> map = new HashMap<>(); String word1 = "OBSIDIAN"; String word2 = "GOOD"; map.put("word1", word1); map.put("word2", word2); String answer = "OBSIDIAN is GOOD!"; //When service.create(promptTemplate); String reply = client.chatByTemplate("temp", map); //Then assertEquals(answer, reply); } ``` - 위 테스트 코드를 설명하자면, 1. 먼저 `${num1} + ${num2} = ? Only say answer. Do not say anything else.`라는 프롬프트 템플릿을 `template_example`이라는 이름으로 저장한다. 2. 그리고 `PromptTemplateService::chatByTemplate`을 통해 템플릿의 이름과 거기에 넣을 키워드 `map`을 인자로 전달한다. 3. 우리가 원하는 건 `PromptTemplateService`가 템플릿의 이름과 키워드를 통해 프롬프트 `1 + 2 = ? Only say answer. Do not say anything else.`를 생성하고, 이를 ChatGPT API로 보내는 것이다. 정상적으로 보내졌다면 `3`이라는 답변을 응답 받을 수 있을 것이다. 4. 응답에 적힌 답변과 예상 답변을 비교한다. ## [[7. Spring WebClient를 통한 Client 구현|클라이언트 코드 작성]] ![[7. Spring WebClient를 통한 Client 구현#클래스 생성 및 의존성 주입]] ![[7. Spring WebClient를 통한 Client 구현#`chat`]] ![[7. Spring WebClient를 통한 Client 구현#`chatByTemplate`]] ## 테스트 결과 확인 ![[Pasted image 20231213200654.png]]