Ollama (本地模型)

运行 LLMs 本地,完全私密 — 无需 API 密钥,无需互联网,无需成本。

概述

┌─────────────────────────────────────────────────────────────────────┐
│                         Ollama Local Setup                          │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│   Your Machine                                                      │
│   ┌─────────────────────────────────────────────────────────────┐  │
│   │                                                             │  │
│   │   ┌──────────────┐      ┌──────────────┐                   │  │
│   │   │  ADK-Rust    │ ───▶ │   Ollama     │                   │  │
│   │   │  Agent       │      │   Server     │                   │  │
│   │   └──────────────┘      └──────┬───────┘                   │  │
│   │                                │                            │  │
│   │                         ┌──────▼───────┐                   │  │
│   │                         │  Local LLM   │                   │  │
│   │                         │  (llama3.2)  │                   │  │
│   │                         └──────────────┘                   │  │
│   │                                                             │  │
│   └─────────────────────────────────────────────────────────────┘  │
│                                                                     │
│   🔒 100% Private - Data never leaves your machine                 │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

为什么选择 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:拉取模型

在新终端中:

# Recommended starter model (3B parameters, fast)
ollama pull llama3.2:3b

# Other popular models
ollama pull qwen3.6:35b-a3b   # Latest Qwen — 73.4% SWE-bench, MoE 35B/3B active
ollama pull qwen3.5            # Strong multilingual and coding
ollama pull qwen3-coder:30b    # Code-focused with tool calling
ollama pull mistral:7b        # Good for code
ollama pull deepseek-r1:14b   # Reasoning model
ollama pull devstral:24b      # Optimized for coding
ollama pull gemma3:9b         # Google's efficient model
ollama pull codellama:13b     # Code generation

步骤 4:添加到您的项目

[dependencies]
adk-model = { version = "2.0.0", 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 = "2.0.0", features = ["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.2:3b3B4GB快速、通用
llama3.1:8b8B8GB流行的均衡模型
qwen3.6:35b-a3b35B (3B active)24GB最佳 agentic 编码 — 73.4% SWE-bench
qwen3.5可变可变强大的多语言和编码能力
qwen3-coder:30b30B19GB专注于代码,支持工具调用
qwen2.5:7b7B8GB良好的工具调用能力,轻量级
mistral:7b7B8GB代码和推理
mistral-nemo:12b12B12GB增强型 Mistral (128K 上下文)
deepseek-r1:14b14B16GB蒸馏推理
deepseek-r1:32b32B32GB更大的推理模型
gemma3:9b9B10GB谷歌的高效开放模型
devstral:24b24B24GB针对编码优化
codellama:13b13B16GB代码生成
llama3.3:70b70B48GB最高质量

选择模型

  • 内存有限 (8GB)?llama3.2:3b
  • 最佳智能体编码?qwen3.6:35b-a3b (24GB, MoE — 仅 3B 活跃)
  • 需要工具调用?qwen3.5qwen3-coder:30b
  • 编写代码?devstral:24bqwen3-coder:30b
  • 需要推理?deepseek-r1:14bdeepseek-r1:32b
  • 最佳质量?llama3.3:70b (需要 48GB+ 内存)

使用 Ollama 进行工具调用

Ollama 支持与兼容模型进行函数调用:

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()?;

注意:工具调用使用非流式模式,以确保本地模型的可靠性。


示例输出

👤 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)
  • 关闭其他应用程序以释放内存
  • 如果可用,考虑 GPU 加速

检查可用模型

ollama list

运行示例

cargo check -p adk-rust --no-default-features --features ollama

在启动使用此提供程序的 Agent 之前,运行 ollama serve 并拉取模型。



上一页: ← 模型提供商 | 下一页: 本地模型 (mistral.rs) →

Ollama (本地模型) - ADK-Rust 文档 | ADK-Rust