Spring/Spring AI

Spring AI - 대화 맥락 기억하기 - defaultAdvisors 활용

Griotold 2025. 4. 15. 11:44

1. 문제 상황

 

어린이용 chatGPT를 만드는 프로젝트를 진행중인데,,,

문제가 생겼다.

LLM이 이전 대화의 맥락을 기억하지 못하는 것이었다.

보통 chatGPT를 사용하면 기본적으로 이전 대화 내역을 기억해서 적절한 응답을 내려준다.

근데, API 형태로 chatGPT를 사용하면 이전 대화 내역을 기억하지 못하는 문제를 발견했다.

개발 환경은 Spring AI 1.0.0-M6, Java 17, gpt-4o-mini 이다.

 

2. 문제 상황 확인

"고양이는 왜 그루밍을 할까?"

에 대한 질문을 던졌을 때 적절한 응답을 받았다. 

내가 AI에게 요청한 것은 답변을 받고 꼬리 질문을 9개를 받는 것이었다.

 

꼬리 질문 중에 "그루밍을 하는 다른 동물은 없을까?" 를 요청하고 답변을 받아 보았다.

 

이전에 고양이에 대해서 이야기하고 다른 동물을 요구했으면 고양이 이외의 동물을 답변해야 하는데, 

또 다시 고양이를 답변하는 문제가 발생한 것이다.

대화형 AI 서비스에 맥락 유지는 사용자 경험을 결정하는 핵심 요소라고 하는데...

 

3. defaultAdvisors

Spring AI의 defaultAdvisors 를 활용하면 복잡한 대화 흐름 관리 로직을 간소화하면서도

사용자 맞춤형 경험을 제공할 수 있다고 한다.

 

advisor는

1. 대화 흐름에 개입하여 메시지를 가공하거나,

2. 메모리(대화 맥락) 관리,

3. 프롬프트 수정 등 다양한 부가 기능을 수행하는 컴포넌트다.

 

아래처럼 적용할 수 있는데

 

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ChatClientConfig {

    @Bean
    public ChatClient chatClient(ChatClient.Builder builder) {
        return builder
                .defaultAdvisors(new MessageChatMemoryAdvisor(new InMemoryChatMemory()))
                .build();
    }
}

 

MessageChatMemoryAdvisor 에 InMemoryChatMemory() 구현체를 주입해줬다.

InMemoryChatMemmory 말고도 다양한 것이 있는데, 

 

서버 재시작시 기록이 소멸되면 안되는 상황에서는 InMemory 말고 다른 걸 사용하면 될 것 같다.

이렇게 하고 테스트를 해보았는데,

 

4. 적용 후 

 

일단 첫 질문은 동일하게 "고양이는 왜 그루밍을 할까?"

를 물어보았고, 곧바로 "그루밍을 하는 다른 동물은 없을까?" 를 물어보았다.

고양이 이외의 동물들을 답변으로 받았다!

 

5. Advisor가 프롬프트를 수정하는 방식

Advisor는 대화 맥락을 기억하거나 프롬프트를 가공하거나 대화 흐름을 제어 및 후처리를 한다.

Advisor 가 어떻게 프롬프트를 가공 및 수정하는지 자세히 알아보자.

 

5 - 1. 프롬프트를 사용한 chatClient 요청

// 프롬프트 템플릿 생성
PromptTemplate promptTemplate = new PromptTemplate(moriPromptResource);
Prompt prompt = promptTemplate.create(Map.of("childAgeGroupDescription", childAgeGroupDescription));

// 프롬프트 실행
AiAnswer aiAnswer = chatClient.prompt(prompt)
        .user(answerRequest.content())  // 사용자 메시지 추가
        .call()
        .entity(AiAnswer.class);

 

 

위와 같이 요청하게 되면 ChatClient 에 MessageChatMemoryAdvisor 가 등록되어 있기 때문에,

모든 chatClient 호출 시 Advisor가 프롬프트를 가공한다. 

구체적으로 살펴 보면,

 

5 - 2. 첫 번째 질문

사용자 입력: "고양이는 왜 그루밍을 할까?"

 

프롬프트 가공 결과

[Role]
당신은 {childAgeGroupDescription} 어린이를 위한 친절한 가정교사야.

[Rule]
- 모든 답변과 질문은 반드시 **반말**로 작성해줘
- ... (이하 생략)

[Context Handling]
- 이전 대화 맥락은 반드시 참조해서 답변해야 해.
- ... (이하 생략)

[Format]
아래는 질문 예시 및 적절한 답변이야.
...

[현재 질문]
고양이는 왜 그루밍을 할까?

첫 질문이므로 대화 기록 없이 템플릿과 현재 질문만 포함된 형태다.

 

5 - 3. 두 번째 질문

사용자 입력: "그루밍을 하는 다른 동물은 없을까?"

 

프롬프트 가공 결과:

[Role]
당신은 {childAgeGroupDescription} 어린이를 위한 친절한 가정교사야.

[Rule]
- 모든 답변과 질문은 반드시 **반말**로 작성해줘
- ... (이하 생략)

[Context Handling]
- 이전 대화 맥락은 반드시 참조해서 답변해야 해.
- ... (이하 생략)

[Format]
아래는 질문 예시 및 적절한 답변이야.
...

[대화 기록]
User: 고양이는 왜 그루밍을 할까?
Assistant: 답변1: 고양이는 몸을 깨끗하게 하려고 그루밍을 해. 답변2: 그루밍을 하면 털에 묻은 먼지나 이물질을 없앨 수 있어. 답변3: 그루밍은 스트레스를 줄이고 기분을 좋게 해줘.

[현재 질문]
그루밍을 하는 다른 동물은 없을까?

 

두 번째 질문부터 대화 기록이 추가가 된다.

 

6. 마무리

Spring AI, defaultAdvisors를 활용해서 대화 맥락을 기억하게 설정해줬다.

없었으면, 데이터베이스에서 조회해서 프롬프트에 넣어주는 등의 번거로운 작업을 했어야 했는데,

다행히도 유능한 선배 개발자들 덕분에 쉽게 개발할 수 있었다. 

고마워요.

 

References

https://docs.spring.io/spring-ai/reference/api/advisors.html

 

Advisors API :: Spring AI Reference

The Spring AI Advisors API provides a flexible and powerful way to intercept, modify, and enhance AI-driven interactions in your Spring applications. By leveraging the Advisors API, developers can create more sophisticated, reusable, and maintainable AI co

docs.spring.io

 

https://www.youtube.com/watch?v=6VdM1MOOMrw&list=PLZV0a2jwt22uoDm3LNDFvN6i2cAVU_HTH&index=13

https://spring.io/blog/2024/10/02/supercharging-your-ai-applications-with-spring-ai-advisors

 

Supercharging Your AI Applications with Spring AI Advisors

In the rapidly evolving world of artificial intelligence, developers are constantly seeking ways to enhance their AI applications. Spring AI, a Java framework for building AI-powered applications, has introduced a powerful feature: the Spring AI Advisors.

spring.io