Ollama 使用指南¶
Ollama 是一个本地部署的开源 LLM 运行框架,支持在本地运行 Llama、Mistral、Gemma 等多种开源模型,提供数据隐私保护和无网络依赖的本地推理能力。
模型概览¶
推荐模型¶
| 模型 | 上下文 | 特色 | 适用场景 |
|---|---|---|---|
| llama3 | 128K | Meta 开源旗舰 | 通用对话、复杂推理 |
| llama3.2 | 128K | 最新版本、性能优化 | 多场景通用 |
| mistral | 32K | 平衡性能和速度 | 代码生成、通用任务 |
| gemma2 | 8K | Google 开源 | 轻量级任务 |
| qwen2 | 32K | 阿里开源、中文优化 | 中文场景 |
| codegemma | 8K | 代码专项 | 代码生成、补全 |
| llava | - | 多模态(仅图片) | 图文理解 |
配置参数¶
详细的配置参数说明请参考:Ollama API 文档
快速开始¶
启动 Ollama 服务¶
# 安装 Ollama
# macOS: brew install ollama
# Linux: curl -fsSL https://ollama.com/install.sh | sh
# 启动服务
ollama serve
# 下载模型
ollama pull llama3.2
基础用法¶
from tfrobot.brain.chain.llms import Ollama
from tfrobot.schema.message.conversation.message_dto import TextMessage
from tfrobot.schema.users import BaseUser
llm = Ollama(name="llama3.2")
user = BaseUser(name="用户", uid="1")
current_input = TextMessage(content="什么是量子计算?", creator=user)
result = llm.complete(current_input=current_input)
print(result.generations[0].text)
连接配置¶
from tfrobot.brain.chain.llms import Ollama
llm = Ollama(
name="llama3.2",
host="http://localhost", # Ollama 服务地址
port=11434, # Ollama 服务端口
timeout=180, # 请求超时(秒)
)
流式输出¶
from tfrobot.brain.chain.llms import Ollama
llm = Ollama(name="llama3.2", stream=True)
工具调用¶
from tfrobot.brain.chain.llms import OllamaWithTools
from tfrobot.drive.tool.tool import tool
@tool
def calculate(a: float, b: float) -> float:
"""计算两个数的和"""
return a + b
llm = OllamaWithTools(name="llama3.2")
result = llm.complete(
current_input=TextMessage(content="3.14 + 0.98 等于多少?", creator=user),
tools=[calculate]
)
错误处理¶
常见错误¶
| 错误场景 | 错误信息 | 解决方案 |
|---|---|---|
| 服务未启动 | Connection refused | 运行 ollama serve |
| 模型不存在 | model not found | 运行 ollama pull <model> |
| 连接超时 | timeout | 增加 timeout 参数 |
| 上下文超长 | context length exceeded | 减少 num_ctx 或缩短输入 |