Runoob Tutorial ArchiveEnglish

Local model deployment

Local model deployment

Many people think AI can only be used in the cloud; when using ChatGPT, data is sent to OpenAI's servers, and when using Claude, requests are sent to Anthropic's data centers.

In reality, AI models can run entirely on your own computer.

Imagine: using AI without an internet connection, sensitive data never leaves your computer, no need to pay for every call, and you can customize it however you want.

This is the value of local model deployment.

This module will guide you from scratch to run your first local AI model on your own computer.


Why local AI

Cloud AI is convenient, but local AI has irreplaceable advantages.

Data privacy protection

This is the primary reason many choose local deployment.

If you are dealing with contracts, medical records, financial data, or internal documents, sending this data to a third-party server is risky.

When running locally, all data is processed on your own computer and will not leave your device.

Use without network

Cloud AI cannot be used on airplanes, trains, or in areas with unstable networks.

After downloading the local model once, it is permanently available without needing a network connection.

Cost Control

Cloud AI is billed per call or Token, and heavy usage can result in a significant expense.

Local models are downloaded once and can be used freely afterward without extra charges.

Customization Possibilities

With cloud models, you cannot modify them; you can only use the functions provided by the service.

With local models, you can fine-tune, quantize, modify prompt templates, and customize them completely according to your needs.

Comparison of these advantages:

Feature Cloud AI Local AI
Data privacy Data needs to be uploaded Data is completely localized
Network dependency Requires internet connection No network required
Usage cost Pay per call One download, unlimited use
Customization capability Limited Fully controllable
Ease of use Ready to use Configuration required
Response speed Depends on the network Depends on the hardware

It's not that cloud AI is bad, but rathereach has its applicable scenariosUse the cloud for casual chat, and the local for sensitive data; use the cloud for simple tasks, and the local for special customization.


Hardware requirement assessment

Whether a local model can run and how fast it runs mainly depends on your hardware configuration.

CPU Inference vs GPU Inference

There are two ways to run a model: CPU inference and GPU inference.

CPU inference runs the model using the computer's main processor; the advantage is good compatibility, as almost all computers can run it; the disadvantage is slow speed, and large models might take a long time.

GPU inference runs the model using a graphics card; the core advantage is strong parallel computing capability, making model running dozens of times faster.

For NVIDIA graphics cards, you need to install the CUDA toolkit; for AMD graphics cards, you can use ROCm; for Intel graphics cards, you can use OpenVINO.

The relationship between VRAM requirements and model size

VRAM determines the size of the model you can run.

The more model parameters, the larger the required VRAM. However, quantization techniques allow running larger models with less VRAM.

VRAM size Runnable models (FP16) Runnable models (quantized) Recommended scenarios
8 GB 7B models are borderline 7B (Q4), 13B (Q4) are borderline Simple conversation, lightweight tasks
16 GB 7B, 13B models 7B, 13B (Q4/Q8), 33B (Q4) Daily use, best cost-performance ratio
24 GB 7B, 13B, 33B models 7B, 13B, 33B (Q4/Q8), 70B (Q4) Professional use, smooth experience
48 GB+ 33B, 70B models All mainstream models Research, production environment

Advantages of Mac M series

Apple Silicon (M1, M2, M3 series chips) has unique advantages in local AI.

Apple's Metal framework and unified memory architecture make running local models on Mac highly efficient.

Unified memory means that the CPU and GPU share memory, and memory can be automatically borrowed when VRAM is insufficient.

A MacBook Pro with 16GB of unified memory can smoothly run quantized 7B and 13B models.

Recommended configuration options

Here are several configuration options depending on different budgets and needs:

Plan Configuration Target audience Expected experience
Beginner plan Any computer (8GB RAM or more) Beginners who want to experience local AI Can run small models, but speed is slow
Cost-effective plan 16GB RAM + 6GB or more VRAM Personal daily use Smoothly runs 7B/13B models
Professional Solution 32GB memory + 12GB or more VRAM Developers, researchers Smooth running of 33B models
Mac Solution M1/M2/M3 + 16GB unified memory Preferred for Mac users Smooth running of 7B/13B models

Don't be intimidated by the term large models. Today's quantization technology allows 7B models to run smoothly on ordinary computers, and the capabilities of a 7B model are sufficient for most daily tasks.


Ollama: The simplest local AI tool

Ollama is currently the most popular local model tool. In one sentence: install models like installing an App, and use AI like using the command line.

Installation and configuration

Ollama supports macOS, Linux, and Windows, and the installation process is very simple.

Installer download address:https://ollama.com/download

Install with one command:



curl -fsSL https://ollama.com/install.sh | sh

macOS users can directly download the installer or install with Homebrew:

Original prompt (Chinese, left untranslated)



# Install using Homebrew on macOS

brew install ollama



# Or download the installer: https://ollama.com/download

Windows users can download the installer from the official website and run it.

After installation, start the Ollama service:



ollama serve

Once the service starts successfully, you can start using it.

Download models

Ollama has a rich model library, including mainstream models like Llama, Qwen, Gemma, and Mistral.

Download models with a single command:

Instance

Download Llama 3 (8B parameters)

ollama pull llama3

Download Qwen (Tongyi Qianwen, Chinese-friendly)

ollama pull qwen

Download Gemma (from Google)

ollama pull gemma

Download Mistral

ollama pull mistral

You can also use the ollama run + model name command; if the model is not specified, it will be downloaded automatically:



ollama run qwen

Running the qwen model will download it if it is not present.

Each model has different versions, such as 8B, 70B, or different quantization versions.

You can useollama listTo view downloaded models:



ollama list

Output similar to:



NAME              ID              SIZE      MODIFIED

qwen3.5:latest    6488c96fa5fa    6.6 GB    3 months ago

Command Line Usage

After downloading the model, you can start chatting by running it directly:

Original prompt (Chinese, left untranslated)



# Run Llama 3, it won't download

ollama run llama3



# Run Qwen, it won't download

ollama run qwen3.5

qwen3.5 is more than enough for general tasks:

178 5 331856

Then you can chat directly with the model:

Original prompt (Chinese, left untranslated)



>>> 你好,请介绍一下你自己

你好!我是 Llama 3,由 Meta 开发的 AI 助手。我可以帮你回答问题、

写作、编程、分析数据等。有什么我可以帮你的吗?



>>> 用 Python 写一个 Hello World 程序

Okay, here is a simple Python Hello World program:



print("Hello, World!")



>>> /bye  # 输入 /bye 退出

Common Commands:

Command Function Example
ollama pull Download model ollama pull llama3
ollama run Run model ollama run llama3
ollama list List installed models ollama list
ollama rm Delete model ollama rm llama3
ollama show View model information ollama show llama3

API interface call

Ollama comes with an HTTP API that you can call using code, not just in the command line.

By default, Ollamahttp://localhost:11434provides API services.

Calling the Ollama API with Python:

Example

File path: /Users/runoob/ollama_test.py

Calling the Ollama API with Python

import

requests

import

json

Ollama API Address

OLLAMA_URL

=

"http://localhost:11434/api/generate"

def

ask_ollama

(

prompt:

str

,

model:

str

=

"llama3"

)

str

:

   

"""
Sends a request to Ollama to get the model response

Args:
prompt: The prompt input by the user
model: The name of the model used, defaults to llama3

Returns:
The response text from the model
"""

   

Construct the request data

payload

=

{

       

"model"

: model

,

     

The model used

       

"prompt"

: prompt

,

   

User input

       

"stream"

:

False

     

Do not use streaming output, return all at once

   

}

   

try

:

       

Send POST request

response

=

requests.

post

(

OLLAMA_URL

,

json

=

payload

)

response.

raise_for_status

(

)

 

Check if the request was successful

       

Parse the returned JSON

result

=

response.

json

(

)

       

return

result.

get

(

"response"

,

""

)

   

except

requests.

exceptions

.

ConnectionError

:

       

return

"Error: Could not connect to Ollama service. Please ensure Ollama is running."

   

except

requests.

exceptions

.

RequestException

as

e:

       

return

f

"Request error: {str(e)}"

Test it

if

name

==

"main"

:

   

Test Question 1

question1

=

"Please introduce the RUNOOB tutorial in one sentence"

answer1

=

ask_ollama

(

question1

)

   

print

(

f

"Question: {question1}"

)

   

print

(

f

"Answer: {answer1}"

)

   

print

(

"-"

50

)

   

Test Question 2

question2

=

"Write a Python function to calculate the Fibonacci sequence"

answer2

=

ask_ollama

(

question2

)

   

print

(

f

"Question: {question2}"

)

   

print

(

f

"Answer: {answer2}"

)

Run this script:

Instance

First install the requests library (if not already installed)

pip

install

requests

Run the script

python ollama_test.py

If you want to use a more advanced wrapper, you can use Ollama's official Python library:

Instance

File path: /Users/runoob/ollama_advanced.py

Use the Ollama Python library

First install: pip install ollama

import

ollama

def

chat_with_runoob

(

)

:

   

"""
Use the Ollama Python library for multi-turn conversations
"""

   

Message history

messages

=

[

       

{

           

"role"

:

"system"

,

           

"content"

:

"You are a friendly programming assistant named RunoobBot. Your answers should be concise, practical, and use many code examples."

       

}

   

]

   

print

(

"RunoobBot has started! Enter 'quit' to exit."

)

   

print

(

"-"

50

)

   

while

True

:

       

Get user input

user_input

=

input

(

"You:"

)

       

if

user_input.

lower

(

)

in

[

"quit"

,

"exit"

,

"exit"

]

:

           

print

(

"Goodbye!"

)

           

break

       

Add user message to history

messages.

append

(

{

           

"role"

:

"user"

,

           

"content"

: user_input

       

}

)

       

Call model

response

=

ollama.

chat

(

model

=

"llama3"

,

messages

=

messages

       

)

       

Get reply

assistant_message

=

response

[

"message"

]

[

"content"

]

       

print

(

f

"RunoobBot: {assistant_message}"

)

       

print

(

"-"

50

)

       

Add assistant reply to history

messages.

append

(

{

           

"role"

:

"assistant"

,

           

"content"

: assistant_message

       

}

)

if

name

==

"main"

:

chat_with_runoob

(

)

Integration with Open WebUI

Although the command line is convenient, a graphical interface is more user-friendly.

Open WebUI is a very beautiful web interface that can connect to Ollama, allowing you to use local models like ChatGPT.

Installing Open WebUI:

Instance

Install Open WebUI using Docker

docker run

-d

-p

3000

:

8080

--add-host

=host.docker.internal:host-gateway

-v

open-webui:

/

app

/

backend

/

data

--name

open-webui

--restart

always ghcr.io

/

open-webui

/

open-webui:main

If you don't use Docker, you can also install it with pip

pip

install

open-webui

open-webui serve

After installation, open in the browserhttp://localhost:3000, and you will see an interface very similar to ChatGPT.

Ollama + Open WebUI is currently the most recommended local AI combination—easy to install, user-friendly interface, and powerful, suitable for most users.


LM Studio: Graphical Interface Operation

If you don't like the command line, LM Studio is a great choice—pure graphical interface, downloading and running models are all done within the window.

Install LM Studio

LM Studio supports Windows, macOS, and Linux.

From the official websitehttps://lmstudio.aiDownload the installer package and install it directly.

Model Download and Management

Open LM Studio, the model library is on the left.

You can search by model name, for example, search for "llama", "qwen", or "mistral" to find the desired model and click download.

LM Studio will automatically list different versions of the same model:

Version Description Recommended Scenario
Q4_K_M 4-bit quantization, small quality loss Most people's choice
Q5_K_M 5-bit quantization, better quality, slightly larger size Choose this when VRAM is sufficient
Q8_0 8-bit quantization, close to native quality Pursue quality, VRAM is large enough
FP16 Full precision, largest volume For research purposes

Downloaded models will appear in the "My Models" list.

Local API service

LM Studio can also provide an API service compatible with the OpenAI API format.

This means that the OpenAI code you write can use local models by only changing the API address and Key.

Example

File path: /Users/runoob/lmstudio_openai.py

LM Studio compatible with OpenAI API format

from

openai

import

OpenAI

Connect to the local LM Studio server

Note: You need to enable the server in LM Studio first

client

=

OpenAI

(

    base_url

=

"http://localhost:1234/v1"

,

    api_key

=

"lm-studio"

 

Use this placeholder for LM Studio

)

def

ask_local_model

(

prompt:

str

,

system_prompt:

str

=

"You are a helpful assistant."

)

str

:

   

"""
Call local models in LM Studio via OpenAI compatible interface
"""

response

=

client.

chat

.

completions

.

create

(

        model

=

"local-model"

,

 

This field will be ignored by LM Studio

        messages

=

[

           

{

"role"

:

"system"

,

"content"

: system_prompt

}

,

           

{

"role"

:

"user"

,

"content"

: prompt

}

       

]

,

temperature

=

0.7

,

   

)

   

return

response.

choices

[

0

]

.

message

.

content

Test

if

name

==

"main"

:

    question

=

Introduce the features of the RUNOOB tutorial

    answer

=

ask_local_model

(

        prompt

=

question

,

system_prompt

=

"You are Runoob's exclusive customer service, professionally answering questions about programming learning."

   

)

   

print

(

f

"Question: {question}"

)

   

print

(

f

"Answer: {answer}"

)

This feature is very useful—you can switch between cloud models and local models using the same set of code as needed.

For users new to local AI, I recommend: start with LM Studio to understand basic concepts and operations; then use Ollama for automation and integration once you are familiar with it.


Introduction to Model Quantization

Quantization is the key technology that allows large models to run on ordinary computers—running larger models with less VRAM while maintaining most of their capabilities.

What is quantization

Simply put, quantization is reducing the precision of model parameters.

Native models usually store each parameter using 16-bit floating-point (FP16) or 32-bit floating-point (FP32).

After quantization, we store them using 8-bit integers (INT8) or even 4-bit integers (INT4).

The precision is reduced, but the size and VRAM requirements are also greatly reduced.

For example:

Precision 7B model size 13B model size VRAM requirement Quality loss
FP16 13 GB 26 GB High None
Q8_0 7 GB 13 GB Chinese Very small
Q5_K_M 5 GB 9 GB Low Acceptable
Q4_K_M 4 GB 7 GB Very low Slight
Q3_K_M 3 GB 5 GB Extremely low Obvious

Experience is: Q8 quantization hardly results in a noticeable drop in quality, and Q4 quantization is sufficient for most tasks.

Detailed explanation of the GGUF format

GGUF is the most popular quantized model format currently.

The predecessor of GGUF is GGML, developed by the llama.cpp project.

Advantages of this format:

Most local model tools (Ollama, LM Studio, llama.cpp) now support the GGUF format.

Difference between Q4/Q8 quantization

Q4 and Q8 are the two most commonly used quantization levels.

How to choose:

Scenario Recommended quantization level Reason
Very limited VRAM (less than 8GB) Q4_K_M Usability is the top priority
Daily conversations, simple tasks Q4_K_M Best cost-performance ratio
Writing, programming, analysis Q5_K_M or Q6_K Balance between quality and speed
Pursuing the best quality Q8_0 Near native quality

AWQ/GPTQ quantization schemes

Besides GGUF quantization, there are two commonly used quantization schemes: AWQ and GPTQ.

The characteristic of AWQ (Activation-aware Weight Quantization) is that it retains weights that have a large impact on the results, resulting in smaller quality loss after quantization.

The characteristic of GPTQ (Gradient-based Post-Training Quantization) is that it optimizes quantization using gradient information, making it suitable for scenarios with a GPU.

These two schemes are mainly used on NVIDIA graphics cards that support CUDA.

Simple comparison:

Quantization scheme Applicable hardware Speed Quality Recommended tools
GGUF CPU + various GPUs Fast Good Ollama, LM Studio
AWQ NVIDIA GPU Fast Very good vLLM, Text Generation WebUI
GPTQ NVIDIA GPU Quickly Very good AutoGPTQ, ExLlama

For beginners, don't worry about these technical details—just use the Q4_K_M version recommended in Ollama or LM Studio; this is the best balance point that has been extensively verified.


Model Selection Guide

With hundreds or thousands of open-source models available now, choosing a model that suits you is very important.

7B/13B/70B Model Comparison

The number of parameters is an important indicator—7B, 13B, and 70B are the most common specifications.

Specifications VRAM requirement (Q4) Inference speed Capability level Applicable scenarios
7B 4-6 GB Quickly Enough Daily conversations, simple tasks
13B 7-10 GB Fast Good Writing, programming, analysis
33B 15-20 GB Medium Excellent Complex reasoning, professional fields
70B 30-40 GB Slower Approaching GPT-3.5 Research and production environments

The sweet spot for most people is the 13B Q4 quantized version—good capability and acceptable speed.

Recommended models with good Chinese support

Many foreign models have mediocre Chinese capabilities; here are a few models recommended for being friendly to Chinese:

Model Name Provider Features Ollama commands
Qwen Alibaba Strong Chinese capabilities, balanced overall ability ollama pull qwen
Yi Zero One Institute Good Chinese comprehension, strong reasoning ability ollama pull yi
DeepSeek DeepSeek Strong coding ability, good Chinese ollama pull deepseek-coder
Llama 3 Meta Strong overall ability, Chinese requires tuning ollama pull llama3
Gemma Google Solid foundation, good coding ability ollama pull gemma

For Chinese tasks, Qwen is the first choice; its Chinese understanding and generation capabilities are in the top tier among open-source models.

Task-specific model selection

Different models have different strengths; choose a model based on the task:

Task type Recommended models Reason
Daily conversation, Q&A Llama 3, Qwen, Mistral Balanced comprehensive capabilities
Writing, copywriting Yi, Llama 3, Claude (cloud) Good writing style, fluent expression
Programming, code DeepSeek-Coder, CodeLlama, StarCoder Strong code understanding and generation capabilities
Mathematics, reasoning Llama 3, Qwen, WizardMath Good logical reasoning ability
Professional fields (medical, legal) Models fine-tuned for specific domains Trained on specialized data

Bigger models are not always better, and newer models are not always better—The best one is the one that suits your hardware and your task. We suggest downloading a few 7B models to try first, and then upgrading once you find what works for you.Practical application: Building a completely offline local knowledge base


One of the most practical use cases for local models is building your own private knowledge base—feeding local documents to the model so it can answer questions based on those documents.

The entire system runs completely offline, and your data will not leave your computer.

The entire system runs completely offline, and data will not leave your computer.

Technical Solution

We use RAG (Retrieval-Augmented Generation) technology:

  1. Split the documents into small chunks

  2. Convert each chunk into a vector using an embedding model

  3. Store the vectors in a vector database

  4. When asking a question, convert the question into a vector as well

  5. Find the most relevant document chunks in the vector database

  6. Send the relevant documents and the question together to the local large model

  7. Large models answer based on document content

This process sounds complicated, but it's simple to implement with existing tools.

Implemented with Ollama + LangChain

We use Python to implement a simple version:

Example

File path: /Users/runoob/local_knowledge_base.py

Fully offline local knowledge base RAG system

First, install dependencies:

pip install langchain langchain-ollama chromadb pypdf

from

langchain_ollama

import

OllamaLLM

,

OllamaEmbeddings

from

langchain_community.

document_loaders

import

PyPDFLoader

,

TextLoader

from

langchain.

text_splitter

import

RecursiveCharacterTextSplitter

from

langchain_community.

vectorstores

import

Chroma

from

langchain.

chains

import

RetrievalQA

import

os

class

LocalKnowledgeBase:

   

"""Local knowledge base class, implements fully offline RAG functionality"""

   

def

init

(

self

,

model_name:

str

=

"llama3"

,

persist_dir:

str

=

"./chroma_db"

)

:

       

"""
Initialize knowledge base

Args:
model_name: The name of the Ollama model used
persist_dir: Vector database persistence directory
"""

       

self

.

model_name

=

model_name

       

self

.

persist_dir

=

persist_dir

       

1. Initialize LLM (local model)

       

self

.

llm

=

OllamaLLM

(

model

=

model_name

)

       

2. Initialize embedding model (local embedding)

       

Use nomic-embed-text, this model is good for both Chinese and English

       

self

.

embeddings

=

OllamaEmbeddings

(

model

=

"nomic-embed-text"

)

       

3. Vector database placeholder

       

self

.

vector_store

=

None

       

self

.

qa_chain

=

None

   

def

load_documents

(

self

,

document_paths:

list

)

:

       

"""
Load documents and build vector database

Args:
document_paths: List of document paths
"""

documents

=

[

]

       

for

path

in

document_paths:

           

if

not

os

.

path

.

exists

(

path

)

:

               

print

(

f

"Warning: file {path} does not exist, skipping"

)

               

continue

           

Select loader based on file extension

           

if

path.

lower

(

)

.

endswith

(

".pdf"

)

:

loader

=

PyPDFLoader

(

path

)

           

elif

path.

lower

(

)

.

endswith

(

".txt"

)

:

loader

=

TextLoader

(

path

,

encoding

=

"utf-8"

)

           

else

:

               

print

(

f

"Warning: unsupported file type {path}, skipping"

)

               

continue

documents.

extend

(

loader.

load

(

)

)

           

print

(

f

"Loaded: {path}"

)

       

if

not

documents:

           

print

(

"No documents loaded successfully"

)

           

return

       

print

(

f

"A total of {len(documents)} document chunks have been loaded"

)

       

4. Split documents

text_splitter

=

RecursiveCharacterTextSplitter

(

chunk_size

=

500

,

     

500 characters per chunk

chunk_overlap

=

100

   

overlap between chunks 100 characters

       

)

split_docs

=

text_splitter.

split_documents

(

documents

)

       

print

(

f

"Split into {len(split_docs)} chunks"

)

       

5. Build vector database

       

print

(

"Building vector database..."

)

       

self

.

vector_store

=

Chroma.

from_documents

(

documents

=

split_docs

,

embedding

=

self

.

embeddings

,

persist_directory

=

self

.

persist_dir

       

)

       

print

(

"Vector database construction completed!"

)

       

6. Constructing the QA Chain

       

self

._build_qa_chain

(

)

   

def

_build_qa_chain

(

self

)

:

       

"""Build RAG QA chain"""

       

if

not

self

.

vector_store

:

           

print

(

"Please load the document first!"

)

           

return

       

Build retriever

retriever

=

self

.

vector_store

.

as_retriever

(

            search_type

=

"similarity"

,

search_kwargs

=

{

"k"

:

3

}

 

Return the 3 most relevant snippets

       

)

       

Build RAG chain

       

self

.

qa_chain

=

RetrievalQA.

from_chain_type

(

llm

=

self

.

llm

,

chain_type

=

"stuff"

,

retriever

=

retriever

,

return_source_documents

=

True

       

)

   

def

load_existing_db

(

self

)

:

       

"""Load existing vector database"""

       

if

os

.

path

.

exists

(

self

.

persist_dir

)

:

           

self

.

vector_store

=

Chroma

(

persist_directory

=

self

.

persist_dir

,

embedding_function

=

self

.

embeddings

           

)

           

self

._build_qa_chain

(

)

           

print

(

"Existing vector database loaded"

)

           

return

True

       

else

:

           

print

(

"No existing vector database found"

)

           

return

False

   

def

ask

(

self

,

question:

str

)

dict

:

       

"""
Ask the knowledge base

Args:
question: The question

Returns:
A dictionary containing the answer and reference sources
"""

       

if

not

self

.

qa_chain

:

           

return

{

"error"

:

"Please load the document or existing database first!"

}

       

Construct the prompt template to encourage Chinese answers

result

=

self

.

qa_chain

.

invoke

(

{

           

"query"

: f

"""Please answer the following questions in Chinese. If the answer is in the context, please point it out clearly.
If there is no answer in the context, please honestly say "Cannot answer based on the provided information".

Question: {question}
"""

       

}

)

       

return

{

           

"question"

: question

,

           

"answer"

: result

[

"result"

]

,

           

"sources"

:

[

doc.

page_content

for

doc

in

result

[

"source_documents"

]

]

       

}

============================================

Usage Example

============================================

if

name

==

"main"

:

   

1. Create knowledge base instance

    kb

=

LocalKnowledgeBase

(

model_name

=

"qwen"

)

 

Use Qwen, Chinese is better

   

2. Attempt to load existing database, otherwise load documents

   

if

not

kb.

load_existing_db

(

)

:

       

Prepare some documents, such as saving some RUNOOB tutorials as txt

sample_docs

=

[

           

"/Users/runoob/documents/runoob_python_tutorial.txt"

,

           

"/Users/runoob/documents/company_handbook.pdf"

,

       

]

kb.

load_documents

(

sample_docs

)

   

3. Interactive Q&A

   

print

(

"="

50

)

   

print

(

"Runoob local knowledge base started!"

)

   

print

(

"Enter your question, or enter 'quit' to exit"

)

   

print

(

"="

50

)

   

while

True

:

user_input

=

input

(

"\nYour question:"

)

       

if

user_input.

lower

(

)

in

[

"quit"

,

"exit"

,

"Exit"

]

:

           

print

(

"Goodbye!"

)

           

break

       

if

not

user_input.

strip

(

)

:

           

continue

       

Question

result

=

kb.

ask

(

user_input

)

       

if

"error"

in

result:

           

print

(

f

"Error: {result['error']}"

)

           

continue

       

print

(

f

"\nAnswer: {result['answer']}"

)

       

print

(

"\nReference source:"

)

       

for

i

,

source

in

enumerate

(

result

[

"sources"

]

,

1

)

:

           

print

(

f

"\n[{i}] {source[:200]}..."

)

Before using this system, you need to download the embedding model:

Instance

Download embedding model

ollama pull nomic-embed-text

Download the main model (if not already downloaded)

ollama pull qwen

This way, you have a private knowledge base system that runs entirely locally.

You can put your own notes, documents, and e-books in it, and let the AI help you retrieve and answer questions.

All the data in this system is local—documents are on your hard drive, the vector database is in your directory, and the model is on your computer, so you don't have to worry about data leakage at all.


Performance optimization tips

The local model is running, but how to make it run faster? Here are some practical tips.

Choose the appropriate quantization level

This is the simplest and most effective optimization—the lower the quantization level, the faster the speed.

If Q4 works, don't use Q8; if Q8 works, don't use FP16.

Adjust the context window size

The larger the context window, the more computation is required.

If you don't need a very long context, you can set it in Ollama's Modelfile:

Instance

Create a custom model to limit the context window

Create a new file Modelfile

echo

"FROM llama3
PARAMETER num_ctx 2048"

Modelfile

Create custom model

ollama create llama3-fast

-f

Modelfile

Run

ollama run llama3-fast

Lower the context from the default of 8192 to 2048; the speed will increase significantly.

Use GPU acceleration

If you have an NVIDIA graphics card or Apple Silicon Mac, ensure Ollama is using the GPU and not the CPU.

Ollama will automatically detect and use the GPU, but sometimes you need to confirm it.

In the Ollama startup log, you should see messages like "Metal GPU activated" or "CUDA activated".

Use faster sampling parameters

Some sampling parameters affect speed:

Instance

Create a speed-optimized Modelfile

File: Modelfile.fast

echo

"FROM llama3
PARAMETER temperature 0.7
PARAMETER top_k 20
PARAMETER top_p 0.9
PARAMETER num_predict 256

Modelfile.fast

Create and run

ollama create llama3-optimized

-f

Modelfile.fast

ollama run llama3-optimized

Parameter description:

Parameter Function Optimization suggestions
temperature Controls randomness Moderate is fine, it does not affect speed
top_k Limit the number of candidate words Setting it a bit smaller (20-40) can speed up the process
top_p Cumulative probability threshold Default 0.9 is fine
num_predict Maximum number of generated tokens Limit as needed
num_ctx Context window size Enough is good, smaller is faster

Disable unnecessary features

If you are calling via API and do not need streaming output, you can set stream to false.

This will not make inference faster, but it will reduce network transmission overhead.

Performance optimization is an art of balance—speed, quality, and VRAM cannot all be achieved. Just find the balance point that suits your needs.