https://zee0541.tistory.com/11
SpringBoot-챗Gpt openAPI 구현하기
호기심으로 챗GPT 으로 연결하여 상담사 챗팅 처럼 구현하고 싶어서 해봤다. https://platform.openai.com/api-keys챗gpt key 를 발급 받아야 한다. build.fradle implementation 'com.fasterxml.jackson.core:jackson-databind:2.
zee0541.tistory.com
코드 가 너무 길어 springBoot springAi 사용하면 코드가 간결해진다.
프로젝트 생성
- OpenAi
기본적으로 추가해야한다.
만약 성공하면
ext {
springAiVersion = '1.0.0-M4' // 실제 버전을 여기에 입력
}
dependencyManagement {
imports {
mavenBom "org.springframework.ai:spring-ai-bom:${springAiVersion}"
}
}
2개가 추가 된다.
Edit Configurations 들어간다.
창이 뜨면 Modify options 클릭 한다.
클릭
설정하면 된다..
설정하고 Run 하면 성공적으로 될것이다.
- 기존 프로젝트 에서 빌트 추가-
여기서.. springai 빌드 가 계속 추가 가 안되고
implementation 'org.springframework.ai:spring-ai-openai-spring-boot-starter' 버전이 없다고 한다.
이 해결을 하는데 1~2시간 걸렸다 ㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠ
그럼 추가 되는 방법 을 설명하겠습니다.(매우 간단했다.. 하하)
implementation 'org.springframework.ai:spring-ai-openai-spring-boot-starter:1.0.0-M4'
:1.0.0-M
이것만 추가 하고
repositories {
mavenCentral()
maven { url 'https://jitpack.io' }
maven { url 'https://repo.spring.io/milestone' } // Spring Milestone Repository
maven { url 'https://repo.spring.io/snapshot' } // Spring Snapshot Repository
}
추가하고
ext {
springAiVersion = '1.0.0-M4'
}
dependencyManagement {
imports {
mavenBom "org.springframework.ai:spring-ai-bom:${springAiVersion}"
}
}
이거는 무조건 필수 추가해한다.
이렇게 하면 정상적으로 등록된다.
config 패키지
@Configuration
public class AppConfig {
@Bean
public ChatClient chatClient(ChatClient.Builder chatClientBuilder) {
return chatClientBuilder.defaultAdvisors(
//메모리 어드바이저 설정
new MessageChatMemoryAdvisor(new InMemoryChatMemory())
).build();
}
}
/*
* ChatClient.Builder 를 받아와 빌더 객체를 생성
*
* defaultAdvisors 메서드를 호출해 MessageChatMemoryAdvisor를 설정 한다
* 여기서 MessageChatMemoryAdvisor는 대화 데이터의 메모리 관리와 관련된 역할
* InMemoryChatMemory를 통해 대화 데이터를 메모리에 저장하도록 지정
*/
ChatService
@Service
public class ChatService {
private final ChatClient chatClient;
public ChatService(ChatClient chatClient) {
this.chatClient = chatClient;
}
//기본적인 메세지 요청하는것
public String chat(String message){
return chatClient.prompt()
.user(message) // 사용자 메시지
.call() // api 호출 하는것
.content(); // gpt 응답
}
// 메시지 와 함께 요청
public String chatWithSystemMessage(String systemMessage, String userMessage){
return chatClient.prompt()
.system(systemMessage) // 시스템 역활 정의
.user(userMessage) // 사용자 메시지
.call()
.content();
}
public String chatJson(String message){
return chatClient.prompt()
.user(message)
.call()
.chatResponse()
.toString(); // json 으로 응답 변환
}
}
ChatController
@RestController
@RequestMapping("/api/chat")
public class ChatController {
private final ChatService chatService;
public ChatController(ChatService chatService) {
this.chatService = chatService;
}
//기본 메시지 요청
@GetMapping
public String chat(@RequestParam String message){
return chatService.chat(message);
}
// 메시지와 사용자 메시지 요청
@GetMapping("/")
public String chatWithSystemMessage(@RequestParam String systemMessage, @RequestParam String userMessage) {
return chatService.chatWithSystemMessage(systemMessage, userMessage);
}
// JSON 형식으로 응답 반환
@GetMapping("/json")
public String chatJson(@RequestParam String message) {
return chatService.chatJson(message);
}
}
이러면 백앤드 는 끝났다
document.addEventListener('DOMContentLoaded', function () {
console.log("대화창 스크립트 로드 완료");
// 대화창 토글
document.getElementById('chat-button').addEventListener('click', function () {
console.log("대화창 토글 버튼 클릭");
const chatContainer = document.getElementById('chat-container');
chatContainer.style.display = chatContainer.style.display === 'none' ? 'block' : 'none';
});
// 메시지 전송 처리
document.getElementById('send-button').addEventListener('click', async function () {
console.log("메시지 전송 시작");
const input = document.getElementById('chat-input');
const message = input.value.trim();
if (!message) {
console.log("빈 메시지, 전송 취소");
return;
}
// 사용자 메시지 화면에 추가
const messagesContainer = document.getElementById('chat-messages');
const userMessage = document.createElement('div');
userMessage.style.marginBottom = '10px';
userMessage.innerHTML = `<b>나:</b> ${message}`;
messagesContainer.appendChild(userMessage);
// 서버에 메시지 전송
try {
console.log("서버에 메시지 전송 중:", message);
const response = await fetch(`/api/chat?message=${encodeURIComponent(message)}`);
const responseData = await response.text();
console.log("서버 응답:", responseData);
// 서버 응답 추가
const botMessage = document.createElement('div');
botMessage.style.marginBottom = '10px';
botMessage.innerHTML = `<b>긱톡커:</b> ${responseData}`;
messagesContainer.appendChild(botMessage);
} catch (error) {
console.error("서버 요청 중 오류:", error);
const errorMessage = document.createElement('div');
errorMessage.style.marginBottom = '10px';
errorMessage.innerHTML = `<b>긱톡커:</b> 에러가 발생했습니다.`;
messagesContainer.appendChild(errorMessage);
}
// 입력 필드 초기화 및 스크롤 유지
input.value = '';
messagesContainer.scrollTop = messagesContainer.scrollHeight;
});
});
이렇게 하면 끝났다.. 정말 코드가 간결하다!
- 결과 -
'Spring Boot' 카테고리의 다른 글
SpringBoot-챗Gpt openAPI 구현하기 (2) | 2025.01.13 |
---|---|
Spring-boot 핸드폰 인증(Colsms + Redis) (2) | 2025.01.08 |
Spring-boot Gmail 임시비밀번호 발급 (0) | 2025.01.08 |
Spring-Boot session 으로 이용한 Google 로그인 api (6) | 2025.01.07 |
Spring-Boot KG-이니시스 결제 Api (2) | 2025.01.07 |