최근 LLM을 개발하고 활용하는 추세가 빠르게 확산되고 있다. Spring AI는 LangChain과 같이 이러한 LLM을 보다 쉽게 사용하도록 돕는 라이브러리. 이러한 흐름과 함께, Spring Boot 환경에서 Spring AI를 활용하면 LLM 기능을 간편하게 통합하여 개발할 수 있을 것 같아 정리 사용 과정을 정리해보려고 한다.
Ollama는 로컬에서 LLM 모델(Mistral, LLaMA, Gemma 등)을 쉽게 실행할 수 있도록 도와주는 플랫폼이다. Docker를 통해 설치가 가능하며 RESTful API를 통해 다양한 언어에서 접근할 수 있는 것이 장점. 개발 환경에서 빠르게 테스트하고 배포 없이 모델을 활용할 수 있다는 점에서 RAG 시스템이나 LLM 서비스 개발에 유용하다.
curl -fsSL https://ollama.com/install.sh | sh
ollama run mistral
build.gradle 또는 pom.xml에 Spring-AI 의존성 추가:
ext {
set('springAiVersion', "1.0.0")
}
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-model-ollama'
}
dependencyManagement {
imports {
mavenBom "org.springframework.ai:spring-ai-bom:${springAiVersion}"
}
}
application.yml 설정:
spring:
ai:
ollama:
base-url: http://localhost:11434
chat:
options:
model: gemma3:4b
temperature: 0.7
# 외 다른 옵션도 설정 가능 없으면 기본 값
모델은 ollama에서 공식으로 제공하는 gemma3:4b 를 사용하였다.
4b는 LLM 의 파라미터 수를 의미함.
ollama gemma3 페이지를 참고하여 여러 파라미터로 된 모델 및 양자화된 버전까지 선택하여 사용할 수 있다.
Spring AI 는 auto-configuration 이 제공되므로 의존성을 추가하고 간단한 application.yml 설정을 하면 바로 사용할 수 있다.
@RestController
@RequestMapping("/chat")
public class ChatController {
private final ChatClient chatClient;
public ChatController(ChatClient chatClient) {
this.chatClient = chatClient;
}
@PostMapping
public ResponseEntity<String> chat(@RequestBody String message) {
ChatResponse chatResponse = chatClient.prompt()
.user("Tell me a joke")
.call()
.chatResponse();
String res = chatResposne
.getResult().getOutput().getText();
return ResponseEntity.ok(res);
}
}
Spring-AI에서는 ChatClient라는 추상화를 제공하므로 이를 이용하면 용이하다. 위의 Controller에서 처럼 제공하는 API 를 통해 LLM 서버와 통신이 가능하다. 아래는 공식문서 내용을 발췌한 것이다.
call() return values
After specifying the call() method on ChatClient, there are a few different options for the response type.
String content(): returns the String content of the response
ChatResponse chatResponse(): returns the ChatResponse object that contains multiple generations and also metadata about the response, for example how many token were used to create the response.
ChatClientResponse chatClientResponse(): returns a ChatClientResponse object that contains the ChatResponse object and the ChatClient execution context, giving you access to additional data used during the execution of advisors (e.g. the relevant documents retrieved in a RAG flow).
entity() to return a Java type
entity(ParameterizedTypeReference type): used to return a Collection of entity types.
entity(Class type): used to return a specific entity type.
entity(StructuredOutputConverter structuredOutputConverter): used to specify an instance of a StructuredOutputConverter to convert a String to an entity type.
You can also invoke the stream() method instead of call().
curl -X POST http://localhost:8080/chat -H "Content-Type: text/plain" -d "안녕!"
"안녕하세요! 무엇을 도와드릴까요?"
이번 글에서는 Spring-AI와 Ollama를 이용해 가장 기본적인 챗봇 기능이 되는 지만 체크해 보았다. 다음 글에서는 Postgresql 에서 확장적으로 제공하는 PgVector DB 를 활용하여 데이터를 임베딩하고 RAG 를 구현하는 방법을 정리할 것이다.