Swagger와 Flask-RESTX를 통해 자연어 명령을 LLM을 통해 시스템 명령으로 바꾸는 API 만들어 보았다.

이 글에서는 LLM의 추론 결과를 웹 API로 제공하고, Swagger UI를 통해 직관적으로 테스트할 수 있도록 하는 방법을 소개하고자 한다. 이전 글에서 LLM 모델을 활용해, 자연어로 주어진 명령을 시스템 함수 호출 형태로 변환하는 로직을 구현했었다.
2025.03.12 - [LLM/Project] - [Project] LLM을 활용한 시스템 인터페이스 만들어보기
[Project] LLM을 활용한 시스템 인터페이스 만들어보기
LLM 모델을 기반으로 반도체 검사 명령어를 이해하는 인터페이스 구성하기 최근 대규모 언어 모델(LLM)의 활용 범위가 넓어지면서, 이를 특정 도메인에 특화시켜 적용하는 흐름이 활발해졌다.이
c0mputermaster.tistory.com
이번 글에서는 이를 Flask 기반의 API로 감싸고, Flask-RESTX를 활용해 Swagger 문서를 생성해보았다.
환경
- Python 3.10+
- Flask
- Flask-RESTX (Swagger UI 포함)
- PyTorch
1. Flask-RESTX란?
Flask-RESTX는 Flask 위에서 작동하는 REST API 확장 라이브러리이다.
- Swagger(OpenAPI) 문서 자동 생성
- Namespace로 API 분리
- 입력/출력 모델 검증
- 데코레이터 기반 라우팅 및 응답 구성
flask 서버 라이브러리는 Flask-restful, flask-restplus, flask-restx 3가지 종류가 존재한다. Flask-restful은 꾸준히 업데이트를 하고 있는 반면에, restplus는 어느 시점에 업데이트가 끊겨서 restx가 restplus를 이어받아 업데이트하고 있다고 한다.
[Flask] Flask rest API 라이브러리 비교
TL:DR (요약) flask-restful 라이브러리로 Flask-restful, flask-restplus, flask-restx 3가지 종류가 존재한다. Flask-restful은 꾸준히 업데이트를 하고 있는 반면에, restplus는 어느 시점에 업데이트가 끊겨서 restx가 r
tw0226.tistory.com
2. api 구성
- /instruct: 명령어 텍스트 → LLM으로 함수 호출 반환
key나 api인증을 제외하고 간단하게 호출과 반환만 가능하도록 구성하였다.
app = Flask(__name__)
api = Api(app, version='1.1', title='반도체 검사 시스템 인터페이스',
description='LLM 명령 실행 및 Intent 분류')
- Api()로 전체 Swagger 설정
- version, title, description 등은 Swagger UI에 표시됨
3. /instruct - LLM 명령 실행
namespace 정의
ns_instruct = api.namespace('instruct', description='LLM 명령 실행')
- instruct/ 경로로 LLM 실행 API 등록
- Swagger UI에는 "LLM 명령 실행" 섹션으로 구분됨
입력 모델
input_model = api.model('InputModel', {
'text': fields.String(required=True, description='명령어 텍스트')
})
- 요청 JSON의 형식을 정의 (예: { "text": "검사 시작해줘" })
응답 모델
output_model = api.model('OutputModel', {
'output': fields.String(description='LLM 응답 함수 호출 결과'),
'elapsed_time': fields.Float(description='응답 시간(초)'),
'gpu_memory': fields.Nested(gpu_model)
})
- marshal_with(output_model)로 출력 자동 포맷
API 구현
@ns_instruct.route('/')
class Instruct(Resource):
@ns_instruct.expect(input_model)
@ns_instruct.marshal_with(output_model)
def post(self):
"""사용자 명령어를 입력받아 함수 호출 형식으로 응답"""
user_input = api.payload['text']
return run_model(user_input)
4. Swagger UI 사용법
서버를 실행하면 기본 주소 http://localhost:5000/에서 자동 생성된 Swagger UI가 http://localhost:5000/에 나타남
- 각 namespace(예: instruct, classify)를 클릭하면 하위 API가 표시됨
- POST 버튼 → Try it out → 값을 입력 → Execute 클릭
- 응답 JSON이 아래에 자동 표시됨
from flask import Flask
from flask_restx import Api, Resource, fields
from model_runner import run_model
from intent_classifier import classify_text
app = Flask(__name__)
api = Api(app, version='1.1', title='시스템 인터페이스 API 테스트',
description='LLM 명령 실행 및 Intent 분류')
# LLM 명령 실행 namespace
ns_instruct = api.namespace('instruct', description='LLM 명령 실행')
input_model = api.model('InputModel', {
'text': fields.String(required=True, description='명령어 텍스트')
})
gpu_model = api.model('GpuModel', {
'allocated_mb': fields.Float(description='사용된 GPU 메모리'),
'reserved_mb': fields.Float(description='예약된 GPU 메모리')
})
output_model = api.model('OutputModel', {
'output': fields.String(description='LLM 응답 함수 호출 결과'),
'elapsed_time': fields.Float(description='응답 시간(초)'),
'gpu_memory': fields.Nested(gpu_model)
})
@ns_instruct.route('/')
class Instruct(Resource):
@ns_instruct.expect(input_model)
@ns_instruct.marshal_with(output_model)
def post(self):
"""사용자 명령어를 입력받아 함수 호출 형식으로 응답"""
user_input = api.payload['text']
return run_model(user_input)
#Intent 분류 namespace
ns_classify = api.namespace('classify', description='문장 intent 분류')
classify_input_model = api.model('ClassifyInput', {
'text': fields.String(required=True, description='분류할 문장')
})
classify_output_model = api.model('ClassifyOutput', {
'label': fields.String(description='예측된 라벨'),
'score': fields.Float(description='예측 확률')
})
@ns_classify.route('/')
class Classify(Resource):
@ns_classify.expect(classify_input_model)
@ns_classify.marshal_with(classify_output_model)
def post(self):
"""문장을 분류"""
text = api.payload['text']
return classify_text(text)
# 서버 실행
if __name__ == '__main__':
app.run(debug=True)
정리
Flask-RESTX는 Swagger UI를 자동으로 제공하면서도 간단하게 API를 만들 수 있었다. LLM 기반의 시스템 인터페이스를 웹 서비스 형태로 제공하고자 할 때 매우 유용한 도구였다.
'Technology Notes' 카테고리의 다른 글
| [Server] Window PuTTY로 원격 접속하기 (0) | 2025.05.07 |
|---|---|
| [Deep Learning] 딥러닝 모델 모바일 최적화 알아보기 (0) | 2025.04.13 |
| [Deep Learning] Anomaly Detection(이상치 탐지)를 알아보자 (0) | 2025.04.09 |
| [Android] Android Emulator ControlService 오류 1062 (0) | 2025.04.08 |
| [Deep Learning] CNN(합성곱 신경망) 정리해보기 (0) | 2025.04.03 |