Visitar URL original
ragchatbot-codebase/OLLAMA_STARTUP_GUIDE.md at main · PiscesCYF/ragchatbot-codebase · GitHub
Skip to content

Latest commit

 

History

History
661 lines (489 loc) · 13.9 KB

OLLAMA_STARTUP_GUIDE.md

File metadata and controls

661 lines (489 loc) · 13.9 KB

Ollama 本地模型完整启动指南

本文档记录了使用 Ollama 本地模型启动 RAG 系统的完整过程,包括实际遇到的问题和解决方案。

📋 目录


环境准备

系统要求

  • 操作系统: macOS / Linux / Windows (WSL2)
  • 内存:
    • 最低 4GB(使用 3B 模型)
    • 推荐 8GB+(使用 7B 模型)
  • Python: 3.13+
  • 包管理器: uv (推荐) 或 pip

工具安装

1. 安装 uv(Python 包管理器)

# macOS / Linux
curl -LsSf https://astral.sh/uv/install.sh | sh

# 验证安装
uv --version
# 输出: uv 0.9.1 或更高版本

2. 安装 Ollama

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

# Windows: 访问 https://ollama.com/download 下载安装包

步骤 1: 安装和启动 Ollama

1.1 启动 Ollama 服务

在第一个终端窗口中启动 Ollama 服务:

ollama serve

预期输出:

time=2025-10-12T00:00:00.000+08:00 level=INFO source=server.go:123 msg="Ollama server starting" version=0.x.x
time=2025-10-12T00:00:00.000+08:00 level=INFO source=server.go:456 msg="listening on 127.0.0.1:11434"

⚠️ 重要:保持这个终端窗口打开!Ollama 服务需要持续运行。

1.2 下载模型

在第二个终端窗口中下载模型:

方案 A: qwen2.5:3b(推荐,轻量版)

ollama pull qwen2.5:3b

特点:

  • ✅ 内存需求:4GB+
  • ✅ 响应速度:快(3-5 秒)
  • ✅ 中文支持:优秀
  • ✅ 适合场景:个人学习、测试

方案 B: qwen2.5:7b(标准版)

ollama pull qwen2.5:7b

特点:

  • ✅ 内存需求:8GB+
  • ✅ 响应速度:中等(5-8 秒)
  • ✅ 质量:更好
  • ✅ 适合场景:正式使用、生产环境

1.3 验证模型安装

# 查看已安装的模型
ollama list

预期输出:

NAME            ID              SIZE      MODIFIED
qwen2.5:3b      357c53fb659c    1.9 GB    11 minutes ago

1.4 测试模型

# 测试模型是否能正常响应
ollama run qwen2.5:3b "你好,介绍一下自己"

预期输出:

你好!我是来自阿里云的大规模语言模型,我叫通义千问...

步骤 2: 配置项目环境

2.1 进入项目目录

cd /path/to/ragchatbot-codebase

2.2 创建 .env 配置文件

# 创建 .env 文件
cat > .env << 'EOF'
# AI Backend Configuration - Using Ollama Local Model
AI_BACKEND=ollama
OLLAMA_MODEL=qwen2.5:3b
OLLAMA_BASE_URL=http://localhost:11434
EOF

2.3 验证配置文件

cat .env

预期输出:

# AI Backend Configuration - Using Ollama Local Model
AI_BACKEND=ollama
OLLAMA_MODEL=qwen2.5:3b
OLLAMA_BASE_URL=http://localhost:11434

步骤 3: 安装项目依赖

3.1 使用 uv 安装依赖

uv sync

预期过程:

Using CPython 3.13.8 interpreter at: /opt/homebrew/opt/python@3.13/bin/python3.13
Creating virtual environment at: .venv
Resolved 137 packages in 19ms
Downloading packages...
Prepared 69 packages in 31.66s
Installed 119 packages in 632ms

关键依赖:

  • chromadb==1.0.15 - 向量数据库
  • anthropic==0.58.2 - Anthropic SDK
  • groq>=0.11.0 - Groq SDK
  • requests>=2.31.0 - HTTP 客户端(用于 Ollama)
  • sentence-transformers==5.0.0 - 文本嵌入模型
  • fastapi==0.116.1 - Web 框架
  • uvicorn==0.35.0 - ASGI 服务器

3.2 验证虚拟环境

# 检查虚拟环境是否创建
ls -la .venv

# 检查 Python 版本
uv run python --version

步骤 4: 启动应用服务

4.1 启动 FastAPI 服务

在第三个终端窗口(或第二个,如果模型已下载完成):

cd backend
uv run uvicorn app:app --reload --port 8000

预期输出:

INFO:     Will watch for changes in these directories: ['/path/to/backend']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [12345] using WatchFiles
INFO:     Started server process [12347]
INFO:     Waiting for application startup.
Loading initial documents...
Loaded 4 courses with 123 chunks
INFO:     Application startup complete.

4.2 理解启动过程

启动时会自动完成以下操作:

  1. 加载配置:读取 .env 文件中的配置
  2. 初始化 RAG 系统:
    • 创建 OllamaGenerator(AI 生成器)
    • 初始化 ChromaDB 向量存储
    • 创建 SentenceTransformer 嵌入模型
  3. 加载课程文档:
    • 扫描 docs/ 目录
    • 解析课程文档(PDF、DOCX、TXT)
    • 分块并存储到向量数据库
  4. 注册 API 路由:
    • /api/query - 查询接口
    • /api/courses - 课程列表接口
    • /api/clear-session - 清除会话接口
  5. 启动 Web 服务器:监听 8000 端口

步骤 5: 验证系统运行

5.1 检查服务状态

# 检查端口监听
lsof -i :8000 | grep LISTEN

预期输出:

Python  12347 username  3u  IPv4 0x... TCP localhost:8000 (LISTEN)

5.2 测试 API 接口

测试课程列表接口

curl -s http://localhost:8000/api/courses

预期输出:

{
  "total_courses": 4,
  "course_titles": [
    "Advanced Retrieval for AI with Chroma",
    "Prompt Compression and Query Optimization",
    "Building Towards Computer Use with Anthropic",
    "MCP: Build Rich-Context AI Apps with Anthropic"
  ]
}

测试查询接口

curl -s -X POST "http://localhost:8000/api/query" \
  -H "Content-Type: application/json" \
  -d '{"query": "Tell me about the Advanced Retrieval course"}'

预期输出:

{
  "answer": "The Advanced Retrieval course covers seven lessons...",
  "sources": [
    "Advanced Retrieval for AI with Chroma - Lesson 0",
    "Advanced Retrieval for AI with Chroma - Lesson 6"
  ],
  "source_links": [
    "https://learn.deeplearning.ai/courses/advanced-retrieval-for-ai/lesson/...",
    "https://learn.deeplearning.ai/courses/advanced-retrieval-for-ai/lesson/..."
  ],
  "session_id": "session_1"
}

5.3 访问 Web 界面

在浏览器中打开:

Web 界面功能:

  • 输入查询框
  • 课程统计信息
  • 建议查询列表
  • 来源显示(带可点击链接)
  • 深色/浅色主题切换

常见问题和解决方案

❌ 问题 1: 工具调用参数缺失错误

错误信息:

Error executing tool: CourseSearchTool.execute() missing 1 required positional argument: 'query'

原因分析: Ollama 本地模型(如 qwen2.5:3b)在生成工具调用 JSON 时,可能没有正确包含所有必需参数。模型生成的 JSON 格式可能不完整或缺少 query 字段。

解决方案: 已在 backend/ollama_generator.py 中添加参数验证和自动补全逻辑:

# 验证必需参数
if actual_tool_name == "search_course_content":
    # 确保 query 参数存在
    if "query" not in tool_args:
        # 如果缺失,使用用户原始查询
        tool_args["query"] = query

修复文件: backend/ollama_generator.py:161-167

验证修复:

curl -s -X POST "http://localhost:8000/api/query" \
  -H "Content-Type: application/json" \
  -d '{"query": "What is Chroma?"}'

应该返回正常的回答,不再报错。


❌ 问题 2: Ollama 服务连接失败

错误信息:

Error generating response: HTTPConnectionPool(host='localhost', port=11434): Max retries exceeded

原因: Ollama 服务未启动或端口配置错误。

解决步骤:

  1. 检查服务状态:
curl http://localhost:11434/api/version

如果失败,说明服务未运行。

  1. 启动 Ollama 服务:
ollama serve
  1. 检查端口配置:
# 确认 .env 中的端口正确
cat .env | grep OLLAMA_BASE_URL
# 应该输出: OLLAMA_BASE_URL=http://localhost:11434
  1. 验证连接:
curl http://localhost:11434/api/tags

应该返回已安装的模型列表。


❌ 问题 3: 模型响应超时

错误信息:

Error generating response: Read timed out

原因:

  • 模型太大,内存不足
  • CPU 性能不足
  • 首次加载模型较慢

解决方案:

  1. 使用更小的模型:
# 切换到 3B 模型
ollama pull qwen2.5:3b

# 修改 .env
OLLAMA_MODEL=qwen2.5:3b
  1. 增加超时时间: 在 backend/ollama_generator.py 中调整超时参数:
timeout=120  # 增加到 120 秒
  1. 启用 GPU 加速(如果有 GPU):
# 检查 GPU 是否可用
nvidia-smi

# Ollama 会自动使用 GPU

❌ 问题 4: 端口被占用

错误信息:

ERROR: [Errno 48] Address already in use

解决方案:

  1. 查找占用端口的进程:
lsof -i :8000
  1. 杀死占用进程:
kill -9 <PID>
  1. 或使用不同端口:
uv run uvicorn app:app --reload --port 8001

❌ 问题 5: 虚拟环境激活失败

错误: 使用 source .venv/bin/activate 激活虚拟环境失败。

解决方案: 使用 uv 时不需要手动激活虚拟环境!

# ❌ 错误做法
source .venv/bin/activate
python app.py

# ✅ 正确做法
uv run python app.py

uv run 会自动使用项目虚拟环境。


❌ 问题 6: Git 提交失败(用户信息未配置)

错误信息:

Author identity unknown
fatal: unable to auto-detect email address

解决方案:

# 配置全局 Git 用户信息
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

# 验证配置
git config --global user.name
git config --global user.email

性能优化建议

1. 模型选择

模型 内存 速度 质量 推荐场景
qwen2.5:3b 4GB ⚡⚡⚡ ⭐⭐⭐ 学习测试
qwen2.5:7b 8GB ⚡⚡ ⭐⭐⭐⭐ 正式使用
llama3.2:3b 4GB ⚡⚡⚡ ⭐⭐⭐ 英文优先

2. GPU 加速

如果有 NVIDIA GPU:

# 检查 GPU 可用性
nvidia-smi

# Ollama 会自动检测并使用 GPU
# 响应速度可提升 5-10 倍

3. 调整并发设置

在 backend/config.py 中调整参数:

# 减少上下文长度,提高速度
MAX_HISTORY: int = 1  # 默认 2

# 减少搜索结果数量
MAX_RESULTS: int = 3  # 默认 5

4. 预加载模型

启动 Ollama 后预加载模型:

# 预热模型
ollama run qwen2.5:3b "你好"

这样第一次查询也会很快。


系统架构说明

组件交互流程

用户查询
    ↓
FastAPI (/api/query)
    ↓
RAGSystem.query()
    ↓
OllamaGenerator.generate_response()
    ↓
[决策] 是否需要搜索工具?
    ↓ YES
CourseSearchTool.execute()
    ↓
VectorStore.search() → ChromaDB
    ↓
[返回搜索结果]
    ↓
OllamaGenerator (第二次调用)
    ↓
基于搜索结果生成回答
    ↓
返回给用户

关键类说明

OllamaGenerator (backend/ollama_generator.py)

  • 负责与 Ollama API 通信
  • 实现工具调用逻辑(通过 prompt engineering)
  • 处理对话历史

CourseSearchTool (backend/search_tools.py)

  • 实现课程内容搜索
  • 支持课程名称过滤和课时过滤
  • 返回格式化的搜索结果

VectorStore (backend/vector_store.py)

  • 封装 ChromaDB 操作
  • 管理两个集合:course_catalog 和 course_content
  • 提供统一的搜索接口

完整启动检查清单

使用前请确认以下所有步骤:

  • Ollama 服务正在运行 (ollama serve)
  • 模型已下载 (ollama list 显示模型)
  • .env 文件已创建并配置正确
  • 虚拟环境已创建 (ls .venv)
  • 依赖已安装完成 (uv sync 成功)
  • 应用服务已启动 (uvicorn 输出 "Application startup complete")
  • API 测试通过 (curl http://localhost:8000/api/courses)
  • Web 界面可访问 (浏览器打开 http://localhost:8000)
  • 查询功能正常(提交问题后有正确回答)

故障排查流程

遇到问题时,按以下顺序检查:

  1. Ollama 服务

    curl http://localhost:11434/api/version
  2. 模型可用性

    ollama list
  3. 配置文件

    cat .env
  4. 应用服务

    curl http://localhost:8000/api/courses
  5. 查看日志

    • 检查 uvicorn 终端输出
    • 查看是否有错误信息

相关文档

  • 多后端配置: MULTI_BACKEND_GUIDE.md
  • 快速开始: QUICK_START.md
  • 技术实现: IMPLEMENTATION_SUMMARY.md
  • 开发指南: CLAUDE.md

更新历史

  • 2025-10-12: 初始版本,记录完整启动流程和工具调用参数修复
  • 修复: OllamaGenerator 工具调用参数验证 (commit: 28c3035)

贡献者: PiscesCYF 最后更新: 2025-10-12