실무에 바로 적용하는 Spring AI: Spring 서비스에 챗봇·RAG·MCP 도입하기
practice-building-chat-api-with-openai
✅ 1. build.gradle 수정
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-webmvc'
// implementation 'org.springframework.ai:spring-ai-starter-model-ollama'
implementation 'org.springframework.ai:spring-ai-starter-model-openai'
testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
✅ 2. application.yml 수정
spring:
application:
name: chat
ai:
openai:
# 환경변수 값
api-key: ${OPENAI_API_KEY}
chat:
# 실제 사용할 대화형 AI의 모델명
model: openai/gpt-4.1-nano
# GitHub Models 서버로 요청을 보냄
base-url: https://models.github.ai/inference
# 세부 API 경로
completions-path: /chat/completions
✅ 3. 환경 변수 설정
- 환경 변수 추가를 위해 Environment variables 클릭
- Value : Github에서 발급받은 토큰 값 입력
✅ 4. Controller 구현
- 우리가 AI와 쉽게 소통할 수 있도록 Spring AI에서 제공하는 객체가 Chat client
ChatController.java
package com.jscode.chat.controller;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ChatController {
private final ChatClient chatClient;
public ChatController(ChatClient.Builder chatClientBuilder){
this.chatClient = chatClientBuilder.build();
}
@GetMapping("/ai")
public String generation(String userPrompt){
return this.chatClient.prompt()
.user(userPrompt)
.call()
.content(); // 받아온 응답 중 메타데이터는 버리고, 순수 content만 추출!
}
}