Runoob Tutorial ArchiveEnglish

Large Model Related Concepts

Large Model Related Concepts

When first encountering Large Model (LLM) development, a flood of new terms appears: Token, RAG, Embedding, Agent..., which seem independent but are actually linked into a complete technical chain.

This article connects these concepts in the order of "What is the model $\rightarrow$ How to train $\rightarrow$ How to use $\rightarrow$ How to optimize," helping novice developers build a clear knowledge framework.

This article is not just a "glossary of terms"; it will also demonstrate how these concepts are implemented using runnable Python code.

All examples are based on the OpenAI compatible protocol; they can be switched to services like Alibaba Cloud Bailian or DeepSeek by changing the interface address and key.

Python OpenAI Reference:https://www.runoob.com/python3/python-openai.html


Overall Technical Chain

Before dissecting each concept, take a look at the complete pipeline of large model technology to build an overall understanding.

From top to bottom, each layer solves a class of core problems: training to create the model, optimization to make it lighter, driving to make it functional, retrieval to supplement knowledge, and tools to enable execution.

Overall technical link diagram of large models

The following sections will unfold layer by layer, from top to bottom, following this pipeline.


Basic Concepts: What is a Model

This section answers the most fundamental question: what exactly is a large model, and how does it work?

LLM (Large Language Model)

LLM stands for Large Language Model, and it is a deep learning model trained on massive amounts of text.

Its essence is a probability model for "predicting the next word": given the preceding text, it predicts the most likely content to appear next.

Products such as ChatGPT, Claude, and Tongyi Qianwen are all based on LLMs at their core.

Transformer and Attention Mechanism

Almost all modern LLMs are based on the Transformer architecture.

Its core innovation is the Attention Mechanism (Attention / Self-Attention): when processing a certain word, the model can dynamically "focus" on other relevant words in the input sequence, thus better understanding the contextual relationship.

To put it another way, when reading a sentence, the model does not scan word by word rigidly, but automatically determines "which preceding word has the strongest relationship with this word."

Token

The model does not process text by "character" or "word," but by Token.

A Token can be a Chinese character, an English word, or part of a word.

Understand that Tokens have two direct practical meanings:

The model's context length limit is calculated based on Tokens; API call billing is also calculated based on Tokens.

Using OpenAI's open-source tokenizer tiktoken, you can directly see how many Tokens a piece of text is split into:

Example

Installation: pip install tiktoken

import

tiktoken

Different models use different tokenizers, encoding_for_model will automatically select the corresponding one

enc

=

tiktoken.

encoding_for_model

(

"gpt-4o-mini"

)

tokens

=

enc.

encode

(

"Hello world"

)

 

Split the text into a list of Tokens

print

(

"Token count:"

,

len

(

tokens

)

)

print

(

"Splitting result:"

,

[

enc.

decode

(

[

t

]

)

for

t

in

tokens

]

)

Output result:

Original prompt (Chinese, left untranslated)



Token 数量:2

切分结果:['Hello', ' world']

If you change it to Chinese or a longer word, the segmentation method will be completely different, so "estimating Tokens by word count" is not accurate.

Context Window

Refers to the maximum number of Tokens the model can "see" and process at one time.

For example, if the context window is 100K, it means that one conversation (including historical messages, your question, and the model's answer) cannot exceed 100,000 Tokens.

The larger the window, the more content the model can "remember," and the longer the document it can process at once.

Number of Parameters

The number of parameters refers to the number of learnable weights inside the model, usually measured in B (Billion), such as 7B or 70B.

It reflects the model's scale and upper limit of capability to some extent, but it is not the only metric—training data quality and architectural design are also crucial.

Common Number of Parameters Magnitude Typical Positioning
1B ~ 7B Small to medium Can run locally on consumer-grade GPUs, suitable for lightweight tasks
8B ~ 34B Medium High cost-performance, covers most general scenarios
70B ~ hundreds of B Large Strongest capability, usually called via cloud API

How is the model trained

An LLM capable of natural conversation usually goes through multiple training stages, layering capabilities.

LLM training process diagram

Pre-training

The model learns the statistical patterns of language, such as grammar, common sense, and logical relationships, on massive amounts of unlabeled text (web pages, books, code, etc.).

This stage consumes the most computing power and forms the foundation of the model's capabilities.

However, the model at this stage is not good at "acting on instructions"; it is more like someone who has read many books but does not know how to communicate.

SFT (Supervised Fine-Tuning)

SFT stands for Supervised Fine-Tuning.

Use manually annotated "question-answer" pairs to teach the model to answer questions according to human instructions, rather than just continuing the text on its own.

RLHF (Reinforcement Learning from Human Feedback)

RLHF stands for Reinforcement Learning from Human Feedback.

Have humans score or rank multiple candidate answers from the model, and then use this feedback to train the model to produce outputs that better align with human preferences (more helpful, honest, and safe).

A similar technique is RLAIF: using AI instead of humans for scoring to reduce annotation costs.

Both share the same goal; the difference lies only in whether the "scorer" is a real person or another AI.

Alignment

Alignment is a more macro concept: making the model's behavior and values conform to human expectations and intentions.

It is a core issue in the field of AI safety, running through every training stage such as SFT and RLHF—SFT and RLHF are essentially "alignment methods."

Fine-tuning

Continuing to train a pre-trained general model using data from a specific domain (such as law, medicine, or customer service).

Compared to pre-training from scratch, fine-tuning is much less costly and is a common practice for adapting general models to specialized scenarios.

MoE (Mixture of Experts)

MoE stands for Mixture of Experts and is a model architecture design.

The model internally contains multiple "expert" sub-networks, and only a portion of them is activated when processing an input, rather than having all parameters participate in the computation.

This allows for controlling the actual computational load while expanding the total model size, achieving "large parameters and fast inference."

Training phase English Main function Dependent data
Pre-training Pre-training Learning language patterns and laying the foundation for capabilities Massive unlabeled text
Supervised Fine-Tuning SFT Learn to answer questions according to instructions Human-labeled question-answer pairs
Reinforcement Learning from Human Feedback RLHF Output that better aligns with human preferences Human scoring/ranking of answers
Alignment Alignment Making the model useful, honest, and safe Throughout the above stages

How developers use large models

This is the part that novice developers need to focus on the most: how to use the API to have the large model serve the application.

This section first provides a most basic, directly runnable dialogue calling example, and then expands on each concept.

Basic API dialogue calling

The following code demonstrates a complete conversation request, utilizing the concepts of System Prompt, user message, and temperature.

Example

Installation: pip install openai

from

openai

import

OpenAI

import

os

Create a client. This code can be reused for services compatible with the OpenAI protocol,

switching to another service provider only requires changing api_key and base_url

client

=

OpenAI

(

api_key

=

os

.

getenv

(

"OPENAI_API_KEY"

)

,

 

Read key from environment variable (required)

)

Initiate a conversation request

response

=

client.

chat

.

completions

.

create

(

    model

=

"gpt-4o-mini"

,

 

Model name (required), change according to the service provider used

messages

=

[

       

System Prompt: Pre-set the model's role and behavioral norms

       

{

"role"

:

"system"

,

"content"

:

You are a professional Python programming assistant, and you only answer technical questions.

}

,

       

User message: The actual question

       

{

"role"

:

"user"

,

"content"

:

"What is runoob?"

}

,

   

]

,

temperature

=

0.7

,

 

Generate temperature, value range 0~2, the larger the value, the more divergent (see below)

)

Print model response

print

(

"Response:"

,

response.

choices

[

0

]

.

message

.

content

)

The usage field records the number of Tokens consumed by this call (billing basis).

print

(

"Input Token count:"

,

response.

usage

.

prompt_tokens

)

print

(

"Output Token count:"

,

response.

usage

.

completion_tokens

)

Output result:

Original prompt (Chinese, left untranslated)



回答:runoob(菜鸟教程)是一个提供编程教程的中文学习网站……

输入 Token 数:33

输出 Token 数:18

The usage field in the returned structure is the implementation of the Token concept mentioned above: it tells you how many Tokens this call consumed and is also the basis for billing.

Prompt

The Prompt is the instruction or question you input to the model, which directly determines the quality of the model's output.

Researching techniques to write clearer and more effective Prompts is called Prompt Engineering.

Common techniques include: providing specific examples, requiring step-by-step thinking, and specifying output formats.

System Prompt

Instructions preset for the model before the user's formal input, used to define the model's role, behavioral norms, and background knowledge.

The "You are a professional Python programming assistant and only answer technical questions" in the example above is a typical System Prompt.

The difference between System Prompt and user messages: System Prompt sets "how the model should act," while user messages propose "what specifically needs to be done."

Placing general guidelines in the System Prompt helps maintain a consistent response style across multiple turns of conversation.

Temperature

Temperature is a parameter that controls the randomness of the model's output, and its value range is generally 0 to 2.

The higher the temperature, the more "creative" and random the answer, and the more likely it is to be wrong; the lower the temperature, the more conservative and stable the answer.

Value Range Output Characteristics Applicable Scenarios
Close to 0 Almost certain, stable and reproducible Writing code, data extraction, factual Q&A
0.3 ~ 0.7 Some variation but controllable General conversation, translation, summarization
0.8 ~ 1.2 Rich in creativity, diverse Brainstorming, copywriting, story creation
Greater than 1.2 Highly random, easy to deviate Use with caution, for special creative scenarios only

In-Context Learning

No fine-tuning of the model is required; by providing a few examples in the Prompt, the model can mimic and complete new similar tasks.

This is one of the most commonly used techniques in Prompt Engineering, also known as Few-shot Learning.

Chain-of-Thought (CoT)

Guides the model to break down complex problems into step-by-step reasoning processes before providing the final answer, instead of jumping directly to the conclusion.

Practice has proven that this method can significantly improve the model's accuracy on complex tasks such as mathematics and logical reasoning.

The simplest way is to add the phrase "Please think step by step" in the Prompt.

Hallucination

Hallucination refers to content generated by the model that appears reasonable and fluent, but is actually incorrect or fabricated.

This is a common flaw in LLMs, because the model is essentially "continuing the most probable text" rather than "verifying facts."

One of the core methods to mitigate hallucination is RAG, as described below: first retrieve real data, then have the model answer based on that data.


Connecting the model to the external world

A pure LLM can only answer questions based on the knowledge learned during training; it does not know the latest information or have the ability to take proactive actions.

The technologies in this section are key to solving these two shortcomings.

Embedding

Embedding converts content such as text and images into a sequence of numbers (vectors).

After conversion, the computer can determine if two pieces of content are semantically similar by calculating the distance between the vectors.

This is the underlying foundation for applications like search, recommendation, and RAG.

Vector Database

A vector database is specifically used to store and retrieve Embedding vectors, such as Pinecone, Milvus, and Chroma.

It can quickly find content most semantically similar to the query among massive amounts of vectors, making it an essential component for building RAG systems.

RAG (Retrieval-Augmented Generation)

RAG stands for Retrieval-Augmented Generation.

Its workflow is: first convert the external knowledge base into vectors and store them in a vector database; when the user asks a question, retrieve the most relevant content; then pass the retrieved results along with the question to the model to generate an answer.

RAG can effectively alleviate hallucinations and allow the model to answer with new knowledge outside of the training data.

RAG retrieval-augmented generation process diagram

Below is a minimal RAG example implemented using OpenAI Embedding and numpy, which does not rely on an external vector database, to facilitate understanding the principle:

Example

Installation: pip install openai numpy

from

openai

import

OpenAI

import

numpy

as

np

import

os

client

=

OpenAI

(

api_key

=

os

.

getenv

(

"OPENAI_API_KEY"

)

)

Simulate a very small "knowledge base": a few documents

documents

=

[

   

"runoob is a Chinese learning website that provides programming tutorials."

,

   

"RAG reduces large model hallucinations by generating based on retrieved real data."

,

   

"Python uses indentation to represent code blocks, and it is generally recommended to use 4 spaces for each level of indentation."

,

]

Step 1: Vectorize the knowledge base (build offline, only needs to be done once)

doc_resp

=

client.

embeddings

.

create

(

input

=

documents

,

model

=

"text-embedding-3-small"

)

doc_vectors

=

[

d.

embedding

for

d

in

doc_resp.

data

]

Step 2: Vectorize the user question

question

=

"What is runoob?"

query_vector

=

client.

embeddings

.

create

(

   

input

=

question

,

model

=

"text-embedding-3-small"

)

.

data

[

0

]

.

embedding

Step 3: Find the most relevant documents using cosine similarity

def

cosine

(

a

,

b

)

:

    a

,

b

=

np.

array

(

a

)

,

np.

array

(

b

)

   

return

float

(

a

@

b /

(

np.

linalg

.

norm

(

a

)

linalg

.

norm

(

b

)

)

)

scores

=

[

cosine

(

query_vector

,

v

)

for

v

in

doc_vectors

]

best_doc

=

documents

[

int

(

np.

argmax

(

scores

)

)

]

 

Documents with the highest similarity

print

(

"Retrieved documents:"

,

best_doc

)

Step four: Submit the retrieved documents along with the question to the model to generate an answer

response

=

client.

chat

.

completions

.

create

(

    model

=

"gpt-4o-mini"

,

messages

=

[

       

{

"role"

:

"system"

,

"content"

:

"Please answer the questions only based on the information provided below, do not make up information that is not in the material."

}

,

       

{

"role"

:

"user"

,

"content"

: f

"Data: {best_doc}\n\nQuestion: {question}"

}

,

   

]

,

)

print

(

"Answer:"

,

response.

choices

[

0

]

.

message

.

content

)

Output result:

Original prompt (Chinese, left untranslated)



检索到的资料:runoob 是一个提供编程教程的中文学习网站。

回答:runoob(菜鸟教程)是一个提供编程教程的中文学习网站。

In a real project, you just need to replace "calculate similarity in memory" in step three with "call vector database retrieval," and the workflow remains exactly the same.

Function Calling

Function Calling allows large models to call external tools or APIs to complete tasks, such as querying real-time weather, performing mathematical calculations, querying databases, or sending emails.

It compensates for the model's flaw of "only being able to generate text and not execute actions," which is a key step in the evolution of large models from chatbots to practical tools.

Its operation involves a two-round interaction: in the first round, the model decides which function to call and what parameters to pass; after your code actually executes the function, the second round returns the result, allowing the model to generate a natural language response.

Example

from

openai

import

OpenAI

import

json

import

os

client

=

OpenAI

(

api_key

=

os

.

getenv

(

"OPENAI_API_KEY"

)

)

Define tools (functions) that the model can call

tools

=

[

   

{

       

"type"

:

"function"

,

       

"function"

:

{

           

"name"

:

"get_weather"

,

           

"description"

:

"Query real-time weather for a specified city"

,

           

"parameters"

:

{

               

"type"

:

"object"

,

               

"properties"

:

{

                   

"city"

:

{

"type"

:

"string"

,

"description"

:

City name, for example: Hangzhou

}

               

}

,

               

"required"

:

[

"city"

]

,

           

}

,

       

}

,

   

}

]

Local function that actually executes the query (replace with real weather API in actual projects)

def

get_weather

(

city

)

:

   

return

f

"{city} is sunny today, temperature 28°C"

Round 1: Give the question to the model, and the model decides which tool to call and what parameters to pass

response

=

client.

chat

.

completions

.

create

(

    model

=

"gpt-4o-mini"

,

    messages

=

[

{

"role"

:

"user"

,

"content"

:

"What is the weather like in Hangzhou today?"

}

]

,

tools

=

tools

,

)

tool_call

=

response.

choices

[

0

]

.

message

.

tool_calls

[

0

]

args

=

json.

loads

(

tool_call.

function

.

arguments

)

 

Parse out parameters, for example {"city": "Hangzhou"}

result

=

get_weather

(

args

[

"city"

]

)

 

Actual execution tool

print

(

"Tool execution result:"

,

result

)

Second round: feed the tool results back to the model to generate a natural language answer based on the results

follow_up

=

client.

chat

.

completions

.

create

(

    model

=

"gpt-4o-mini"

,

messages

=

[

       

{

"role"

:

"user"

,

"content"

:

"What is the weather like in Hangzhou today?"

}

,

response.

choices

[

0

]

.

message

,

 

The model's decision to "call a tool" in the previous step

       

{

"role"

:

"tool"

,

"tool_call_id"

: tool_call.

id

,

"content"

: result

}

,

 

Tool return result

   

]

,

tools

=

tools

,

)

print

(

"Final answer:"

,

follow_up.

choices

[

0

]

.

message

.

content

)

Output result:

Original prompt (Chinese, left untranslated)



工具执行结果:杭州 今天晴,气温 28°C

最终回答:杭州今天是晴天,气温大约 28°C,适合外出活动。

MCP (Model Context Protocol)

MCP stands for Model Context Protocol, an open protocol that standardizes how large models connect to external tools and data sources.

It can be compared to a "USB interface in the AI field": as long as different tools and data sources adhere to this protocol, they can be uniformly called by various large models that support MCP.

It solves the problem of "repeatedly integrating every tool" in the Function Calling era, reducing development workload.

Agent

An Agent is a system built on a large model that can autonomously plan tasks, call tools, and execute multi-step operations.

Compared to a question-and-answer dialogue, an Agent is more like a "digital employee" that can independently complete complex tasks, such as automatically running the entire process of "search for information → write code → test → fix bugs."

Its core loop relies on ReAct (Reason + Act): think about the next step, call a tool, observe the results, and then think again until the task is complete.

Agent workflow diagram

Multimodal

Multimodal refers to the model's ability to simultaneously understand and/or generate multiple types of data, not limited to text, but also including images, audio, and video.

Many mainstream large models now possess multimodal capabilities such as reading images and analyzing charts.

Technology Problem Solved One-sentence understanding
Embedding Let the computer understand semantic similarity Convert text into computable vectors
Vector database Efficiently store and retrieve vectors A dedicated repository for semantic search
RAG The model does not know or fabricates the latest knowledge Check the materials before answering
Function Calling The model can only generate text and cannot perform actions Allow the model to call external tools
MCP Every tool connected requires repeated development Unified USB interface for AI tools
Agent Single-turn conversation cannot complete complex tasks Digital employees capable of autonomous multi-step planning

Make models run faster and more efficiently

The stronger a model's capabilities, the larger its size and the higher its running cost are often.

The two concepts below are designed to make models lighter and more efficient during actual deployment.

Quantization

Quantization compresses model parameters from high precision (e.g., 32-bit floating-point numbers) to low precision (e.g., 8-bit or 4-bit integers).

It can significantly reduce the GPU memory used by the model and improve inference speed, at the cost of some accuracy loss, which is acceptable in many scenarios.

Model Distillation

Use the output of a powerful but large "teacher model" to train a smaller "student model" for distillation.

The goal is to enable the small model to learn the capabilities of the large model, resulting in a smaller, faster inference, and lower deployment cost for the distilled model.

Comparison items Quantization Distillation
What to do Compress parameter precision (32-bit -> 8/4-bit) Use a large model to teach a small model
What is changed is the numerical representation of the same model to obtain a new small model
Main benefits saving VRAM and increasing speed smaller models are stronger and faster
Whether retraining is necessary Usually no retraining is required Need to train student models
Typical scenarios Fitting large models into limited VRAM Replacing large models with small models for deployment

Learning path for beginners

For novice developers, it is not necessary to grasp all concepts at once.

It is recommended to proceed step-by-step in the following order, which will be easier to build a complete system than memorizing concepts in isolation.

Stage Grasp the concepts Be able to do
First step LLM, Token, Prompt Call API to complete conversation
Second step Embedding, vector database, RAG Connect external knowledge to the model
Step 3 Function Calling, Agent Allowing the model to call tools and complete tasks autonomously
Step 4 Fine-tuning, quantization, distillation Production environment deployment and optimization

You don't need to memorize the definitions of every concept; running the code examples in this document will help you understand them much deeper.


Core Terminology Quick Reference

Compile all key terms appearing in the entire document into a table, grouped by "Relevant Stage," for easy reference and review.

Term English / Full Name Relevant Stage One-sentence explanation
LLM Large Language Model (Large Language Model) Basic Concept A deep learning model trained on massive amounts of text is essentially "predicting the next word"
Transformer Transformer Basic concept The underlying network architecture shared by almost all modern LLMs
Attention mechanism Attention / Self-Attention Basic concept Allow the model to dynamically focus on relevant words in the input to understand contextual relationships
Token Token Basic Concepts The smallest unit of text processed by the model; context length and API billing are both calculated based on it
Context Window Context Window Basic Concepts Maximum number of tokens a model can "see" and process at once
Parameter count Parameters Basic concepts The number of weights that can be learned internally by the model, often measured in billions (B)
Pre-training Pre-training Training Learn language patterns on massive amounts of unlabeled text to lay the foundation for capabilities
SFT Supervised Fine-Tuning Training Teach the model to answer questions according to instructions using question-answer pair data
RLHF Reinforcement Learning from Human Feedback Training Calibrate model output using human scoring to better align with human preferences
RLAIF Reinforcement Learning from AI Feedback Training Replace human scoring with AI to reduce annotation costs
Alignment Alignment Training Make the model's behavior align with human intent, ensuring it is helpful, honest, and safe
Fine-tuning Fine-tuning Training Continue training on a general model using domain data to adapt to professional scenarios
MoE Mixture of Experts Training Multiple expert sub-networks are activated on demand, large parameters and fast inference
Prompt Prompt Use The instructions or questions given to the model directly determine the output quality
Prompt Engineering Prompt Engineering Use Research techniques for writing clearer and more effective Prompts
System Prompt System Prompt Usage Instructions to pre-set the model's role and behavioral norms
Temperature Temperature Usage Parameter to control output randomness, takes values from 0 to 2, larger means more divergent
Context learning In-Context Learning Use Provide a few examples in the Prompt and it will follow, also known as Few-shot
Chain-of-Thought Chain-of-Thought (CoT) Use Guide the model to step-by-step reasoning before providing an answer to improve accuracy on complex tasks
Hallucination Hallucination Usage The model generates fluent but incorrect or fabricated content
Embedding Embedding External world Convert content into vectors to measure semantic similarity
Vector database Vector Database External world A database specifically for storing and retrieving vectors, such as Milvus or Chroma
RAG Retrieval-Augmented Generation External world First retrieve real data before generating to alleviate hallucinations and supplement new knowledge
Function Calling Function Calling External World Allow the model to call external tools or APIs to perform actual actions
MCP Model Context Protocol External World Open protocol for standardized connection tools, the "USB interface" of AI
Agent Agent External world A system capable of autonomous planning, tool invocation, and multi-step execution of complex tasks
ReAct Reason + Act External world Agent's core loop: Think—Act—Observe—Think again
Multimodal Multimodal External world Simultaneously understanding and/or generating multiple data types such as text, images, audio, etc.
Quantization Quantization Optimization Compression parameter precision (32-bit -> 8/4-bit), saves VRAM and increases speed
Model Distillation Model Distillation Optimization Using large models to teach small models to obtain smaller and faster deployment models