Ollama 是一个用于运行和管理大型语言模型(LLM)的工具。它提供了简单且功能丰富的 API 接口,方便用户与模型交互。以下是 Ollama 的所有 API 及其详细用法。
1. 生成文本 (/api/generate)
生成文本是 Ollama 的核心功能,允许用户通过 API 与模型交互。
请求方法
POST
请求 URL
http://localhost:11434/api/generate
请求参数
| 参数名 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
model |
string | 是 | 要使用的模型名称(如 llama2)。 |
prompt |
string | 是 | 输入提示文本。 |
stream |
bool | 否 | 是否启用流式输出(默认 false)。 |
max_tokens |
int | 否 | 生成文本的最大 token 数量(默认无限制)。 |
temperature |
float | 否 | 控制生成文本的随机性(默认 1.0,范围 0.0 到 2.0)。 |
top_p |
float | 否 | 控制生成文本的多样性(默认 1.0,范围 0.0 到 1.0)。 |
stop |
string | 否 | 生成文本的停止条件(如 \n)。 |
示例请求
curl http://localhost:11434/api/generate -d '{
"model": "llama2",
"prompt": "Hello, how are you?",
"stream": false,
"max_tokens": 50,
"temperature": 0.7
}'
响应示例
{
"response": "I'm fine, thank you! How can I assist you today?",
"done": true
}
2. 列出可用模型 (/api/tags)
获取当前系统中所有可用的模型列表。
请求方法
GET
请求 URL
http://localhost:11434/api/tags
示例请求
curl http://localhost:11434/api/tags
响应示例
{
"models": [
{
"name": "llama2",
"size": "7B",
"modified_at": "2023-10-01T12:00:00Z"
},
{
"name": "tinyllama",
"size": "1B",
"modified_at": "2023-10-01T12:00:00Z"
}
]
}
3. 拉取模型 (/api/pull)
从远程仓库拉取指定模型。
请求方法
POST
请求 URL
http://localhost:11434/api/pull
请求参数
| 参数名 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
name |
string | 是 | 要拉取的模型名称。 |
stream |
bool | 否 | 是否启用流式输出(默认 false)。 |
示例请求
curl http://localhost:11434/api/pull -d '{
"name": "llama2",
"stream": false
}'
响应示例
json
{
"status": "success",
"message": "Model 'llama2' pulled successfully."
}
4. 删除模型 (/api/delete)
删除本地存储的指定模型。
请求方法
DELETE
请求 URL
http://localhost:11434/api/delete
请求参数
| 参数名 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
name |
string | 是 | 要删除的模型名称。 |
示例请求
bash
curl -X DELETE http://localhost:11434/api/delete -d '{
"name": "llama2"
}'
响应示例
json
{
"status": "success",
"message": "Model 'llama2' deleted successfully."
}
5. 获取模型信息 (/api/show)
获取指定模型的详细信息。
请求方法
POST
请求 URL
http://localhost:11434/api/show
请求参数
| 参数名 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
name |
string | 是 | 要查询的模型名称。 |
示例请求
bash
curl http://localhost:11434/api/show -d '{
"name": "llama2"
}'
响应示例
json
{
"name": "llama2",
"size": "7B",
"modified_at": "2023-10-01T12:00:00Z",
"details": {
"architecture": "Transformer",
"license": "Apache 2.0"
}
}
6. 流式生成文本 (/api/generate with stream=true)
启用流式输出,实时获取生成的文本。
请求方法
POST
请求 URL
http://localhost:11434/api/generate
请求参数
| 参数名 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
model |
string | 是 | 要使用的模型名称。 |
prompt |
string | 是 | 输入提示文本。 |
stream |
bool | 是 | 必须设置为 true。 |
max_tokens |
int | 否 | 生成文本的最大 token 数量(默认无限制)。 |
temperature |
float | 否 | 控制生成文本的随机性(默认 1.0,范围 0.0 到 2.0)。 |
top_p |
float | 否 | 控制生成文本的多样性(默认 1.0,范围 0.0 到 1.0)。 |
stop |
string | 否 | 生成文本的停止条件(如 \n)。 |
示例请求
bash
curl http://localhost:11434/api/generate -d '{
"model": "llama2",
"prompt": "Hello, how are you?",
"stream": true
}'
响应示例
json
{
"response": "I'm fine, thank you!",
"done": false
}
{
"response": " How can I assist you today?",
"done": true
}
7. 检查服务状态 (/api/health)
检查 Ollama 服务是否正常运行。
请求方法
GET
请求 URL
http://localhost:11434/api/health
示例请求
bash
curl http://localhost:11434/api/health
响应示例
json
{
"status": "healthy"
}
8. 停止生成 (/api/cancel)
停止正在进行的生成任务。
请求方法
POST
请求 URL
http://localhost:11434/api/cancel
示例请求
bash
curl -X POST http://localhost:11434/api/cancel
响应示例
json
{
"status": "success",
"message": "Generation task canceled."
}
9. 获取版本信息 (/api/version)
获取 Ollama 的版本信息。
请求方法
GET
请求 URL
http://localhost:11434/api/version
示例请求
bash
curl http://localhost:11434/api/version
响应示例
json
{
"version": "0.1.0",
"build_date": "2023-10-01T12:00:00Z"
}
10. 重启服务 (/api/restart)
重启 Ollama 服务。
请求方法
POST
请求 URL
http://localhost:11434/api/restart
示例请求
bash
curl -X POST http://localhost:11434/api/restart
响应示例
json
{
"status": "success",
"message": "Ollama service restarted."
}
11. 获取模型配置 (/api/config)
获取当前模型的配置信息。
请求方法
GET
请求 URL
http://localhost:11434/api/config
示例请求
bash
curl http://localhost:11434/api/config
响应示例
json
{
"model": "llama2",
"temperature": 0.7,
"max_tokens": 100
}
12. 更新模型配置 (/api/config)
更新当前模型的配置信息。
请求方法
POST
请求 URL
http://localhost:11434/api/config
请求参数
| 参数名 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
model |
string | 否 | 要更新的模型名称。 |
temperature |
float | 否 | 控制生成文本的随机性(默认 1.0,范围 0.0 到 2.0)。 |
max_tokens |
int | 否 | 生成文本的最大 token 数量(默认无限制)。 |
top_p |
float | 否 | 控制生成文本的多样性(默认 1.0,范围 0.0 到 1.0)。 |
示例请求
bash
curl -X POST http://localhost:11434/api/config -d '{
"temperature": 0.8,
"max_tokens": 200
}'
响应示例
json
{
"status": "success",
"message": "Model configuration updated."
}
总结
以上是 Ollama 的所有 API 及其详细用法。通过这些 API,您可以轻松地管理模型、生成文本并与 Ollama 服务交互。
2.Ollama API进行模型推理
1. 启动 Ollama 服务
确保 Ollama 服务已启动并运行在 localhost:11434。如果未启动,可以使用以下命令启动:
bash
ollama serve
2. 使用 /api/generate 进行推理
/api/generate 是 Ollama 的核心 API,用于生成文本。
请求方法
POST
请求 URL
http://localhost:11434/api/generate
请求参数
| 参数名 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
model |
string | 是 | 要使用的模型名称(如 llama2)。 |
prompt |
string | 是 | 输入提示文本。 |
stream |
bool | 否 | 是否启用流式输出(默认 false)。 |
max_tokens |
int | 否 | 生成文本的最大 token 数量(默认无限制)。 |
temperature |
float | 否 | 控制生成文本的随机性(默认 1.0,范围 0.0 到 2.0)。 |
top_p |
float | 否 | 控制生成文本的多样性(默认 1.0,范围 0.0 到 1.0)。 |
stop |
string | 否 | 生成文本的停止条件(如 \n)。 |
示例请求
使用 curl 进行请求:
bash
curl http://localhost:11434/api/generate -d '{
"model": "llama2",
"prompt": "Hello, how are you?",
"stream": false,
"max_tokens": 50,
"temperature": 0.7
}'
响应示例
json
{
"response": "I'm fine, thank you! How can I assist you today?",
"done": true
}
3. 使用 /api/generate 进行流式推理
如果需要实时获取生成的文本,可以启用流式输出。
示例请求
bash
curl http://localhost:11434/api/generate -d '{
"model": "llama2",
"prompt": "Hello, how are you?",
"stream": true
}'
响应示例
json
{
"response": "I'm fine, thank you!",
"done": false
}
{
"response": " How can I assist you today?",
"done": true
}
4. 使用 Python 进行推理
以下是使用 Python 调用 Ollama API 的示例代码。
安装依赖
bash
pip install requests
示例代码
python
import requests
url = "http://localhost:11434/api/generate"
payload = {
"model": "llama2",
"prompt": "Hello, how are you?",
"stream": False,
"max_tokens": 50,
"temperature": 0.7
}
response = requests.post(url, json=payload)
if response.status_code == 200:
result = response.json()
print("Generated Text:", result["response"])
else:
print("Error:", response.status_code, response.text)
5. 使用 JavaScript 进行推理
以下是使用 JavaScript 调用 Ollama API 的示例代码。
示例代码
javascript
const fetch = require('node-fetch');
const url = "http://localhost:11434/api/generate";
const payload = {
model: "llama2",
prompt: "Hello, how are you?",
stream: false,
max_tokens: 50,
temperature: 0.7
};
fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
})
.then(response => response.json())
.then(data => {
console.log("Generated Text:", data.response);
})
.catch(error => {
console.error("Error:", error);
});
6. 使用 Docker 进行推理
如果使用 Docker 运行 Ollama,可以通过容器调用 API。
示例请求
bash
docker exec -it ollama curl http://localhost:11434/api/generate -d '{
"model": "llama2",
"prompt": "Hello, how are you?",
"stream": false
}'
3.ollama知识库文件推理
Ollama 本身并不直接支持文件上传和解析(如 PDF、Word 或 Text 文件)。但是,你可以通过以下步骤实现这一功能:
- 将文件内容提取为文本:使用工具将文件(如 PDF、Word)转换为纯文本。
- 将文本发送给 Ollama:将提取的文本作为输入,通过 Ollama API 进行推理。
以下是详细步骤和示例代码:
1. 安装文件解析工具
根据文件类型,安装相应的工具来提取文本内容。
PDF 文件
使用 PyPDF2 或 pdfminer.six 提取 PDF 文件内容:
bash
pip install PyPDF2
Word 文件
使用 python-docx 提取 Word 文件内容:
bash
pip install python-docx
Text 文件
直接读取文本文件内容,无需额外工具。
2. 提取文件内容
以下是提取不同文件类型的示例代码。
PDF 文件
python
from PyPDF2 import PdfReader
def extract_text_from_pdf(file_path):
reader = PdfReader(file_path)
text = ""
for page in reader.pages:
text += page.extract_text()
return text
pdf_text = extract_text_from_pdf("example.pdf")
print(pdf_text)
Word 文件
python
from docx import Document
def extract_text_from_docx(file_path):
doc = Document(file_path)
text = ""
for paragraph in doc.paragraphs:
text += paragraph.text + "\n"
return text
docx_text = extract_text_from_docx("example.docx")
print(docx_text)
Text 文件
python
def extract_text_from_txt(file_path):
with open(file_path, "r", encoding="utf-8") as file:
text = file.read()
return text
txt_text = extract_text_from_txt("example.txt")
print(txt_text)
3. 将文本发送给 Ollama
将提取的文本作为输入,通过 Ollama API 进行推理。
示例代码
python
import requests
# 提取文件内容
file_path = "example.pdf" # 替换为你的文件路径
if file_path.endswith(".pdf"):
text = extract_text_from_pdf(file_path)
elif file_path.endswith(".docx"):
text = extract_text_from_docx(file_path)
elif file_path.endswith(".txt"):
text = extract_text_from_txt(file_path)
else:
raise ValueError("Unsupported file format")
# 调用 Ollama API
url = "http://localhost:11434/api/generate"
payload = {
"model": "llama2",
"prompt": f"Please summarize the following text:\n{text}",
"stream": False,
"max_tokens": 500,
"temperature": 0.7
}
response = requests.post(url, json=payload)
if response.status_code == 200:
result = response.json()
print("Generated Text:", result["response"])
else:
print("Error:", response.status_code, response.text)
4. 处理大文件
如果文件较大,可以分段提取文本并分批发送给 Ollama。
示例代码
python
def chunk_text(text, max_length=1000):
return [text[i:i + max_length] for i in range(0, len(text), max_length)]
text_chunks = chunk_text(text)
for chunk in text_chunks:
payload = {
"model": "llama2",
"prompt": f"Please summarize the following text:\n{chunk}",
"stream": False,
"max_tokens": 500,
"temperature": 0.7
}
response = requests.post(url, json=payload)
if response.status_code == 200:
result = response.json()
print("Generated Text:", result["response"])
else:
print("Error:", response.status_code, response.text)
5. 使用 Docker 运行
如果使用 Docker 运行 Ollama,可以通过容器调用 API。
示例请求
bash
docker exec -it ollama curl http://localhost:11434/api/generate -d '{
"model": "llama2",
"prompt": "Please summarize the following text:\n<extracted_text>",
"stream": false
}'
4.人像图片,生成卡通图片
Ollama 是一个专注于文本生成和推理的工具,它本身并不直接支持图像处理或生成卡通图片的功能。如果你想实现上传人像图片并生成卡通图片,需要使用专门的图像处理工具或模型(如 Stable Diffusion、GANs 等),然后将生成的卡通图片与 Ollama 结合使用。
以下是实现这一功能的完整步骤:
1. 使用图像处理工具生成卡通图片
你可以使用以下工具或模型将人像图片转换为卡通风格:
工具推荐
- Stable Diffusion: 一个强大的生成式 AI 模型,支持图像风格转换。
- CartoonGAN: 专门用于生成卡通风格图像的 GAN 模型。
- OpenCV: 通过图像处理技术实现卡通化效果。
- DeepAI: 提供在线卡通化 API。
示例:使用 OpenCV 实现卡通化
以下是一个简单的 Python 示例,使用 OpenCV 将人像图片转换为卡通风格:
python
import cv2
def cartoonize_image(image_path):
# 读取图片
image = cv2.imread(image_path)
# 转换为灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 使用中值滤波去除噪声
gray = cv2.medianBlur(gray, 5)
# 使用自适应阈值生成边缘
edges = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 9)
# 将图像转换为卡通风格
color = cv2.bilateralFilter(image, 9, 300, 300)
cartoon = cv2.bitwise_and(color, color, mask=edges)
# 保存卡通化图片
output_path = "cartoonized_image.png"
cv2.imwrite(output_path, cartoon)
return output_path
# 使用示例
input_image = "portrait.jpg"
cartoon_image = cartoonize_image(input_image)
print(f"Cartoonized image saved to: {cartoon_image}")
2. 将生成的卡通图片与 Ollama 结合
生成卡通图片后,你可以将其路径或描述发送给 Ollama,生成相关的文本描述或故事。
示例:生成卡通图片的描述
python
import requests
# 调用 Ollama API 生成描述
url = "http://localhost:11434/api/generate"
payload = {
"model": "llama2",
"prompt": "Describe the following cartoon image:\n",
"stream": False,
"max_tokens": 100,
"temperature": 0.7
}
response = requests.post(url, json=payload)
if response.status_code == 200:
result = response.json()
print("Generated Description:", result["response"])
else:
print("Error:", response.status_code, response.text)
3. 使用 Stable Diffusion 生成卡通图片
如果你希望使用更强大的生成式模型,可以尝试 Stable Diffusion。
示例:使用 Stable Diffusion 生成卡通图片
-
安装
diffusers库:bash
pip install diffusers transformers torch -
使用以下代码生成卡通图片:
python
from diffusers import StableDiffusionPipeline import torch # 加载模型 model_id = "stabilityai/stable-diffusion-2-1" pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16) pipe = pipe.to("cuda") # 生成卡通图片 prompt = "A cartoon style portrait of a person" image = pipe(prompt).images[0] # 保存图片 image.save("cartoon_portrait.png") print("Cartoon image saved to: cartoon_portrait.png")
4. 使用在线服务生成卡通图片
如果你不想本地运行模型,可以使用在线服务(如 DeepAI 或 Runway ML)生成卡通图片。
示例:使用 DeepAI API
注册 DeepAI 并获取 API 密钥。
-
使用以下代码生成卡通图片:
python
import requests # DeepAI API 配置 api_key = "your-deepai-api-key" url = "https://api.deepai.org/api/cartoon-generator" headers = {"api-key": api_key} # 上传图片并生成卡通图片 with open("portrait.jpg", "rb") as file: response = requests.post(url, files={"image": file}, headers=headers) if response.status_code == 200: result = response.json() print("Cartoon image URL:", result["output_url"]) else: print("Error:", response.status_code, response.text)
5. 整合流程
将以上步骤整合为一个完整的流程:
- 上传人像图片。
- 使用图像处理工具生成卡通图片。
- 将卡通图片的描述发送给 Ollama,生成相关的文本。
总结
虽然 Ollama 本身不支持图像处理,但你可以通过结合图像处理工具(如 OpenCV、Stable Diffusion 或 DeepAI)和 Ollama 的文本生成能力,实现上传人像图片并生成卡通图片的功能。