project/LLM + RAG + Ollama + NestJS 백엔드 연동 실습
📘 시리즈: LLM + RAG + Ollama + NestJS 백엔드 연동 실습 3. NestJS에서 Ollama와 통신하는 REST API 만들기
octo54
2025. 6. 20. 11:42
반응형
📘 시리즈: LLM + RAG + Ollama + NestJS 백엔드 연동 실습
3. NestJS에서 Ollama와 통신하는 REST API 만들기
🎯 목표
이번 글에서는 NestJS로 만든 백엔드 서버에서
로컬에 실행된 Ollama 모델에 질문을 보내고,
LLM의 응답을 받아 API로 전달하는 기본 구조를 구현합니다.
🧱 프로젝트 구조 미리보기
src/
┣ llm/
┃ ┣ llm.controller.ts 👈 API endpoint
┃ ┣ llm.service.ts 👈 Ollama와 통신 로직
┃ ┗ dto/
┃ ┗ ask.dto.ts 👈 요청 형태 정의
┗ app.module.ts
🔧 1. LLM 모듈 생성
nest generate module llm
nest generate controller llm
nest generate service llm
📮 2. DTO 정의 (ask.dto.ts)
export class AskDto {
question: string;
}
🔌 3. Ollama 통신 서비스 (llm.service.ts)
반응형
import { Injectable } from '@nestjs/common';
import axios from 'axios';
@Injectable()
export class LlmService {
async askQuestion(prompt: string): Promise<string> {
const response = await axios.post(
'http://localhost:11434/api/generate',
{
model: 'mistral', // 또는 llama2, gemma 등
prompt: prompt,
stream: false,
},
);
return response.data.response;
}
}
🌐 4. 컨트롤러 구성 (llm.controller.ts)
import { Controller, Post, Body } from '@nestjs/common';
import { AskDto } from './dto/ask.dto';
import { LlmService } from './llm.service';
@Controller('llm')
export class LlmController {
constructor(private readonly llmService: LlmService) {}
@Post('ask')
async ask(@Body() askDto: AskDto) {
const response = await this.llmService.askQuestion(askDto.question);
return { answer: response };
}
}
▶️ 5. API 호출 테스트
Postman이나 Curl로 다음 요청을 보냅니다:
curl -X POST http://localhost:3000/llm/ask \
-H "Content-Type: application/json" \
-d '{"question": "What is a vector database?"}'
✅ 응답 예시:
{
"answer": "A vector database is a type of database..."
}
🧪 Tip: 에러 처리 및 응답 캐싱 추가는 다음 편에서!
✅ 정리
- NestJS로 Ollama에 질문을 보낼 수 있는 API를 만들었고
- Ollama는 localhost:11434에서 LLM 응답을 반환
- 이제 이 구조를 기반으로 RAG 통합, 문서 임베딩 등의 기능을 붙여 나갈 수 있습니다
NestJS Ollama 연동,LLM API 만들기,로컬 LLM 통신,NestJS AI 백엔드,Ollama REST API 사용법,Mistral API NestJS,AI 응답 API 구현,RAG 백엔드 실습,NestJS LangChain 연동,Open Source LLM 연동