본문으로 건너뛰기 Ollama 완벽 가이드 | 로컬 LLM·Llama·Mistral·API·실전 활용

Ollama 완벽 가이드 | 로컬 LLM·Llama·Mistral·API·실전 활용

Ollama 완벽 가이드 | 로컬 LLM·Llama·Mistral·API·실전 활용

이 글의 핵심

Ollama로 로컬 LLM을 실행하는 완벽 가이드. Llama, Mistral 모델 실행, REST API, LangChain 통합까지 실전 예제로 정리. Ollama·LLM·Llama 중심으로 설명합니다. Start now.

이 글의 핵심

Ollama로 로컬 LLM을 실행하는 완벽 가이드입니다. Llama, Mistral 모델 실행, REST API, LangChain 통합까지 실전 예제로 정리했습니다.

실무 경험 공유: OpenAI API를 Ollama로 전환하면서, API 비용이 100% 절감되고 데이터 프라이버시가 보장된 경험을 공유합니다.

들어가며: “LLM API 비용이 부담돼요”

실무에서 마주치는 문제들

API 비용이 높아요

OpenAI는 비쌉니다. Ollama는 로컬에서 무료로 실행됩니다. 데이터 프라이버시가 중요해요

클라우드는 걱정됩니다. Ollama는 로컬에서 안전합니다. 인터넷이 불안정해요

API는 연결이 필요합니다. Ollama는 오프라인에서 작동합니다.

1. Ollama란?

LLM 민주화: “Docker for AI Models”

Ollama(2023)는 Jeffrey Morgan이 만든 “로컬에서 LLM을 실행하는 가장 쉬운 방법”입니다. 2023년 Llama 2 공개 이후 오픈소스 LLM이 폭발적으로 증가했지만, 실행 환경 구성(CUDA·Python 의존성·모델 다운로드)이 복잡했습니다.

Ollama는 Docker 철학을 차용했습니다:

# Docker
docker run nginx

# Ollama
ollama run llama3

핵심 혁신

  • 모델 레지스트리: ollama.com/library에서 원클릭 다운로드
  • 자동 양자화: 7B 모델을 4-bit·8-bit로 압축 (13GB → 4GB)
  • GPU 자동 감지: CUDA·Metal·ROCm 자동 선택
  • REST API 내장: localhost:11434로 즉시 서빙

Ollama vs LM Studio vs Text Generation WebUI

측면OllamaLM StudioText Generation WebUI
UICLI·API 중심GUIGUI
모델 설치ollama pull llama3GUI 다운로드Hugging Face 수동
API✅ REST (내장)✅ REST✅ REST (gradio)
GPU 지원CUDA·Metal·ROCmCUDA·MetalCUDA 주력
개발자 친화✅ (CLI)일반 사용자고급 사용자
사용 사례백엔드 통합·자동화로컬 ChatGPT 대체모델 실험·파인튜닝

오픈소스 LLM 생태계 (2024-2026)

모델개발사크기특징
Llama 3.1Meta8B·70B·405BGPT-4급 성능, 128K context
MistralMistral AI7B·8x7B·8x22B효율적, Mixture of Experts
GemmaGoogle2B·7B·27B경량, 모바일 최적화
QwenAlibaba7B·14B·72B다국어 강점
Phi-3Microsoft3.8B소형 고성능

Ollama 지원 모델: ollama.com/library에서 50+ 모델 (양자화 버전 포함)

핵심 특징

Ollama는 로컬 LLM 실행 도구입니다. 주요 장점

  • 로컬 실행: API 비용 제로, 데이터 프라이버시 보장
  • 다양한 모델: Llama·Mistral·Gemma·Qwen 등 50+ 모델
  • REST API: OpenAI API 호환 인터페이스
  • 빠른 속도: GPU 가속 (CUDA·Metal·ROCm)
  • 오픈소스: MIT 라이선스, 무료

시스템 요구사항

  • 최소: 8GB RAM, CPU만 (느림)
  • 권장: 16GB RAM, NVIDIA GPU (8GB VRAM) → 7B 모델
  • 최적: 32GB RAM, NVIDIA GPU (24GB VRAM) → 70B 모델

2. 설치 및 실행

설치

# macOS/Linux
curl -fsSL https://ollama.com/install.sh | sh
# Windows
# https://ollama.com/download

모델 실행

# Llama 3
ollama run llama3
# Mistral
ollama run mistral
# Gemma
ollama run gemma:7b
# 모델 목록
ollama list
# 모델 삭제
ollama rm llama3

3. CLI 사용

터미널에서 다음 명령어를 실행합니다.

# 대화
ollama run llama3
>>> Hello!
>>> /bye
# 단일 질문
ollama run llama3 "What is Python?"
# 파일 입력
ollama run llama3 < prompt.txt

4. REST API

기본 호출

curl http://localhost:11434/api/generate -d '{
  "model": "llama3",
  "prompt": "Why is the sky blue?",
  "stream": false
}'

Python

import requests
import json
def query_ollama(prompt: str, model: str = "llama3") -> str:
    response = requests.post(
        "http://localhost:11434/api/generate",
        json={
            "model": model,
            "prompt": prompt,
            "stream": False
        }
    )
    return response.json()[response]
# 사용
answer = query_ollama("What is Python?")
print(answer)

Streaming

def query_ollama_stream(prompt: str, model: str = "llama3"):
    response = requests.post(
        "http://localhost:11434/api/generate",
        json={
            "model": model,
            "prompt": prompt,
            "stream": True
        },
        stream=True
    )
    for line in response.iter_lines():
        if line:
            data = json.loads(line)
            if not data.get("done"):
                print(data[response], end="", flush=True)
# 사용
query_ollama_stream("Write a story about a cat")

5. Chat API

def chat(messages: list[dict]) -> str:
    response = requests.post(
        "http://localhost:11434/api/chat",
        json={
            "model": "llama3",
            "messages": messages,
            "stream": False
        }
    )
    return response.json()[message][content]
# 사용
messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "What is Python?"}
]
answer = chat(messages)
print(answer)

6. LangChain 통합

from langchain_community.llms import Ollama
from langchain.prompts import ChatPromptTemplate
from langchain.chains import LLMChain
llm = Ollama(model="llama3")
template = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant."),
    ("human", "{question}")
])
chain = LLMChain(llm=llm, prompt=template)
result = chain.invoke({"question": "What is Python?"})
print(result[text])

7. RAG 구현

from langchain_community.llms import Ollama
from langchain.vectorstores import Chroma
from langchain_openai import OpenAIEmbeddings
from langchain.chains import RetrievalQA
from langchain.document_loaders import TextLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
# 문서 로드
loader = TextLoader("document.txt")
documents = loader.load()
# 청크 분할
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000)
chunks = text_splitter.split_documents(documents)
# Vector Store
embeddings = OpenAIEmbeddings()
vectorstore = Chroma.from_documents(
    documents=chunks,
    embedding=embeddings
)
# QA Chain
llm = Ollama(model="llama3")
qa_chain = RetrievalQA.from_chain_type(
    llm=llm,
    chain_type="stuff",
    retriever=vectorstore.as_retriever()
)
# 질문
answer = qa_chain.invoke({"query": "What is the main topic?"})
print(answer[result])

8. Modelfile

커스텀 모델

# Modelfile
FROM llama3
PARAMETER temperature 0.7
PARAMETER top_p 0.9
SYSTEM """
You are a helpful coding assistant.
You provide clear and concise code examples.
"""
ollama create my-coding-assistant -f Modelfile
ollama run my-coding-assistant

정리 및 체크리스트

핵심 요약

  • Ollama: 로컬 LLM 실행
  • 무료: 오픈소스
  • 다양한 모델: Llama, Mistral, Gemma
  • REST API: 간편한 통합
  • LangChain: 완벽한 호환
  • Modelfile: 커스터마이징

구현 체크리스트

  • Ollama 설치
  • 모델 다운로드
  • CLI 사용
  • REST API 호출
  • Chat API 구현
  • LangChain 통합
  • RAG 구현

같이 보면 좋은 글


이 글에서 다루는 키워드

Ollama, LLM, Llama, Mistral, AI, Local, Open Source

자주 묻는 질문 (FAQ)

Q. GPU가 필요한가요?

A. 권장하지만 필수는 아닙니다. CPU로도 실행 가능하지만 느립니다.

Q. 어떤 모델을 사용해야 하나요?

A. Llama 3 8B가 성능과 속도의 균형이 좋습니다.

Q. 프로덕션에서 사용할 수 있나요?

A. 네, 하지만 하드웨어 요구사항을 확인하세요.

Q. 무료인가요?

A. 네, 완전히 무료입니다.