Ollama (로컬 모델)

API 키, 인터넷, 비용 없이 완전한 개인 정보 보호를 통해 LLM을 로컬에서 실행하세요.

개요

┌─────────────────────────────────────────────────────────────────────┐
│                         Ollama Local Setup                          │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│   Your Machine                                                      │
│   ┌─────────────────────────────────────────────────────────────┐  │
│   │                                                             │  │
│   │   ┌──────────────┐      ┌──────────────┐                   │  │
│   │   │  ADK-Rust    │ ───▶ │   Ollama     │                   │  │
│   │   │  Agent       │      │   Server     │                   │  │
│   │   └──────────────┘      └──────┬───────┘                   │  │
│   │                                │                            │  │
│   │                         ┌──────▼───────┐                   │  │
│   │                         │  Local LLM   │                   │  │
│   │                         │  (llama3.2)  │                   │  │
│   │                         └──────────────┘                   │  │
│   │                                                             │  │
│   └─────────────────────────────────────────────────────────────┘  │
│                                                                     │
│   🔒 100% 비공개 - 데이터는 절대로 사용자 머신을 떠나지 않습니다   │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

Ollama를 선택하는 이유

이점설명
🆓 무료API 비용이 전혀 없습니다
🔒 비공개데이터가 사용자 머신에 유지됩니다
📴 오프라인인터넷 없이 작동합니다
🎛️ 제어원하는 모델을 선택하고 설정을 사용자 지정할 수 있습니다
빠름네트워크 지연이 없습니다

1단계: Ollama 설치

macOS

brew install ollama

Linux

curl -fsSL https://ollama.com/install.sh | sh

Windows

ollama.com에서 다운로드하세요.


2단계: 서버 시작

ollama serve

다음과 같이 표시됩니다:

Couldn't find '/Users/you/.ollama/id_ed25519'. Generating new private key.
Your new public key is: ssh-ed25519 AAAA...
time=2024-01-05T12:00:00.000Z level=INFO source=server.go msg="Listening on 127.0.0.1:11434"

3단계: 모델 풀(Pull)

새 터미널에서:

# 권장 시작 모델 (3B 매개변수, 빠름)
ollama pull llama3.2

# 기타 인기 모델
ollama pull qwen2.5:7b    # 뛰어난 도구 호출
ollama pull mistral       # 코드에 적합
ollama pull codellama     # 코드 생성
ollama pull gemma2        # Google의 효율적인 모델

4단계: 프로젝트에 추가

[dependencies]
adk-model = { version = "0.2", features = ["ollama"] }

5단계: 코드에서 사용하기

use adk_model::ollama::{OllamaModel, OllamaConfig};
use adk_agent::LlmAgentBuilder;
use std::sync::Arc;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // No API key needed!
    let model = OllamaModel::new(OllamaConfig::new("llama3.2"))?;

    let agent = LlmAgentBuilder::new("local_assistant")
        .instruction("You are a helpful assistant running locally.")
        .model(Arc::new(model))
        .build()?;

    // Use the agent...
    Ok(())
}

완전한 동작 예제

use adk_rust::prelude::*;
use adk_rust::Launcher;
use std::sync::Arc;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    dotenvy::dotenv().ok();
    
    // No API key needed!
    let model = OllamaModel::new(OllamaConfig::new("llama3.2"))?;

    let agent = LlmAgentBuilder::new("ollama_assistant")
        .description("Ollama-powered local assistant")
        .instruction("You are a helpful assistant running locally via Ollama. Be concise.")
        .model(Arc::new(model))
        .build()?;

    // Run interactive session
    Launcher::new(Arc::new(agent)).run().await?;
    
    Ok(())
}

Cargo.toml

[dependencies]
adk-rust = { version = "0.2", features = ["cli", "ollama"] }
tokio = { version = "1", features = ["full"] }
dotenvy = "0.15"
anyhow = "1.0"

구성 옵션

use adk_model::ollama::{OllamaModel, OllamaConfig};

let config = OllamaConfig::new("llama3.2")
    .with_base_url("http://localhost:11434")  // Custom server URL
    .with_temperature(0.7)                     // Creativity (0.0-1.0)
    .with_max_tokens(2048);                    // Max response length

let model = OllamaModel::new(config)?;

권장 모델

모델크기필요한 RAM가장 적합한 용도
llama3.23B4GB빠르고 범용적
llama3.2:7b7B8GB더 나은 품질
qwen2.5:7b7B8GB최고의 Tool calling
mistral7B8GB코드 및 추론
codellama7B8GB코드 생성
gemma29B10GB균형 잡힌 성능
llama3.1:70b70B48GB최고 품질

모델 선택

  • RAM이 제한적 (8GB)?llama3.2 (3B)
  • Tool calling이 필요한가요?qwen2.5:7b
  • 코드를 작성하나요?codellama 또는 mistral
  • 최고의 품질을 원하나요?llama3.1:70b (48GB+ RAM 필요)

Ollama를 사용한 Tool Calling

Ollama는 호환되는 모델로 function calling을 지원합니다:

use adk_model::ollama::{OllamaModel, OllamaConfig};
use adk_agent::LlmAgentBuilder;
use adk_tool::FunctionTool;
use std::sync::Arc;

// qwen2.5 has excellent tool calling support
let model = OllamaModel::new(OllamaConfig::new("qwen2.5:7b"))?;

let weather_tool = Arc::new(FunctionTool::new(
    "get_weather",
    "Get weather for a location",
    |_ctx, args| async move {
        let location = args.get("location").and_then(|v| v.as_str()).unwrap_or("unknown");
        Ok(serde_json::json!({
            "location": location,
            "temperature": "72°F",
            "condition": "Sunny"
        }))
    },
));

let agent = LlmAgentBuilder::new("weather_assistant")
    .instruction("Help users check the weather.")
    .model(Arc::new(model))
    .tool(weather_tool)
    .build()?;

참고: Tool calling은 로컬 모델과의 안정성을 위해 스트리밍하지 않는 모드를 사용합니다.


출력 예시

👤 User: Hello! What can you do?

🤖 Ollama (llama3.2): Hello! I'm a local AI assistant running on your 
machine. I can help with:
- Answering questions
- Writing and editing text
- Explaining concepts
- Basic coding help

All completely private - nothing leaves your computer!

문제 해결

"연결 거부됨"

# Make sure Ollama is running
ollama serve

"모델을 찾을 수 없음"

# Pull the model first
ollama pull llama3.2

느린 응답

  • 더 작은 모델 사용 (llama3.2 대신 llama3.1:70b)
  • 다른 애플리케이션을 종료하여 RAM 확보
  • 가능하다면 GPU 가속 고려

사용 가능한 모델 확인

ollama list

예제 실행

# official_docs_examples 폴더에서
cd official_docs_examples/models/providers_test
cargo run --bin ollama_example

관련


이전: ← Model Providers | 다음: Local Models (mistral.rs) →