Spring-AI로 LLM 사용해보기

twonezero·2025년 6월 7일
0

SpringAI

목록 보기
1/2
post-thumbnail

최근 LLM을 개발하고 활용하는 추세가 빠르게 확산되고 있다. Spring AI는 LangChain과 같이 이러한 LLM을 보다 쉽게 사용하도록 돕는 라이브러리. 이러한 흐름과 함께, Spring Boot 환경에서 Spring AI를 활용하면 LLM 기능을 간편하게 통합하여 개발할 수 있을 것 같아 정리 사용 과정을 정리해보려고 한다.

🔍 목표

  • Ollama 로컬 모델을 활용하여 Spring-AI 기반의 간단한 챗봇 구현
  • Spring Boot 프로젝트에서 LLM을 연동하는 기초 흐름 이해

🧠 Ollama란?

Ollama는 로컬에서 LLM 모델(Mistral, LLaMA, Gemma 등)을 쉽게 실행할 수 있도록 도와주는 플랫폼이다. Docker를 통해 설치가 가능하며 RESTful API를 통해 다양한 언어에서 접근할 수 있는 것이 장점. 개발 환경에서 빠르게 테스트하고 배포 없이 모델을 활용할 수 있다는 점에서 RAG 시스템이나 LLM 서비스 개발에 유용하다.


⚙️ 환경 설정

1. Ollama 설치

  • Ollama 설치는 공식 홈페이지에서 간편하게 설치가 가능하고, Mac 유저또는 Windows는 git bash를 통해 아래와 같이 터미널에서 설치 후 사용해 볼 수 있다. 자세한 건 Ollama 공식홈페이지 참고
curl -fsSL https://ollama.com/install.sh | sh
ollama run mistral

2. Spring Boot 프로젝트 설정

  • Spring-AI 1.0.0 이 release 되었으므로 사용하는 것이 좋다. Spring initailizer 에서 간편하게 의존성 추가할 수 있다. 다른 필요한 의존성들 또한 Spring initializer 에서 추가 가능하다.
  • 주의할 점: SpringAI 1.0.0 이전의 버전들은 라이브러리의 모듈 이름 등의 변화가 있으니 잘 체크해보고 넣어야 함.

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}"
  }
}

Ollama 를 사용하기 위한 프로젝트 설정

  • 공식 홈페이지를 참고하면 각 LLM 서빙 프레임워크 및 API 제공자에 맞게 설정 및 사용 방법이 나와 있다.
    참고: Ollama Chat

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 페이지를 참고하여 여러 파라미터로 된 모델 및 양자화된 버전까지 선택하여 사용할 수 있다.


💬 간단한 Chat API 구현

Spring AI 는 auto-configuration 이 제공되므로 의존성을 추가하고 간단한 application.yml 설정을 하면 바로 사용할 수 있다.

1. ChatController 에서 바로 테스트

@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);
        
    }
}

2. ChatClient 인터페이스 활용

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 를 구현하는 방법을 정리할 것이다.


🗓️ 다음 글 예고

  • 📦 PgVector와 벡터 DB 연동하기
  • 🔍 문서 기반 QnA 시스템: RAG 기본 개념 및 구현
  • 📂 Document ETL Pipeline 설계

profile
큰 그림을 보려 노력하는 백엔드 개발자입니다😊

0개의 댓글