Ollama 是一个用于运行和管理大型语言模型(LLM)的工具。它提供了简单且功能丰富的 API 接口,方便用户与模型交互。以下是 Ollama 的所有 API 及其详细用法。
/api/generate)生成文本是 Ollama 的核心功能,允许用户通过 API 与模型交互。
POST
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 | 否 | 生成文本的停止条件(如 )。 |
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
}/api/tags)获取当前系统中所有可用的模型列表。
GET
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"
}
]
}/api/pull)从远程仓库拉取指定模型。
POST
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."
}/api/delete)删除本地存储的指定模型。
DELETE
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."
}/api/show)获取指定模型的详细信息。
POST
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"
}
}/api/generate with stream=true)启用流式输出,实时获取生成的文本。
POST
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 | 否 | 生成文本的停止条件(如 )。 |
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
}/api/health)检查 Ollama 服务是否正常运行。
GET
http://localhost:11434/api/health
bash
curl http://localhost:11434/api/health
json
{
"status": "healthy"
}/api/cancel)停止正在进行的生成任务。
POST
http://localhost:11434/api/cancel
bash
curl -X POST http://localhost:11434/api/cancel
json
{
"status": "success",
"message": "Generation task canceled."
}/api/version)获取 Ollama 的版本信息。
GET
http://localhost:11434/api/version
bash
curl http://localhost:11434/api/version
json
{
"version": "0.1.0",
"build_date": "2023-10-01T12:00:00Z"
}/api/restart)重启 Ollama 服务。
POST
http://localhost:11434/api/restart
bash
curl -X POST http://localhost:11434/api/restart
json
{
"status": "success",
"message": "Ollama service restarted."
}/api/config)获取当前模型的配置信息。
GET
http://localhost:11434/api/config
bash
curl http://localhost:11434/api/config
json
{
"model": "llama2",
"temperature": 0.7,
"max_tokens": 100
}/api/config)更新当前模型的配置信息。
POST
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 服务交互。
确保 Ollama 服务已启动并运行在 localhost:11434。如果未启动,可以使用以下命令启动:
bash
ollama serve
/api/generate 进行推理/api/generate 是 Ollama 的核心 API,用于生成文本。
POST
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 | 否 | 生成文本的停止条件(如 )。 |
使用 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
}/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
}以下是使用 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)以下是使用 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);
});如果使用 Docker 运行 Ollama,可以通过容器调用 API。
bash
docker exec -it ollama curl http://localhost:11434/api/generate -d {
"model": "llama2",
"prompt": "Hello, how are you?",
"stream": false
}Ollama 本身并不直接支持文件上传和解析(如 PDF、Word 或 Text 文件)。但是,你可以通过以下步骤实现这一功能:
将文件内容提取为文本:使用工具将文件(如 PDF、Word)转换为纯文本。
将文本发送给 Ollama:将提取的文本作为输入,通过 Ollama API 进行推理。
以下是详细步骤和示例代码:
根据文件类型,安装相应的工具来提取文本内容。
使用 PyPDF2 或 pdfminer.six 提取 PDF 文件内容:
bash
pip install PyPDF2
使用 python-docx 提取 Word 文件内容:
bash
pip install python-docx
直接读取文本文件内容,无需额外工具。
以下是提取不同文件类型的示例代码。
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)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 + "
"
return text
docx_text = extract_text_from_docx("example.docx")
print(docx_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)将提取的文本作为输入,通过 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:
{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)如果文件较大,可以分段提取文本并分批发送给 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:
{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)如果使用 Docker 运行 Ollama,可以通过容器调用 API。
bash
docker exec -it ollama curl http://localhost:11434/api/generate -d {
"model": "llama2",
"prompt": "Please summarize the following text:
<extracted_text>",
"stream": false
}Ollama 是一个专注于文本生成和推理的工具,它本身并不直接支持图像处理或生成卡通图片的功能。如果你想实现上传人像图片并生成卡通图片,需要使用专门的图像处理工具或模型(如 Stable Diffusion、GANs 等),然后将生成的卡通图片与 Ollama 结合使用。
以下是实现这一功能的完整步骤:
你可以使用以下工具或模型将人像图片转换为卡通风格:
Stable Diffusion: 一个强劲的生成式 AI 模型,支持图像风格转换。
CartoonGAN: 专门用于生成卡通风格图像的 GAN 模型。
OpenCV: 通过图像处理技术实现卡通化效果。
DeepAI: 提供在线卡通化 API。
以下是一个简单的 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}")生成卡通图片后,你可以将其路径或描述发送给 Ollama,生成相关的文本描述或故事。
python
import requests
# 调用 Ollama API 生成描述
url = "http://localhost:11434/api/generate"
payload = {
"model": "llama2",
"prompt": "Describe the following cartoon image:
",
"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)如果你希望使用更强劲的生成式模型,可以尝试 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")如果你不想本地运行模型,可以使用在线服务(如 DeepAI 或 Runway ML)生成卡通图片。
注册 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)将以上步骤整合为一个完整的流程:
上传人像图片。
使用图像处理工具生成卡通图片。
将卡通图片的描述发送给 Ollama,生成相关的文本。
虽然 Ollama 本身不支持图像处理,但你可以通过结合图像处理工具(如 OpenCV、Stable Diffusion 或 DeepAI)和 Ollama 的文本生成能力,实现上传人像图片并生成卡通图片的功能。