Ollama本地部署
下載安裝ollama
https://ollama.com/download,windows版本國內網絡下載慢可以用迅雷下載比較快
查看有哪些model可供下載
https://ollama.com/library
安裝什么model
| 模型名稱 | 參數大小 | 推薦內存 | 速度 | 能力 | 特點 | 適用場景 |
|---|---|---|---|---|---|---|
qwen2.5:0.5b |
0.5B | < 1GB | ????? | ??☆ | 中文特化,速度極致 | 純中文快速對話 |
llama3.2:1b |
1B | ~1GB | ????? | ??? | 綜合最佳,生態好 | 通用入門首選 |
gemma2:2b |
2B | ~2GB | ???? | ??? | 均衡,安全 | 均衡任務 |
llama3.2:3b |
3B | ~3GB | ???? | ???☆ | 能力增強版 | 需要更強能力 |
phi3:mini |
3.8B | ~4GB | ???? | ???? | 小鋼炮,強推理 | 輕量編碼和推理 |
-
第一次嘗試,無腦選:
ollama run llama3.2:1b -
主要用中文,追求極致速度:
ollama run qwen2.5:0.5b -
感覺小模型有點弱,想試試強一點的:
ollama run phi3:mini或ollama run llama3.2:3b
安裝model
方法1.如圖,選擇model后隨便提個問題,就會自動下載選擇的model

方法2:ollama pull model, 如ollama pull llama2
查看已安裝的model
C:\Users\xxx>ollama list
NAME ID SIZE MODIFIED
llama2:latest 78e26419b446 3.8 GB About a minute ago
gpt-oss:20b aa4295ac10c3 13 GB 24 minutes ago
現在就可以在ollama UI窗口提問題了
ollama要求
- CPU:多核處理器(推薦 4 核或以上)。
- GPU:如果你計劃運行大型模型或進行微調,推薦使用具有較高計算能力的 GPU(如 NVIDIA 的 CUDA 支持)。
- 內存:至少 8GB RAM,運行較大模型時推薦 16GB 或更高。
- 存儲:需要足夠的硬盤空間來存儲預訓練模型,通常需要 10GB 至數百 GB 的空間,具體取決于模型的大小。
- 軟件要求:確保系統上安裝了最新版本的 Python(如果打算使用 Python SDK)。
我的電腦配置不夠,所以一個問題得等5分鐘才能答完
python ollama
pip install ollama
#一次性相響應
import ollama
response = ollama.generate(
model="qwen2.5:0.5b", # 模型名稱
prompt="JS怎么發起get post put delete請求", # 提示文本
stream=False
)
print(response)
"""
model='qwen2.5:0.5b' created_at='2025-08-30T14:33:53.9313696Z' done=True done_reason='stop' total_duration=21634910800 load_duration=91260900 prompt_eval_count=37 prompt_eval_duration=30577100 eval_count=580 eval_duration=21511551900 response="在JavaScript中,我們可以使用`XMLHttpRequest`或者Promise來發起不同類型的HTTP GET、POST、PUT和DELETE請求。以下是一些示例:\n\n1. **POST請求**:\n - 使用`XMLHttpRequest`:\n ```javascript\n var xhr = new XMLHttpRequest();\n xhr.open('POST', 'https://example.com/api/data');\n xhr.setRequestHeader('Content-Type', 'application/json');\n xhr.send(JSON.stringify({ key: 'value' }));\n ```\n - 使用Promise(瀏覽器):\n ```javascript\n const promise = new Promise((resolve, reject) => {\n xhr.open('POST', 'https://example.com/api/data');\n xhr.setRequestHeader('Content-Type', 'application/json');\n xhr.send(JSON.stringify({ key: 'value' }));\n });\n promise.then(data => console.log(data));\n promise.catch(reject);\n ```\n\n2. **GET請求**:\n - 使用`XMLHttpRequest`:\n ```javascript\n var xhr = new XMLHttpRequest();\n xhr.open('GET', 'https://example.com/api/data');\n xhr.send();\n ```\n - 使用Promise(瀏覽器):\n ```javascript\n const promise = new Promise((resolve, reject) => {\n xhr.open('GET', 'https://example.com/api/data');\n xhr.send();\n });\n promise.then(data => console.log(data));\n promise.catch(reject);\n ```\n\n3. **PUT請求**:\n - 使用`XMLHttpRequest`:\n ```javascript\n var xhr = new XMLHttpRequest();\n xhr.open('PUT', 'https://example.com/api/data');\n xhr.setRequestHeader('Content-Type', 'application/json');\n xhr.send(JSON.stringify({ key: 'value' }));\n ```\n - 使用Promise(瀏覽器):\n ```javascript\n const promise = new Promise((resolve, reject) => {\n xhr.open('PUT', 'https://example.com/api/data');\n xhr.setRequestHeader('Content-Type', 'application/json');\n xhr.send(JSON.stringify({ key: 'value' }));\n });\n promise.then(data => console.log(data));\n promise.catch(reject);\n ```\n\n4. **DELETE請求**:\n - 使用`XMLHttpRequest`:\n ```javascript\n var xhr = new XMLHttpRequest();\n xhr.open('DELETE', 'https://example.com/api/data');\n ```\n - 使用Promise(瀏覽器):\n ```javascript\n const promise = new Promise((resolve, reject) => {\n xhr.open('DELETE', 'https://example.com/api/data');\n xhr.send();\n });\n promise.then(data => console.log(data));\n promise.catch(reject);\n ```\n\n在每個請求中,我們都可以明確地指定目標URL、方法(POST、PUT、DELETE)、以及包含的參數。請根據需要調整URL和數據格式以適應具體需求。]
"""
#流式響應
import ollama response = ollama.generate( model="qwen2.5:0.5b", # 模型名稱 prompt="JS怎么發起get post put delete請求", # 提示文本 stream=True ) print(response) full_response = "" for chunk in response: # 每次獲取一個片段,并打印出來(實現打字機效果) part = chunk.get('response', '') print(part, end='', flush=True) # end='' 確保不換行 full_response += part # 打印一個換行,然后你可以使用完整的 full_response 變量 print("\n\n---完整回答已生成---")
"""
<generator object Client._request.<locals>.inner at 0x000002244C232440>
在JavaScript中,我們可以使用`fetch()` API來發送HTTP請求。以下是一些常見的GET、POST、PUT和DELETE請求的例子:
1. GET 請求:
```javascript
fetch('https://example.com')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
```
2. POST 請求:
```javascript
fetch('https://example.com', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ data: 'Hello, World!' })
})
.then(response => response.json())
.catch(error => console.error(error));
```
3. PUT 請求:
```javascript
fetch('https://example.com', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ data: 'Updated data!' })
})
.then(response => response.json())
.catch(error => console.error(error));
```
4. DELETE 請求:
```javascript
fetch('https://example.com', {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ data: 'Delete data!' })
})
.then(response => response.json())
.catch(error => console.error(error));
```
5. 其他請求方法:
- GET 請求:與`fetch('https://example.com')`相同。
- POST 請求:與`fetch('https://example.com', { method: 'POST' })`相同。
- PUT 請求:與`fetch('https://example.com', { method: 'PUT' })`相同。
- DELETE 請求:與`fetch('https://example.com', { method: 'DELETE')}`相同。
每個請求都會以JSON格式返回響應。如果你需要發送不同的數據,可以在請求頭中添加適當的字段(例如,用`Content-Type`設置為`application/json`),并且在發送請求時傳遞相應的參數或實體數據。
---完整回答已生成---
"""
#流式響應
from ollama import Client
client = Client(host='http://localhost:11434')
# 使用 chat 接口
response = client.chat(
model='qwen2.5:0.5b',
messages=[
{
'role': 'user',
'content': 'JS怎么發起get post put delete請求',
},
],
stream=True
)
full_response = ""
for chunk in response:
# 從 chunk 中獲取消息內容
content = chunk['message']['content']
print(content, end='', flush=True)
full_response += content
print("\n\n---完整回答已生成---")
#流式響應
from ollama import chat
stream = chat(
model='deepseek-coder',
messages=[{'role': 'user', 'content': 'JS網格布局'}],
stream=True,
)
# 逐塊打印響應內容
for chunk in stream:
print(chunk['message']['content'], end='', flush=True)
ollama命令
ollama serve #啟動 Ollama 服務以在后臺運行 ollama stop #停止正在運行的 Ollama 服務 ollama restart #重啟 Ollama 服務 ollama version #查看當前安裝的 Ollama 版本 ollama update #更新 Ollama 到最新版本 ollama clean #清理 Ollama 的緩存 ollama show <model-name>#查看指定模型的詳細信息 ollama deps <model-name> #查看模型的依賴關系 ollama config <model-name> #查看模型的配置文件 ollama export <model-name> <output-file> #將模型導出為文件 ollama import <input-file> #從文件導入模型 ollama system #查看 Ollama 的系統信息 ollama resources <model-name> #查看模型的資源使用情況 ollama perf <model-name> #查看模型的性能指標 ollama history <model-name> #查看模型的歷史記錄 ollama status <model-name> #檢查指定模型的狀態 ollama logs #查看 Ollama 的日志信息 ollama pull <model-name> #拉取模型 ollama run <model-name> #運行模型 ollama list #列出本地模型 ollama rm <model-name> #刪除模型 ollama create <custom-model-name> -f <Modelfile> #基于現有模型創建自定義模型 ollama cp <source-model-name> <new-model-name> #復制一個已存在的模型 ollama push <model-name>#推送自定義模型
ollama模型交互
>ollama run qwen2.5:0.5b #交互式運行模型 >>> who are you I am Qwen, a large language model developed by Alibaba Cloud to help with various tasks such as summarizing text and generating human-like responses. If you have any questions or need assistance with something specific, feel free to ask! >>> pyqt PyQt is a comprehensive library for creating desktop applications in Python. It provides extensive support for GUI programming, allowing developers to create richly interactive user interfaces, including widgets and graphical components that interact with the mouse and keyboard. Key features of PyQt include: 1. User interface creation: It supports various widget types such as buttons, sliders, lists, etc., which are commonly used in desktop applications. 2. Data handling: It is designed for data manipulation tasks such as filtering, searching, sorting, and plotting data. 3. Animation support: PyQt provides features like frames and animations to create interactive applications. 4. Event-driven programming: It supports event-based programming, allowing developers to control the state of GUI elements directly. 5. Cross-platform compatibility: PyQt can be run on Windows, macOS, and Linux. PyQt is widely used in various fields such as mobile app development, web applications, scientific computing, and more. It provides a wide range of tools and features that make it an essential tool for creating dynamic user interfaces. If you have any specific questions about PyQt or need help with implementing certain functionalities in your application, feel free to ask! >>> /bye #退出模型 ollama run qwen2.5:0.5b "pyqt"#命令行參數運行
echo "pyqt" | ollama run llama2:latest #使用管道運行模型
ollama API 交互
1. 啟動 Ollama 服務
在使用 API 之前,需要確保 Ollama 服務正在運行。可以通過以下命令啟動服務:
ollama serve
默認情況下,服務會運行在 http://localhost:11434。#所以你再次運行會報錯Error: listen tcp 127.0.0.1:11434: bind: Only one usage of each socket address (protocol/network address/port) is normally permitted.
2. API 端點
Ollama 提供了以下主要 API 端點:
生成文本(Generate Text)
端點:POST /api/generate
功能:向模型發送提示詞(prompt),并獲取生成的文本。
請求格式:
{
"model": "<model-name>", // 模型名稱
"prompt": "<input-text>", // 輸入的提示詞
"stream": false, // 是否啟用流式響應(默認 false)
"options": { // 可選參數
"temperature": 0.7, // 溫度參數
"max_tokens": 100 // 最大 token 數
}
}
響應格式:
{
"response": "<generated-text>", // 生成的文本
"done": true // 是否完成
}
聊天(Chat)
端點:POST /api/chat
功能:支持多輪對話,模型會記住上下文。
請求格式:
{
"model": "<model-name>", // 模型名稱
"messages": [ // 消息列表
{
"role": "user", // 用戶角色
"content": "<input-text>" // 用戶輸入
}
],
"stream": false, // 是否啟用流式響應
"options": { // 可選參數
"temperature": 0.7,
"max_tokens": 100
}
}
響應格式:
{
"message": {
"role": "assistant", // 助手角色
"content": "<generated-text>" // 生成的文本
},
"done": true
}
列出本地模型(List Models)
端點:GET /api/tags
功能:列出本地已下載的模型。
響應格式:
{
"models": [
{
"name": "<model-name>", // 模型名稱
"size": "<model-size>", // 模型大小
"modified_at": "<timestamp>" // 修改時間
}
]
}
拉取模型(Pull Model)
端點:POST /api/pull
功能:從模型庫中拉取模型。
請求格式:
{
"name": "<model-name>" // 模型名稱
}
響應格式:
{
"status": "downloading", // 下載狀態
"digest": "<model-digest>" // 模型摘要
}
3. 使用示例
生成文本
使用 curl 發送請求:
實例
curl http://localhost:11434/api/generate -d '{
"model": "deepseek-coder",
"prompt": "你好,你能幫我寫一段代碼嗎?",
"stream": false
}'
多輪對話
使用 curl 發送請求:
實例
curl http://localhost:11434/api/chat -d '{
"model": "deepseek-coder",
"messages": [
{
"role": "user",
"content": "你好,你能幫我寫一段 Python 代碼嗎?"
}
],
"stream": false
}'
列出本地模型
使用 curl 發送請求:
curl http://localhost:11434/api/tags
拉取模型
使用 curl 發送請求:
實例
curl http://localhost:11434/api/pull -d '{
"name": "deepseek-coder"
}'
4. 流式響應
Ollama 支持流式響應(streaming response),適用于實時生成文本的場景。
啟用流式響應
在請求中設置 "stream": true,API 會逐行返回生成的文本。
實例
curl http://localhost:11434/api/generate -d '{
"model": "deepseek-coder",
"prompt": "你好,你能幫我寫一段代碼嗎?",
"stream": true
}'
響應格式
每行返回一個 JSON 對象:
實例
{
"response": "<partial-text>", // 部分生成的文本
"done": false // 是否完成
}
5. 編程語言示例
Python 使用 requests 庫與 Ollama API 交互:
實例
import requests
# 生成文本
response = requests.post(
"http://localhost:11434/api/generate",
json={
"model": "deepseek-coder",
"prompt": "你好,你能幫我寫一段代碼嗎?",
"stream": False
}
)
print(response.json())
多輪對話:
實例
response = requests.post(
"http://localhost:11434/api/chat",
json={
"model": "deepseek-coder",
"messages": [
{
"role": "user",
"content": "你好,你能幫我寫一段 Python 代碼嗎?"
}
],
"stream": False
}
)
print(response.json())
JavaScript 使用 fetch API 與 Ollama 交互:
實例
// 生成文本
fetch("http://localhost:11434/api/generate", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "deepseek-coder",
prompt: "你好,你能幫我寫一段代碼嗎?",
stream: false
})
})
.then(response => response.json())
.then(data => console.log(data));
多輪對話:
實例
fetch("http://localhost:11434/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "deepseek-coder",
messages: [
{
role: "user",
content: "你好,你能幫我寫一段 Python 代碼嗎?"
}
],
stream: false
})
})
.then(response => response.json())
.then(data => console.log(data));
浙公網安備 33010602011771號