Langchain #2 RAG 기반 LLM API 서버 구축

Langchain #2 RAG 기반 LLM API 서버 구축 #

#2025-09-23


1 #

#1 작업 위치 설정

# 1. 작업 위치
$ pwd
/Users/yshmbid/Documents/home/github/MLops/template/#10.code

# 2. 파일 확인
$ ls
__pycache__                     practice_LLM_App_main.py
practice_LLM_App_front.vue

#

#2 백엔드 띄우기

# 3. 백엔드 띄우기
$ uvicorn practice_LLM_App_main:app --port 8005 --reload
INFO:     Will watch for changes in these directories: ['/Users/yshmbid/Documents/home/github/MLops/template/#10.code']
INFO:     Uvicorn running on http://127.0.0.1:8005 (Press CTRL+C to quit)
INFO:     Started reloader process [7018] using StatReload

🖥 CPU 환경에서 로드합니다.
`torch_dtype` is deprecated! Use `dtype` instead!
Device set to use mps:0
INFO:     Started server process [7020]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
image

#

#3 프론트 띄우기

# 4. 프론트 수행
# 새 터미널에서
$ pwd
/Users/yshmbid/Documents/home/github/MLops/template/#10.code

$ ls
__pycache__                     practice_LLM_App_main.py
practice_LLM_App_front.vue

# 5. 설치
$ npm install -g @vue/cli
$ vue create llm-chat-vue
$ ls
__pycache__                     llm-chat-vue                    practice_LLM_App_front.vue      practice_LLM_App_main.py
$ cd llm-chat-vue
$ ls
README.md               jsconfig.json           package-lock.json       public                  vue.config.js
babel.config.js         node_modules            package.json            src
$ cd src
$ ls
App.vue         assets          components      main.js

여기서 App.vue를 practice_LLM_App_front.vue의 내용으로 수정하기.

# 6. 프론트앤드 실행
$ npm install axios
image

#

2. RAG 기반 LLM API 서버 구축 #

#1 위치 설정, swagger ui 띄우기

# 1. 위치 설정
$ pwd
/Users/yshmbid/Documents/home/github/MLops/template

# 2. 실행
$ uvicorn practice_RAG_App_main_fixed:app --port 8003 --reload

## 사용 방법 요약
# 1. 서버 실행 후, 자동으로 SQLite 인-메모리 DB가 초기화
# 2. GET /db-tables로 샘플 테이블(customers, products) 확인
# 3. POST /upload-dbtable?table=customers → 내부 벡터 인덱스 생성
# 4. POST /rag-query
#    {"prompt":"Acorn Ltd의 세그먼트는?","source":"internal"}
#    데이터에 없는 질문은 정확히 차단되어 "지식베이스에서 답을 찾을 수 없습니다." 반환
#5. 빠르게 점검하려면 GET /selftest-internal 호출'''
image

cf) 패키지 버전 확인

$ conda list torch
# packages in environment at /opt/anaconda3/envs/rag3:
# Name                    Version                   Build  Channel
libtorch                  2.7.1           cpu_mkl_hd81324f_102    conda-forge
pytorch                   2.7.1           cpu_mkl_py311_hec6b2c5_102    conda-forge

$ conda list transformers
# packages in environment at /opt/anaconda3/envs/rag3:
# Name                    Version                   Build  Channel
sentence-transformers     5.1.1                    pypi_0    pypi
transformers              4.56.2                   pypi_0    pypi

$ conda list sentence-transformers
# packages in environment at /opt/anaconda3/envs/rag3:
# Name                    Version                   Build  Channel
sentence-transformers     5.1.1                    pypi_0    pypi

#

#2 실습 수행

  1. 서버 실행 및 초기화
$ uvicorn practice_RAG_App_main_fixed:app --port 8003 --reload
  • 포트 8003에서 FastAPI 서버 실행
  • 시작 시점에 SQLite 인메모리 DB(customers, products)가 자동 생성됨
  • 벡터스토어 상태를 확인하면?
ℹ️ 내부 벡터 인덱스가 아직 없습니다. /upload-dbtable 로 생성하세요.
ℹ️ 외부 벡터 인덱스가 아직 없습니다. /upload-topic 으로 생성하세요.
ℹ️ PDF 벡터 인덱스가 아직 없습니다. /upload-paper 로 생성하세요.
  • 아직 어떤 벡터DB도 초기화되지 않은 상태.

#

  1. PDF 업로드 및 벡터화
  • 엔드포인트: POST /upload-paper

  • Swagger UI image

  • 로그

    • PDF(paper-attention.pdf)를 업로드하면 RecursiveCharacterTextSplitter로 쪼개고, OpenAI 임베딩을 적용하여 FAISS에 저장해서 VECTORSTORE_PDF 초기화.

#

  1. 내부 DB 테이블 확인
  • 엔드포인트: GET /db-tables

  • Swagger UI image

  • 로그

    • { “tables”: [“customers”, “products”] }
    • 인메모리 SQLite에 두 개의 샘플 테이블(customers, products)이 준비되어 있음을 확인

#

  1. 내부 테이블 벡터화
  • 엔드포인트: POST /upload-dbtable?table=customers

  • Swagger UI image

  • 로그

    • customers 테이블 데이터가 벡터화되어 VECTORSTORE_INTERNAL 생성

#

  1. 외부 웹 검색 데이터 벡터화
  • 엔드포인트: POST /upload-topic?topic=생성형 AI

  • Swagger UI image

  • 로그

    • Naver 뉴스 API를 통해 생성형 AI 관련 기사 20개를 크롤링 -> OpenAI 임베딩 적용 -> VECTORSTORE_EXTERNAL 생성 완료.

#

  1. RAG 질의
  • 엔드포인트: POST /rag-query

  • Swagger UI

  • 로그

    • 설명: 외부 벡터스토어에서 문맥을 검색 -> LLM(ChatGPT API, gpt-4o)을 통해 요약 답변을 생성.
    • 출처 표기도 괄호 형태로 포함시켜 “환각 최소화 + 근거 제시” 방식으로 동작.

#

  1. 내부 파이프라인 셀프 테스트
  • 엔드포인트: GET /selftest-internal

  • Swagger UI image image

  • 설명

    • 실제 데이터 존재: “Enterprise” 반환
    • 존재하지 않는 속성: “지식베이스에서 답을 찾을 수 없습니다.”
    • 스키마 무관 질문(Attention?): “지식베이스에서 답을 찾을 수 없습니다.”
      • 환각 억제 규칙이 잘 작동함을 보여줌.

#

  • internal로 해보기
image image
  • pdf로 해보기 image image

#