是一個開源工具,旨在讓開發者和使用者能夠輕鬆地在個人電腦上(macOS、Windows、Linux)下載、設定並運行大型語言模型(LLM),例如:Llama3、Mistral、Gemma、Qwen 等。它將模型的複雜設定打包成一個簡單的服務,並提供REST API,能用幾行程式碼就與強大AI模型互動
簡單易用
:一條指令就能下載並運行一個模型,無需處理複雜Python環境和依賴項本地運行保障隱私
:所有模型和資料都保存在自己的電腦上,不需將敏感資訊傳送到雲端高效能
:Ollama 為不同作業系統進行了最佳化,能有效利用硬體資源(特別是GPU)開放生態系
:支援匯入 GGUF 等多種開放模型格式,並擁有活躍的社群標準化API
:提供與 OpenAI 相容的 REST API,讓現有應用程式可以輕鬆遷移+-------------------+ +----------------+
| 你的應用程式 | ---> | Ollama API | ---> [ LLaMA / Mistral / Phi-3 模型 ]
+-------------------+ +----------------+
↑ ↓
(HTTP 請求) (本地推理)
簡單來說:
curl -fsSL https://ollama.com/install.sh | sh
到官方網站下載安裝程式:https://ollama.com
指令 | 功能 |
---|---|
ollama run llama3 |
運行 LLaMA 3 模型 |
ollama pull mistral |
下載 Mistral 模型 |
ollama list |
查看已下載模型 |
ollama rm modelname |
刪除模型 |
# 啟動 LLaMA 3 模型對話
ollama run llama3
> 你好,幫我寫一句 AI 廣告詞
import requests
# 發送 Prompt 到本地 Ollama API
response = requests.post(
'http://localhost:11434/api/generate',
json={
"model": "llama3",
"prompt": "用中文解釋什麼是 Ollama"
}
)
for line in response.iter_lines():
if line:
print(line.decode('utf-8'))
(A) 基本文字生成 (Generation)
這是最簡單用法,傳送一段文字,取得模型的回應
import ollama
# 確保你已經透過 `ollama run qwen:1.8b` 下載了該模型
try:
response = ollama.generate(
model='qwen:1.8b',
prompt='為什麼天空是藍色的?'
)
print(response['response'])
except ollama.ResponseError as e:
print(f"錯誤:{e.error}")
print("請確認模型 'qwen:1.8b' 是否已下載並可運行。")
print("你可以使用指令 `ollama list` 來查看已安裝的模型。")
程式碼解析:
import ollama
:匯入函式庫ollama.generate()
:核心函式model='qwen:1.8b'
:指定要使用的模型,必須是ollama list中存在的模型prompt='...'
:要傳送給模型的提示詞response['response']
:回應是一個字典,其中response鍵對應的值就是模型生成的文字(B) 串流 (Streaming) 回應
對聊天應用,逐字顯示回應能大幅改善使用者體驗,這就是「串流」
import ollama
import sys
# 使用 stream=True 來啟用串流模式
stream = ollama.generate(
model='qwen:1.8b',
prompt='請寫一首關於宇宙的短詩',
stream=True
)
# stream 是一個產生器 (generator),我們需要遍歷它來取得每個部分
print("模型正在生成回應:")
for chunk in stream:
# chunk 是一個字典,其中 'response' 鍵包含了一小段文字
if 'response' in chunk:
print(chunk['response'], end='', flush=True)
print("\n\n生成完畢。")
程式碼解析:
stream=True
:啟用串流模式(C) 對話模式 (Chat Completions)
需要上下文多輪對話,使用chat模式更為合適
import ollama
# messages 是一個列表,用來存放對話歷史
messages = [
{
'role': 'user',
'content': '你好,我對天文學很感興趣。',
},
]
# 第一次對話
response = ollama.chat(model='qwen:1.8b', messages=messages)
assistant_response = response['message']['content']
print(f"AI: {assistant_response}")
# 將 AI 的回應加入對話歷史
messages.append({'role': 'assistant', 'content': assistant_response})
# 基於上面的上下文,提出新的問題
print("\n--- 第二輪對話 ---")
messages.append({
'role': 'user',
'content': '那請為我解釋一下什麼是黑洞?'
})
# 再次呼叫 chat,這次會包含之前的對話歷史
response_2 = ollama.chat(model='qwen:1.8b', messages=messages)
print(f"AI: {response_2['message']['content']}")
程式碼解析:
ollama.chat()
:對話專用的函式messages
:列表中的每個元素都是一個字典,包含 role (角色 user 或 assistant) 和 content (內容)(D) 生成Embedding
Embedding 是將文字轉換為向量的技術,對於語義搜尋、RAG(檢索增強生成)等等應用至關重要
import ollama
# 要轉換為 embedding 的文字
text_to_embed = "太陽是太陽系的中心"
# 呼叫 embeddings 函式
response = ollama.embeddings(
model='mxbai-embed-large', # 建議使用專門的 embedding 模型
prompt=text_to_embed
)
# 取得 embedding 向量
embedding_vector = response['embedding']
print(f"成功生成 Embedding!")
print(f"向量維度: {len(embedding_vector)}")
print(f"向量前 5 個值: {embedding_vector[:5]}")
# 注意:你需要先下載 embedding 模型 `ollama pull mxbai-embed-large`
進階主題:使用 Modelfile 自訂模型
Modelfile 類似於 Dockerfile,它允許現有模型創建一個自訂版本。可以用它來設定系統提示詞 (System Prompt)、調整模型參數等等
範例
:創建一個「古文翻譯助理」
1.建立一個名為 Modelfile 的檔案 (沒有副檔名)
# 基於 qwen:1.8b 模型
FROM qwen:1.8b
# 設定系統提示詞,定義 AI 的角色和行為
SYSTEM """
你是一個專業的古文翻譯大師。
你的任務是將使用者提供的任何現代中文句子翻譯成典雅的文言文。
你不需要解釋,只需要提供翻譯結果。
"""
# 設定模型溫度,值越低,回應越確定;值越高,越有創意
PARAMETER temperature 0.3
2.在終端機中使用 ollama create 指令創建模型:
# -f 指定 Modelfile 路徑
# guwen-translator 是你給新取的名字
ollama create guwen-translator -f ./Modelfile
3.運行你自訂的模型:
ollama run guwen-translator "我今天心情很好,想出去走走。"
4.或者在 Python 程式碼中使用:
import ollama
response = ollama.generate(
model='guwen-translator', # 使用你自訂的模型名稱
prompt='網路上的資訊太多,讓人眼花撩亂。'
)
print(response['response'])
這個自訂模型現在就有了固定的「人設」,每次調用都無需重複提供系統提示詞
const response = await fetch("http://localhost:11434/api/generate", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "llama3",
prompt: "請用三句話介紹 Ollama"
})
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
console.log(decoder.decode(value));
}
Ollama 的魅力在於其標準 API,讓各種語言都能輕鬆整合
JavaScript/TypeScript
:
官方函式庫
: ollama-js (npm install ollama)
import ollama from 'ollama'
const response = await ollama.chat({
model: 'llama3',
messages: [{ role: 'user', content: 'Why is the sky blue?' }],
})
console.log(response.message.content)
Ollama 與 LangChain 和 LlamaIndex 這兩個主流 LLM 應用框架無縫整合,可以非常方便地用來建構複雜AI應用,例如:RAG (檢索增強生成)、Agent 等等
LangChain Python 範例
:
from langchain_community.llms import Ollama
from langchain_core.prompts import ChatPromptTemplate
# 初始化 Ollama 模型
llm = Ollama(model="qwen:1.8b")
# 建立一個提示模板
prompt = ChatPromptTemplate.from_messages([
("system", "你是一個世界級的廚師。"),
("user", "{input}")
])
# 建立一個處理鏈 (Chain)
chain = prompt | llm
# 呼叫鏈
response = chain.invoke({"input": "我只有雞蛋、番茄和米飯,能做什麼菜?"})
print(response)
Ollama 大幅降低了在本地端使用大型語言模型的門檻。無論是想快速驗證想法的開發者、注重資料隱私的使用者,還是希望打造複雜 AI 應用工程師,Ollama 都提供了一個絕佳起點。從簡單的指令行互動,到利用 Python/JS 進行串流和對話,再到透過 Modelfile 打造專屬模型,Ollama 讓本地端 AI 開發變得前所未有的簡單和強大