Ollama API 应用指南
1. 基础信息
- 默认地址:
http://localhost:11434/api
- 数据格式:
application/json
- 支持方法:
POST
(主要)、GET
(部分接口)
2. 模型管理 API
(1) 列出本地模型
- 端点:
GET /api/tags
- 功能: 获取已下载的模型列表。
- 示例:
curl http://localhost:11434/api/tags
import requests response = requests.get("http://localhost:11434/api/tags") print(response.json()["models"])
(2) 拉取模型
- 端点:
POST /api/pull
- 参数:
name
: 模型名称(必需,如llama3:8b
)stream
: 是否流式显示进度(默认true
)insecure
: 是否跳过 TLS 验证(默认false
)
- 示例:
curl http://localhost:11434/api/pull -d '{"name": "mistral"}'
response = requests.post("http://localhost:11434/api/pull",json={"name": "mistral", "stream": False} )
(3) 删除模型
- 端点:
DELETE /api/delete
- 参数:
name
(模型名称) - 示例:
curl -X DELETE http://localhost:11434/api/delete -d '{"name": "llama2"}'
response = requests.delete("http://localhost:11434/api/delete",json={"name": "llama2"} )
(4) 创建自定义模型
- 端点:
POST /api/create
- 参数:
name
(模型名)、modelfile
(模型配置内容) - 示例:
curl http://localhost:11434/api/create -d '{"name": "my-llama","modelfile": "FROM llama3\nSYSTEM 你是一个法律助手" }'
3. 文本生成与交互
(1) 生成文本 (/api/generate
)
- 参数:
{"model": "模型名","prompt": "输入文本","system": "系统提示(可选)","template": "模板(覆盖默认提示格式)","context": [数组,历史上下文ID],"stream": false,"options": {"temperature": 0.8,"top_p": 0.9,"max_tokens": 1000,"num_ctx": 4096} }
- 响应:
{"model": "模型名","response": "生成文本","context": [新的上下文ID],"done": true }
- Python 流式处理:
response = requests.post("http://localhost:11434/api/generate",json={"model": "llama3", "prompt": "写一篇科幻小说开头", "stream": True},stream=True ) for line in response.iter_lines():if line:print(json.loads(line)["response"], end="", flush=True)
(2) 多轮对话 (/api/chat
)
- 参数:
{"model": "模型名","messages": [{"role": "user", "content": "内容1"},{"role": "assistant", "content": "内容2"}],"stream": false }
- 响应:
{"message": {"role": "assistant", "content": "回复内容"},"context": [上下文ID] }
- Python 示例:
messages = [{"role": "user", "content": "如何学习Python?"},{"role": "assistant", "content": "先掌握基础语法。"},{"role": "user", "content": "推荐一本书?"} ] response = requests.post("http://localhost:11434/api/chat",json={"model": "llama3", "messages": messages} ) print(response.json()["message"]["content"])
4. 嵌入向量 (/api/embeddings
)
- 参数:
{"model": "模型名","prompt": "输入文本","options": {"temperature": 0.5} # 可选参数 }
- 响应:
{"embedding": [0.1, -0.2, ...] # 浮点数数组 }
- Python 示例:
response = requests.post("http://localhost:11434/api/embeddings",json={"model": "llama3", "prompt": "自然语言处理"} ) vector = response.json()["embedding"]
5. 高级功能与参数
(1) 上下文延续
- 在生成请求中传递
context
数组以维持对话状态:response1 = requests.post("/api/generate", json={"model": "llama3", "prompt": "你好"}) context = response1.json()["context"]response2 = requests.post("/api/generate",json={"model": "llama3", "prompt": "继续上文", "context": context} )
(2) 性能调优参数
options
字段支持以下关键参数:{"num_ctx": 4096, // 上下文窗口大小"num_gqa": 8, // Grouped-Query Attention 组数"num_gpu": 1, // GPU 层数(仅限支持GPU的模型)"main_gpu": 0, // 主 GPU 索引"temperature": 0.7, // 随机性(0-1)"repeat_penalty": 1.1 // 抑制重复生成 }
6. 错误处理
- 常见状态码:
400
: 请求参数错误404
: 模型不存在500
: 服务器内部错误
- 错误响应格式:
{"error": "错误描述" }
7. 完整 Python 客户端示例
import ollama# 生成文本
response = ollama.generate(model='llama3', prompt='用一句话解释人工智能',options={'temperature': 0.5}
)
print(response['response'])# 流式对话
stream = ollama.chat(model='llama3',messages=[{'role': 'user', 'content': '写一首五言绝句'}],stream=True
)
for chunk in stream:print(chunk['message']['content'], end='', flush=True)# 获取嵌入向量
embedding = ollama.embeddings(model='llama3', prompt='深度学习')
print(embedding['embedding'][:5]) # 打印前5维
8. 注意事项
-
模型兼容性
- 不同模型支持的参数可能不同(如 GPU 加速需模型编译时启用 CUDA)。
-
长上下文处理
- 增大
num_ctx
可能导致内存不足,建议逐步测试。
- 增大
-
流式传输优化
- 使用
stream=True
时,客户端需逐块处理数据以减少延迟。
- 使用
-
自定义模型集成
- 通过
Modelfile
创建的模型可直接通过 API 调用(model: 自定义模型名
)。
- 通过
通过此指南,可全面掌握 Ollama API 的核心功能,适用于开发聊天机器人、自动化脚本、语义分析等多种场景。