本文档记录了使用 Ollama 本地模型启动 RAG 系统的完整过程,包括实际遇到的问题和解决方案。
- 操作系统: macOS / Linux / Windows (WSL2)
- 内存:
- 最低 4GB(使用 3B 模型)
- 推荐 8GB+(使用 7B 模型)
- Python: 3.13+
- 包管理器: uv (推荐) 或 pip
# macOS / Linux
curl -LsSf https://astral.sh/uv/install.sh | sh
# 验证安装
uv --version
# 输出: uv 0.9.1 或更高版本# macOS / Linux
curl -fsSL https://ollama.com/install.sh | sh
# Windows: 访问 https://ollama.com/download 下载安装包在第一个终端窗口中启动 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 服务需要持续运行。
在第二个终端窗口中下载模型:
ollama pull qwen2.5:3b特点:
- ✅ 内存需求:4GB+
- ✅ 响应速度:快(3-5 秒)
- ✅ 中文支持:优秀
- ✅ 适合场景:个人学习、测试
ollama pull qwen2.5:7b特点:
- ✅ 内存需求:8GB+
- ✅ 响应速度:中等(5-8 秒)
- ✅ 质量:更好
- ✅ 适合场景:正式使用、生产环境
# 查看已安装的模型
ollama list预期输出:
NAME ID SIZE MODIFIED
qwen2.5:3b 357c53fb659c 1.9 GB 11 minutes ago
# 测试模型是否能正常响应
ollama run qwen2.5:3b "你好,介绍一下自己"预期输出:
你好!我是来自阿里云的大规模语言模型,我叫通义千问...
cd /path/to/ragchatbot-codebase# 创建 .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
EOFcat .env预期输出:
# AI Backend Configuration - Using Ollama Local Model
AI_BACKEND=ollama
OLLAMA_MODEL=qwen2.5:3b
OLLAMA_BASE_URL=http://localhost:11434
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 SDKgroq>=0.11.0- Groq SDKrequests>=2.31.0- HTTP 客户端(用于 Ollama)sentence-transformers==5.0.0- 文本嵌入模型fastapi==0.116.1- Web 框架uvicorn==0.35.0- ASGI 服务器
# 检查虚拟环境是否创建
ls -la .venv
# 检查 Python 版本
uv run python --version在第三个终端窗口(或第二个,如果模型已下载完成):
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.
启动时会自动完成以下操作:
- 加载配置:读取
.env文件中的配置 - 初始化 RAG 系统:
- 创建 OllamaGenerator(AI 生成器)
- 初始化 ChromaDB 向量存储
- 创建 SentenceTransformer 嵌入模型
- 加载课程文档:
- 扫描
docs/目录 - 解析课程文档(PDF、DOCX、TXT)
- 分块并存储到向量数据库
- 扫描
- 注册 API 路由:
/api/query- 查询接口/api/courses- 课程列表接口/api/clear-session- 清除会话接口
- 启动 Web 服务器:监听 8000 端口
# 检查端口监听
lsof -i :8000 | grep LISTEN预期输出:
Python 12347 username 3u IPv4 0x... TCP localhost:8000 (LISTEN)
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"
}在浏览器中打开:
- Web 界面: http://localhost:8000
- API 文档: http://localhost:8000/docs
Web 界面功能:
- 输入查询框
- 课程统计信息
- 建议查询列表
- 来源显示(带可点击链接)
- 深色/浅色主题切换
错误信息:
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?"}'应该返回正常的回答,不再报错。
错误信息:
Error generating response: HTTPConnectionPool(host='localhost', port=11434): Max retries exceeded
原因: Ollama 服务未启动或端口配置错误。
解决步骤:
- 检查服务状态:
curl http://localhost:11434/api/version如果失败,说明服务未运行。
- 启动 Ollama 服务:
ollama serve- 检查端口配置:
# 确认 .env 中的端口正确
cat .env | grep OLLAMA_BASE_URL
# 应该输出: OLLAMA_BASE_URL=http://localhost:11434- 验证连接:
curl http://localhost:11434/api/tags应该返回已安装的模型列表。
错误信息:
Error generating response: Read timed out
原因:
- 模型太大,内存不足
- CPU 性能不足
- 首次加载模型较慢
解决方案:
- 使用更小的模型:
# 切换到 3B 模型
ollama pull qwen2.5:3b
# 修改 .env
OLLAMA_MODEL=qwen2.5:3b- 增加超时时间:
在
backend/ollama_generator.py中调整超时参数:
timeout=120 # 增加到 120 秒- 启用 GPU 加速(如果有 GPU):
# 检查 GPU 是否可用
nvidia-smi
# Ollama 会自动使用 GPU错误信息:
ERROR: [Errno 48] Address already in use
解决方案:
- 查找占用端口的进程:
lsof -i :8000- 杀死占用进程:
kill -9 <PID>- 或使用不同端口:
uv run uvicorn app:app --reload --port 8001错误:
使用 source .venv/bin/activate 激活虚拟环境失败。
解决方案:
使用 uv 时不需要手动激活虚拟环境!
# ❌ 错误做法
source .venv/bin/activate
python app.py
# ✅ 正确做法
uv run python app.pyuv run 会自动使用项目虚拟环境。
错误信息:
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| 模型 | 内存 | 速度 | 质量 | 推荐场景 |
|---|---|---|---|---|
| qwen2.5:3b | 4GB | ⚡⚡⚡ | ⭐⭐⭐ | 学习测试 |
| qwen2.5:7b | 8GB | ⚡⚡ | ⭐⭐⭐⭐ | 正式使用 |
| llama3.2:3b | 4GB | ⚡⚡⚡ | ⭐⭐⭐ | 英文优先 |
如果有 NVIDIA GPU:
# 检查 GPU 可用性
nvidia-smi
# Ollama 会自动检测并使用 GPU
# 响应速度可提升 5-10 倍在 backend/config.py 中调整参数:
# 减少上下文长度,提高速度
MAX_HISTORY: int = 1 # 默认 2
# 减少搜索结果数量
MAX_RESULTS: int = 3 # 默认 5启动 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)
- 查询功能正常(提交问题后有正确回答)
遇到问题时,按以下顺序检查:
-
Ollama 服务
curl http://localhost:11434/api/version
-
模型可用性
ollama list
-
配置文件
cat .env
-
应用服务
curl http://localhost:8000/api/courses
-
查看日志
- 检查 uvicorn 终端输出
- 查看是否有错误信息
- 多后端配置:
MULTI_BACKEND_GUIDE.md - 快速开始:
QUICK_START.md - 技术实现:
IMPLEMENTATION_SUMMARY.md - 开发指南:
CLAUDE.md
- 2025-10-12: 初始版本,记录完整启动流程和工具调用参数修复
- 修复: OllamaGenerator 工具调用参数验证 (commit: 28c3035)
贡献者: PiscesCYF 最后更新: 2025-10-12