LLM 연동 샘플링 기록 1

김해준's avatar
Mar 09, 2026
LLM 연동 샘플링 기록 1

0) 문서 목적

이 문서는 LLM 연동 샘플링의 1단계(챕터 1) 에서 무엇을 했고 무엇을 확인했는지 기록한다.
  • 범위: Spring Boot에서 LLM 질의/응답 왕복 검증
  • 기준: Postman으로 실제 요청/응답 확인
  • 제외: DB 저장, Repository, 고도화된 운영 구조

1) 챕터 1 결과 요약

챕터 1의 핵심 목표였던 “연동 성공 여부 확인”은 완료됐다.
  • 엔드포인트: POST /api/llm/chat
  • HTTP 호출: HttpURLConnection
  • JSON 처리: Gson
  • 응답 파싱: choices[0].message.content
  • 검증: Postman 수동 테스트

2) 진행 과정

2-1. 최소 뼈대 생성

복잡도 최소화를 위해 Controller + Service + DTO만 구성했다.
  • LlmController
  • LlmService
  • LlmChatRequest
  • LlmChatResponse
추가 정책: - DTO는 record 대신 일반 클래스 사용 - 생성자/접근자는 Lombok 어노테이션으로 단순화

2-2. Mock 단계 검증

실제 외부 API 호출 전, 내부 라우팅/DTO/요청 흐름부터 확인했다.
  1. LlmService.chat(prompt)에서 mock 응답 반환
  1. POST /api/llm/chat 연결
  1. Postman으로 요청/응답 확인

2-3. 실호출 단계 전환

MOCK_ENABLED=false로 전환 후 OpenAI API 실호출을 확인했다.
  • 호출 URL: POST https://api.openai.com/v1/chat/completions
  • 요청 구조:
{ "model": "gpt-4o-mini", "messages": [ { "role": "user", "content": "안녕" } ] }
  • 응답에서 choices[0].message.content를 추출해 API 응답으로 반환

3) 챕터 1의 현재 코드 상태

API

  • POST /api/llm/chat
  • prompt가 null/blank면 400 Bad Request

서비스

  • MOCK_ENABLED 상수로 mock/실호출 분기
  • 실호출 시 HttpURLConnection + Gson으로 OpenAI 호출
중요: - 현재 모드 전환은 “설정 파일 토글”이 아니라 코드 상수(MOCK_ENABLED) 변경 방식이다.

3-1) 핵심 코드 스니펫

아래 코드는 챕터 1에서 팀이 바로 이해해야 할 핵심 포인트만 발췌한 것이다.

Controller: 입력 검증 + 서비스 호출

@PostMapping("/chat") public LlmChatResponse chat(@RequestBody LlmChatRequest request) { if (request == null || request.getPrompt() == null || request.getPrompt().isBlank()) { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "prompt 값은 필수입니다."); } String answer = llmService.chat(request.getPrompt()); return new LlmChatResponse(answer); }

Service: 모드 분기 + 실호출 진입

private static final String BASE_URL = "https://api.openai.com/v1"; private static final String MODEL = "gpt-4o-mini"; private static final String API_KEY = "your-api-key"; private static final boolean MOCK_ENABLED = false; public String chat(String prompt) { if (MOCK_ENABLED) { return "[MOCK] " + prompt; } if (API_KEY.isBlank()) { throw new IllegalStateException("API_KEY가 비어 있습니다. LlmService에 값을 설정해 주세요."); } // HttpURLConnection + Gson으로 OpenAI 호출 // POST /v1/chat/completions ... }

Service: 요청 JSON 생성 포인트

JsonObject requestBody = new JsonObject(); requestBody.addProperty("model", MODEL); JsonObject message = new JsonObject(); message.addProperty("role", "user"); message.addProperty("content", prompt); JsonArray messages = new JsonArray(); messages.add(message); requestBody.add("messages", messages);

Service: 응답 파싱 핵심 (choices[0].message.content)

private String extractContent(String responseBodyText) { JsonObject root = gson.fromJson(responseBodyText, JsonObject.class); if (root == null || !root.has("choices")) { throw new IllegalStateException("LLM 응답 형식이 올바르지 않습니다."); } JsonArray choices = root.getAsJsonArray("choices"); if (choices == null || choices.isEmpty()) { throw new IllegalStateException("LLM 응답에 choices가 없습니다."); } JsonObject firstChoice = choices.get(0).getAsJsonObject(); JsonObject message = firstChoice.getAsJsonObject("message"); if (message == null || !message.has("content")) { throw new IllegalStateException("LLM 응답의 content가 없습니다."); } String content = message.get("content").getAsString(); if (content == null || content.isBlank()) { throw new IllegalStateException("LLM 응답의 content가 비어 있습니다."); } return content; }

4) 예외 처리 및 검증

방어한 실패 케이스

  • API 키 누락
  • HTTP 상태코드 비정상(2xx 아님)
  • 응답 구조 이상
    • choices 없음
    • choices 빈 배열
    • message.content 없음
    • content 공백

검증 근거

  • 테스트 클래스: LlmServiceExtractContentTest
  • 검증 항목:
    • 정상 응답 파싱
    • 위 4개 예외 케이스 발생 확인

5) 수동 테스트(Postman) 기록

  • URL: http://localhost:8090/api/llm/chat
  • Method: POST
  • Body:
{ "prompt": "오늘 날씨 느낌으로 짧은 문장 하나 써줘" }

6) 스크린샷 삽입 위치

6-1. Postman 요청 화면

notion image
Postman 요청

6-2. 성공 응답 화면

notion image
Postman 성공 응답

6-3. 400 응답 화면(빈 prompt)

notion image
Postman 400 응답

참고 문서

  • Chat Completions API Reference
  • Responses vs Chat Completions Guide

 
Share article