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

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

이 글의 핵심

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

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

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

실무 문제 시나리오

시나리오 1: API 비용이 높아요
OpenAI는 비쌉니다. Ollama는 로컬에서 무료로 실행됩니다.

시나리오 2: 데이터 프라이버시가 중요해요
클라우드는 걱정됩니다. Ollama는 로컬에서 안전합니다.

시나리오 3: 인터넷이 불안정해요
API는 연결이 필요합니다. Ollama는 오프라인에서 작동합니다.


1. Ollama란?

핵심 특징

Ollama는 로컬 LLM 실행 도구입니다.

주요 장점:

  • 로컬 실행: 무료
  • 다양한 모델: Llama, Mistral, Gemma
  • REST API: 간편한 통합
  • 빠른 속도: GPU 가속
  • 오픈소스: 무료

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 구현

같이 보면 좋은 글

  • LangChain 완벽 가이드
  • OpenAI API 가이드
  • ChromaDB 완벽 가이드

이 글에서 다루는 키워드

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

자주 묻는 질문 (FAQ)

Q. GPU가 필요한가요?

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

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

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

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

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

Q. 무료인가요?

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

... 996 lines not shown ... Token usage: 63706/1000000; 936294 remaining Start-Sleep -Seconds 3