这一章列出使用 Ollama 时可能遇到的问题和解决方案。
问题:
Connection refused: localhost:11434
解决方法:
# macOS/Linux
ps aux | grep ollama
# Windows
tasklist | findstr ollama
ollama serve
# macOS/Linux
lsof -i :11434
# Windows
netstat -ano | findstr :11434
问题:
TimeoutError: Request timed out
解决方法:
import requests
response = requests.post(
"http://localhost:11434/api/chat",
json={"model": "llama3.2", "messages": messages},
timeout=300 # 5 分钟
)
检查网络连接
减少请求大小
问题:
model 'xxx' not found
解决方法:
ollama pull llama3.2
import ollama
models = ollamaari.list()
print([m['name'] for m in models['models']])
# 错误
model='llama3.2'
# 正确
model='llama3.2:latest'
问题:
failed to load model
解决方法:
检查内存是否足够
使用更小的模型或量化:
ollama pull llama3.2:1b
ollama show llama3.2
问题:
CUDA out of memory
解决方法:
response = ollama.chat(
model='llama3.2',
messages=messages,
options={'num_ctx': 2048}
)
ollama pull llama3.2:3b-q4_K_S
response = ollama.chat(
model='llama3.2',
messages=messages,
options={'num_gpu': 20}
)
response = ollama.chat(
model='llama3.2',
messages=messages,
options={'num_gpu': 0}
)
解决方法:
使用更小的模型
减少生成长度:
response = ollama.chat(
model='llama3.2',
messages=messages,
options={'num_predict': 100}
)
启用 GPU 加速
使用流式输出提升体验
解决方法:
ollama.generate(
model='llama3.2',
prompt='',
keep_alive='0'
)
使用更小的量化
限制并发数量
问题: 模型输出在中间停止。
解决方法:
response = ollama.chat(
model='llama3.2',
messages=messages,
options={'num_predict': 2000}
)
检查停止词设置
检查上下文长度
解决方法:
response = ollama.chat(
model='llama3.2',
messages=messages,
options={'temperature': 0.3}
)
改进提示词
使用更好的模型
添加系统提示
问题:
400 Bad Request
解决方法:
import json
request = {
"model": "llama3.2",
"messages": [{"role": "user", "content": "你好"}]
}
print(json.dumps(request, indent=2))
检查必需参数
验证参数类型
问题:
500 Internal Server Error
解决方法:
journalctl -u ollama -f
重启 Ollama
检查模型文件
import logging
logging.basicConfig(level=logging.DEBUG)
def debug_chat(messages):
print("请求:")
print(json.dumps(messages, indent=2, ensure_ascii=False))
response = ollama.chat(
model='llama3.2',
messages=messages
)
print("\n响应:")
print(json.dumps(response, indent=2, ensure_ascii=False))
return response
import time
import cProfile
def profile_chat():
profiler = cProfile.Profile()
profiler.enable()
response = ollama.chat(
model='llama3.2',
messages=[{'role': 'user', 'content': '你好'}]
)
profiler.disable()
profiler.print_stats()
profile_chat()
# macOS/Linux
tail -f ~/.ollama/logs/server.log
# Windows
type %USERPROFILE%\.ollama\logs\server.log
ollama --version
ollama --help