Ollama 本地部署完整教學:從第一個模型,到程式能呼叫的 AI API
本地 AI 實作 02|資料核對:2026 年 11 月 30 日
把模型下載到電腦,只完成部署的一部分。真正能接進工作流程的本地 AI,還要能被程式呼叫、確認使用的運算資源,並在出錯時知道問題發生在哪一層。
這篇帶你完成三個可驗收的結果:電腦能回答問題、同一台電腦的程式能收到回答,以及你知道它正在使用哪個模型。範例採用 qwen3:4b,因為官方模型庫有明確標籤與容量資訊,適合用來理解流程;它是教學範例,不是所有任務的最佳模型。
一、先理解你要裝的是什麼
Ollama 是執行與管理模型的工具,模型權重則是另外下載的資料。程式透過 API 把問題交給 Ollama,再取得模型產生的回答。
本文只連到本機 http://127.0.0.1:11434。官方文件區分本機 API 與雲端 API;本機模型呼叫不需要 Ollama 雲端金鑰,但 Ollama 也能使用雲端模型。因此,看到 Ollama 視窗或 localhost 網址,仍應確認選的是已下載的本機模型。API 位址與認證說明
先準備電腦可用的記憶體與磁碟空間。qwen3:4b 在核對時的官方下載大小約為 2.5GB,量化為 Q4_K_M;執行時還需要快取與其他工作空間,不能把 2.5GB 當成完整的顯存需求。模型標籤與檔案資訊
二、依作業系統安裝,再確認終端機認得指令
Windows
從 Ollama 官方下載頁取得安裝程式,完成後開啟 Ollama,再開一個新的 PowerShell 視窗。官方 Windows 版會在背景提供服務;不必先架設 Docker。若有獨立顯示卡,另外確認驅動與官方支援條件。Windows 安裝與需求
macOS
從官方 macOS 下載頁取得安裝檔,將 App 放進 Applications 並啟動,依提示完成命令列工具設定,再開 Terminal。官方文件目前列出 macOS 14 或更新版本;Apple M 系列可使用 CPU 與 GPU,Intel Mac 的路徑是 CPU。macOS 安裝與需求
Linux
官方提供安裝腳本。以下將下載與執行拆開,方便先查看腳本內容;less 按 q 離開後再執行下一行。
curl -fsSL https://ollama.com/install.sh -o install-ollama.sh
less install-ollama.sh
sh install-ollama.sh
若服務沒有自動啟動,可在一個終端機執行 ollama serve,保持該視窗開啟,再用另一個終端機操作模型。已在背景執行時不需要重複啟動。Linux 官方安裝與服務設定
三種系統都先輸入:
ollama --version
能看到版本資訊才繼續。若顯示找不到指令,先重新開終端機,檢查安裝與 PATH;這時尚未進入模型好不好用的問題。
三、下載指定模型標籤,完成第一個對話
依序執行:
ollama pull qwen3:4b
ollama list
ollama show qwen3:4b
ollama run qwen3:4b
pull 下載模型,list 列出已下載項目,show 查看指定模型資訊,run 開始對話。記下 list 顯示的模型名稱與 ID,之後比較效果時才不會拿不同版本混在一起。Ollama CLI 文件
進入對話後,先設定一個較容易排查的上下文起點:
/set parameter num_ctx 4096
接著輸入這段原創驗收題:
請使用繁體中文,只根據以下資料回答:
測試活動於 12 月 6 日舉辦,共 24 個名額,已報名 17 人。
請列出剩餘名額,並說明資料是否提供活動地點。
若未提供,不要猜測。
預期應指出剩餘 7 個名額,且沒有提供活動地點。答案正確才算通過這一題;文字看起來流暢並不足夠。這只是連線與基本行為驗收,不代表模型已能勝任所有工作。
輸入 /bye 離開對話。另開終端機或趁模型仍載入時執行 ollama ps,查看處理器欄位是 GPU、CPU,或兩者混合。ollama list 是磁碟上的模型清單,ollama ps 才是目前載入的模型。上下文與運算資源檢查
四、讓程式收到第一個 API 回應
以下兩段擇一使用,功能相同。它們明確指定模型、4096 tokens 上下文,並使用 stream: false,讓第一次練習直接取得完整 JSON。think: false 用於這裡的 Qwen3 範例;換其他模型時,要依它支援的思考控制調整。Chat API、思考模式
macOS/Linux:Terminal
curl http://127.0.0.1:11434/api/chat \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3:4b",
"messages": [
{"role": "user", "content": "用繁體中文,一句話解釋什麼是本地模型。"}
],
"stream": false,
"think": false,
"options": {"num_ctx": 4096, "num_predict": 256}
}'
Windows:PowerShell
$payload = @{
model = "qwen3:4b"
messages = @(
@{ role = "user"; content = "用繁體中文,一句話解釋什麼是本地模型。" }
)
stream = $false
think = $false
options = @{ num_ctx = 4096; num_predict = 256 }
} | ConvertTo-Json -Depth 6
$response = Invoke-RestMethod `
-Uri "http://127.0.0.1:11434/api/chat" `
-Method Post `
-ContentType "application/json; charset=utf-8" `
-Body ([System.Text.Encoding]::UTF8.GetBytes($payload))
$response.message.content
PowerShell 的續行符號是反引號,後面不能再多空格。這裡明確轉為 UTF-8,避免中文請求在不同終端機環境中出現編碼問題。
原始 JSON 的最終回答位於 message.content。若使用串流,程式要逐段讀取資料;不能把多行串流 JSON 當作單一 JSON 解析。第一次先關閉串流,是為了減少與模型能力無關的排錯因素。
五、從「接通」走到「可以重複使用」
為每次驗收記下:作業系統、Ollama 版本、模型名稱與 ID、上下文、輸出上限、是否思考,以及題目。只改一個設定,再重跑同一批題目。
API 回傳的 load_duration、eval_count、eval_duration 可協助區分載入時間與生成時間;官方時間欄位使用奈秒。若 eval_duration 大於零,可用 eval_count ÷ (eval_duration / 1,000,000,000) 計算該次回應的生成速率。這不是使用者從送出到看見第一個字的等待時間,也不包含整段應用流程。回傳欄位定義
先做一次暖機,再重複同一組短題目,分開記錄品質與耗時。沒有這些紀錄,「昨天很快、今天很慢」很難定位究竟是模型、輸入長度、冷啟動,還是其他程式占用資源。
若想固定提示與參數,可以建立一個名為 Modelfile 的純文字檔:
FROM qwen3:4b
PARAMETER num_ctx 4096
PARAMETER num_predict 512
SYSTEM 請使用繁體中文。只根據使用者提供的資料回答;缺少資訊時請明確說明。
在該檔案所在資料夾執行:
ollama create local-assistant -f Modelfile
ollama run local-assistant
這是在包裝模型設定與提示,沒有重新訓練權重。API 若要使用這份設定,將 model 改成 local-assistant。Modelfile 官方說明
六、遇到問題,按層排查
| 現象 | 優先檢查 | 下一步 |
|---|---|---|
找不到 ollama |
安裝與終端機 PATH | 重開終端機,再確認版本 |
| Connection refused | 本機服務是否啟動 | 開啟 App,或檢查 Linux 服務 |
| Address already in use | 是否已啟動同一服務 | 先檢查現有服務,不要一直開新的 serve |
| Model not found | 模型名稱是否與 list 一致 |
補下載完整標籤,修正拼字 |
| 記憶體不足 | 模型、上下文、其他程式占用 | 縮短輸入與上下文,必要時換小模型 |
| 有回答但很慢 | ps 的 CPU/GPU 分配 |
查驅動、可用記憶體與首輪載入時間 |
| HTTP 成功但答案錯 | 題目、資料、模型能力 | 用固定題目驗收,避免只靠延長提示 |
本篇刻意只使用同一台電腦。另一台電腦上的 127.0.0.1 指向它自己;放進 Docker 後,localhost 的位置也會改變。等本機流程穩定,再處理內網連線、登入與使用權限;不要為了讓遠端連得上,就直接把沒有保護的模型 API 暴露到網際網路。官方連線與代理設定
完成後,你得到的是一個可被其他程式呼叫的本機推論服務。接下來最值得做的,是選一項小而固定的工作,例如活動資料摘要或分類,建立輸入、輸出格式與驗收規則,再逐步接入自動化。
練習附件
文末附有與內文一致的 Modelfile。下載後確認檔名沒有被加上 .txt,再於檔案所在資料夾執行建立指令;這份檔案只提供參數與提示設定,不包含模型權重。
官方參考資料
本文依官方文件整理;教學題目、起始設定與排錯順序為本文設計。未在本文宣稱實機效能或跨硬體測試結果。
本地 AI 實作系列
- 01 LM Studio:不寫程式的本地部署入門
- 02 Ollama:安裝模型並呼叫本地 API(本篇)
- 03 硬體與量化:6GB 到 16GB 顯存怎麼選
- 04 圖片辨識:Qwen3-VL 與 JSON 輸出
- 05 文件問答:PDF、RAG 與來源核對
Local AI implementation 02 | Data verification: November 30, 2026
downloading the model to the computer only completes part of the deployment. The local AI that can truly be integrated into the workflow must also be callable by the program, confirm the used computing resources, and know which layer the problem occurs in when an error occurs.
This article takes you through three verifiable results: the computer can answer questions, the program on the same computer can receive answers, and you know which model it is using. The example uses qwen3:4bbecause the official model library has clear labels and capacity information, making it suitable for understanding the process; it is a teaching example, not the best model for all tasks.
I. First, understand what you are installing
Ollama is a tool for executing and managing models, and the model weights are downloaded as separate data. The program uses the API to pass questions to Ollama and then obtains the answers generated by the model.
This article only links to the local machine http://127.0.0.1:11434. The official documentation distinguishes between local API and cloud API; local model calls do not require an Ollama cloud key, but Ollama can also use cloud models. Therefore, when you see the Ollama window or localhost URL, you should still confirm that you have selected the downloaded local model.API address and authentication explanation
First, prepare the available memory and disk space on your computer.qwen3:4b During verification, the official download size is approximately 2.5GB, quantized as Q4_K_M; execution also requires cache and other workspaces, so do not consider 2.5GB as the complete video memory requirement.Model labels and file information
II. Install according to the operating system and then confirm that the terminal recognizes the command
Windows
From the Ollama official download pageobtain the installation program, complete the installation, and then open Ollama and a new PowerShell window. The official Windows version will provide services in the background; you do not need to set up Docker first. If you have a separate graphics card, also confirm the driver and official support conditions.Windows installation and requirements
macOS
Fromthe official macOS download pageobtain the installation file, put the App in Applications, and start it, following the prompts to complete the command-line tool settings, and then open Terminal. The official documentation currently lists macOS 14 or later versions; Apple M series can use CPU and GPU, and the path for Intel Mac is CPU.macOS installation and requirements
Linux
The official provides an installation script. The following will download and execute separately, making it convenient to view the script content first;less Press q Leave and then execute the next line.
curl -fsSL https://ollama.com/install.sh -o install-ollama.sh
less install-ollama.sh
sh install-ollama.sh
If the service does not start automatically, you can run ollama servein a terminal, keep that window open, and then operate the model in another terminal. It does not need to be restarted when it is already running in the background.Linux official installation and service settings
All three systems first enter:
ollama --version
You can see the version information before proceeding. If it displays that the command is not found, restart the terminal, check the installation and PATH; this is not yet a problem with whether the model is good or not.
Third, download the specified model label and complete the first conversation
Execute in order:
ollama pull qwen3:4b
ollama list
ollama show qwen3:4b
ollama run qwen3:4b
pull Download the model,list list the downloaded items,show view the specified model information,run start the conversation. Note down list the model name and ID displayed, so that you can compare the effects later and not mix different versions together.Ollama CLI documentation
After entering the conversation, first set a context starting point that is easier to troubleshoot:
/set parameter num_ctx 4096
Then enter this original acceptance topic:
請使用繁體中文,只根據以下資料回答:
測試活動於 12 月 6 日舉辦,共 24 個名額,已報名 17 人。
請列出剩餘名額,並說明資料是否提供活動地點。
若未提供,不要猜測。
It is expected to indicate that there are 7 remaining places and that the activity location is not provided. The answer is correct only if it passes this topic; the text looks smooth but is not enough. This is just a connection and basic behavior acceptance, and does not mean that the model is already capable of doing all the work.
Enter /bye to exit the conversation. Open another terminal or run ollama pswhile the model is still loaded, to check if the processor field is GPU, CPU, or a mix of both.ollama list This is the list of models on the disk.ollama ps This is the model currently loaded.Context and computing resource check
Fourth, let the program receive the first API response
The following two paragraphs can be used interchangeably, with the same function. They explicitly specify the model, 4096 tokens context, and use stream: falseto get the complete JSON directly in the first practice.think: false Used here for the Qwen3 example; when switching to other models, you need to adjust according to the thinking control it supports.Chat API、Thinking mode
macOS/Linux: Terminal
curl http://127.0.0.1:11434/api/chat \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3:4b",
"messages": [
{"role": "user", "content": "用繁體中文,一句話解釋什麼是本地模型。"}
],
"stream": false,
"think": false,
"options": {"num_ctx": 4096, "num_predict": 256}
}'
Windows: PowerShell
$payload = @{
model = "qwen3:4b"
messages = @(
@{ role = "user"; content = "用繁體中文,一句話解釋什麼是本地模型。" }
)
stream = $false
think = $false
options = @{ num_ctx = 4096; num_predict = 256 }
} | ConvertTo-Json -Depth 6
$response = Invoke-RestMethod `
-Uri "http://127.0.0.1:11434/api/chat" `
-Method Post `
-ContentType "application/json; charset=utf-8" `
-Body ([System.Text.Encoding]::UTF8.GetBytes($payload))
$response.message.content
The continuation character for PowerShell is a backtick, and there should be no extra spaces after it. Here, it is explicitly converted to UTF-8 to avoid encoding issues with Chinese requests in different terminal environments.
The final answer of the original JSON is located message.contentIf using a stream, the program needs to read the data segment by segment; it cannot parse multiple lines of streaming JSON as a single JSON. The first time, the stream is closed to reduce debugging factors unrelated to model capabilities.
Five, from "connection" to "can be reused"
For each acceptance, record the operating system, Ollama version, model name and ID, context, output limit, whether to think, and topic. Change only one setting and re-run the same batch of topics.
The API returns load_duration、eval_count、eval_duration can help distinguish between loading time and generation time; the official time field uses nanoseconds. eval_duration Greater than zero, can be used eval_count ÷ (eval_duration / 1,000,000,000) Calculate the generation rate of this response. This does not include the waiting time from sending to seeing the first character, nor does it include the entire application process.Return field definition
First, do a warm-up, then repeat the same set of short questions, recording quality and time separately. Without these records, it's hard to determine whether "yesterday was fast, today was slow" is due to the model, input length, cold start, or other programs occupying resources.
If you want to fix the prompt and parameters, you can create a plain text file named Modelfile a plain text file:
FROM qwen3:4b
PARAMETER num_ctx 4096
PARAMETER num_predict 512
SYSTEM 請使用繁體中文。只根據使用者提供的資料回答;缺少資訊時請明確說明。
Run the following command in the folder where the file is located:
ollama create local-assistant -f Modelfile
ollama run local-assistant
This is packaging model settings and prompts without retraining weights. If the API wants to use this setting, change model to local-assistant。Modelfile official documentation
Six, if you encounter problems, check layer by layer
| Phenomenon | Priority check | Next step |
|---|---|---|
Can't find ollama |
Installation and Terminal PATH | Restart the terminal and check the version again |
| Connection refused | Is the local service started | Open the App or check the Linux service |
| Address already in use | Is the same service already started | Check existing services first, don't keep opening new ones serve |
| Model not found | Is the model name consistent with list consistent with |
Download the complete label and correct the spelling |
| Out of memory | Model, context, and other programs occupy | Shorten the input and context, and replace with a smaller model if necessary |
| There is a response but it's very slow | ps CPU/GPU allocation |
Check the driver, available memory, and first-load time |
| HTTP successful but the answer is wrong | Topic, data, model capability | Use fixed topics for verification, avoid relying solely on extended prompts |
This article intentionally only uses the same computer. On another computer, 127.0.0.1 points to itself; after putting it in Docker, the location of localhost will also change. Wait for the local process to stabilize before handling intranet connections, login, and usage permissions; don't expose the unprotected model API to the internet just to allow remote connections.Official connection and proxy settings
After completion, you get a local inference service that can be called by other programs. The next most worthwhile thing to do is to select a small and fixed task, such as activity data summary or classification, establish input, output formats and acceptance rules, and then gradually connect to automation.
Exercise attachment
There is an attachment at the end of the article that is consistent with the content. ModelfileAfter downloading, confirm that the file name has not been added to .txtand then run the build command in the folder where the file is located; this file only provides parameter and prompt settings, and does not include model weights.
Official reference materials
This article is organized based on official documents; the teaching topics, initial settings, and troubleshooting order are designed by this article. The article does not claim actual machine performance or cross-hardware test results.
Local AI practice series
- 01 LM Studio: Local deployment entry without programming
- 02 Ollama: Install the model and call the local API (this article)
- 03 Hardware and quantization: How to choose from 6GB to 16GB video memory
- 04 Image recognition: Qwen3-VL and JSON output
- 05 Document Q&A: PDF, RAG, and source verification