본문 바로가기
AI

Ollama + restAPI

by david100gom 2025. 4. 21.

Ollama를 백엔드로 활용하여 Node.js로 API를 구축하는 건 꽤 직관적이에요. Ollama는 기본적으로 로컬에서 REST API (localhost:11434) 로 모델과 대화할 수 있도록 해줘요. Node.js에서는 axios나 node-fetch를 써서 쉽게 연동할 수 있습니다.


✅ 기본 구조

  1. Ollama가 로컬에서 실행 중이어야 함 (기본 포트: 11434)
  2. Node.js 서버에서 HTTP 요청을 통해 Ollama API와 통신

✅ 예시: 간단한 Express.js 기반 API

1. Node.js 프로젝트 초기화

mkdir ollama-api
cd ollama-api
npm init -y
npm install express axios

2. index.js 작성

const express = require('express');
const axios = require('axios');
const app = express();

app.use(express.json());

app.post('/chat', async (req, res) => {
  const { message } = req.body;

  try {
    const response = await axios.post('http://localhost:11434/api/generate', {
      model: 'llama2', // 설치된 모델 이름
      prompt: message,
      stream: false
    });

    res.json({ response: response.data.response });
  } catch (err) {
    console.error('Error talking to Ollama:', err.message);
    res.status(500).json({ error: 'Ollama error' });
  }
});

app.listen(3000, () => {
  console.log('Server listening on http://localhost:3000');
});

3. 서버 실행

node index.js

4. API 테스트

curl -X POST http://localhost:3000/chat \
  -H "Content-Type: application/json" \
  -d '{"message":"안녕! 오늘 날씨 어때?"}'

✅ 기타 팁

  • 설치된 모델 이름은 ollama list 로 확인 가능
  • 실시간 스트리밍 응답을 원하면 stream: true 설정 + EventSource or WebSocket 필요
  • 프론트엔드 연동도 쉬움 (React/Vue 등)

필요하다면 WebSocket 기반 스트리밍 버전도 알려줄 수 있어요!
원하는 기능이나 구조가 있으면 더 구체적으로 도와줄게요.

728x90

댓글