目錄
用 Python 串接 Ollama(ollama 套件與 OpenAI SDK)
安裝
pip install ollama
請先確認 Ollama 服務正在執行,並已下載要使用的模型(例如 ollama pull qwen3:8b)。
基本對話
from ollama import chat
response = chat(
model="qwen3:8b",
messages=[
{"role": "system", "content": "請用繁體中文回答。"},
{"role": "user", "content": "用三點說明什麼是機器學習。"},
],
)
print(response.message.content)
回應物件也可以用字典的方式讀取:response["message"]["content"]。
串流輸出
讓文字一邊產生一邊顯示:
from ollama import chat
stream = chat(
model="qwen3:8b",
messages=[{"role": "user", "content": "寫一段 100 字的自我介紹範例"}],
stream=True,
)
for chunk in stream:
print(chunk.message.content, end="", flush=True)
print()
多輪對話:做一個終端機聊天程式
模型不會自己記住歷史,要把每一輪的訊息都存在清單中:
from ollama import chat
messages = [{"role": "system", "content": "你是一位親切的助理,請用繁體中文回答。"}]
while True:
user_input = input("你:").strip()
if user_input in {"exit", "quit", "離開"}:
break
messages.append({"role": "user", "content": user_input})
reply = ""
print("AI:", end="", flush=True)
for chunk in chat(model="qwen3:8b", messages=messages, stream=True):
piece = chunk.message.content
reply += piece
print(piece, end="", flush=True)
print()
messages.append({"role": "assistant", "content": reply})
對話越長,送出的內容越多,最後可能超過上下文長度。實務上可以只保留最近幾輪,或把舊的對話摘要起來。
參數與思考模式
response = chat(
model="qwen3:8b",
messages=[{"role": "user", "content": "1 到 100 的總和是多少?"}],
options={"temperature": 0.2, "num_ctx": 8192},
think=True,
keep_alive="30m",
)
print("思考:", response.message.thinking)
print("回答:", response.message.content)
讀取圖片
response = chat(
model="gemma3",
messages=[{
"role": "user",
"content": "這張圖片裡有什麼?",
"images": ["./photo.jpg"], # 也可以傳入 bytes 或 base64 字串
}],
)
print(response.message.content)
其他功能
import ollama
ollama.generate(model="qwen3:8b", prompt="一句話介紹台北") # 單次生成
ollama.list() # 已下載的模型
ollama.ps() # 已載入的模型
ollama.pull("nomic-embed-text") # 下載模型
ollama.show("qwen3:8b") # 模型資訊
ollama.embed(model="nomic-embed-text", input="你好") # 文字嵌入
連到其他主機
from ollama import Client
client = Client(host="http://192.168.1.50:11434")
response = client.chat(model="qwen3:8b", messages=[{"role": "user", "content": "你好"}])
print(response.message.content)
也可以設定環境變數 OLLAMA_HOST,預設的 chat() 函式就會使用它。
非同步
在 FastAPI 等非同步框架中使用:
import asyncio
from ollama import AsyncClient
async def main():
client = AsyncClient()
response = await client.chat(
model="qwen3:8b",
messages=[{"role": "user", "content": "你好"}],
)
print(response.message.content)
asyncio.run(main())
錯誤處理
import ollama
try:
ollama.chat(model="not-exist", messages=[{"role": "user", "content": "hi"}])
except ollama.ResponseError as e:
print("錯誤:", e.error, e.status_code)
if e.status_code == 404:
print("模型不存在,請先 ollama pull")
except ConnectionError:
print("連不到 Ollama,請確認服務有在執行")
改用 OpenAI Python SDK
如果你的程式原本使用 OpenAI SDK,只要修改 base_url:
pip install openai
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:11434/v1/",
api_key="ollama", # 必須填寫,但 Ollama 不會檢查
)
completion = client.chat.completions.create(
model="qwen3:8b",
messages=[{"role": "user", "content": "你好,請自我介紹"}],
)
print(completion.choices[0].message.content)
這樣同一份程式可以在本機模型和雲端 API 之間切換,LangChain、LlamaIndex 等框架也都能用同樣的方式接上 Ollama。
下一節介紹 JavaScript / Node.js 的用法。
更新於 2026年10月12日