Large Language Model Basics (LLM)
Large Language Model Basics (LLM)
Large Language Models (LLM) are the brain of AI Agents; understanding this is fundamental to building intelligent Agents.
The reason Large Language Models can converse with you, write articles, and program is essentially that they guess the most reasonable next text, character by character, based on the text (prompt) you provide.
Simply put, a large language model is a deep learning model trained on massive amounts of text data, enabling it to understand and generate human language. The large language model learns the statistical patterns of language by analyzing vast amounts of text from the internet, and when it receives input, it generates the most reasonable continuation based on the learned patterns.

We can imagine a large language model asan extremely diligent student with an excellent memory.:
-
Learning Phase (Training): It has read almost all publicly available text on the internet—books, articles, web pages, code, etc. (the data volume reaches the trillion-word level). During this process, it is not memorizing, but learning an extremely complex set of linguistic rules.
-
Application Phase (Inference): When you ask it a question or give it an instruction, it applies the learned rules to generate the most logical and contextual answer, word by word.
Its "large" nature is mainly reflected in two aspects:
- Large parameter scale: The model has hundreds of billions or even trillions of adjustable parameters internally, which record the learned language knowledge.
- Large training data: The volume of text data used for training is huge, covering the essence of publicly available internet information.
The figure below shows the process of LLM generating text word by word—it predicts only one word at a time, then incorporates this new word into the input to continue predicting the next word, cycling until the complete answer is generated:

Animation demonstration:
The large model is thinking
…
Do one thing at each step: guess the next character based on the preceding text
▌
Candidate for the next character
Top-5 probability
step0
Selected:—
Although LLMs are powerful, they also have clear limitations:
| Capability | Description | Limitations |
|---|---|---|
| Knowledge cutoff | Training data has a cutoff date | Cannot know new information after training |
| Mathematical computation | Can perform simple calculations | Complex calculations are prone to errors |
| Real-time information | Requires external tools for assistance | Cannot obtain real-time data on its own |
| Factual accuracy | May generate incorrect information | Requires fact-checking |
| Long text processing | Context length is limited | Ultra-long texts may lose information |
| Logical consistency | May be contradictory | Requires careful design and verification |
Important reminder:LLMs are not omniscient or omnipotent; they are essentially statistical pattern matching systems. Understanding their limitations allows for better utilization of their capabilities.
Core working principle: A brief analysis of the Transformer architecture
The amazing capabilities of LLMs are inseparable from their underlying core technology—Transformer architecture. You do not need to delve into complex mathematical principles, but you can understand its core idea.
Imagine you want to write an article about the solar system:
- Reading materials: You would first look at many related books and webpages.
- Grasp the main points: You will notice that words like sun, planet, orbit, and gravity appear frequently and are interconnected.
- Organize the language: Based on the focus you want to express (e.g., introducing Mars), you will selectively use the information you saw earlier about Mars's size, color, position, etc., and organize it into coherent sentences.
The way Transformer works is similar to this; its core process is divided into three stages:
- Input processing: Your words are broken down into words or characters (Tokens) and converted into numbers that computers can understand (vectors).
- Context understanding (core):Self-AttentionIt allows the model to weigh the importance ofall other words in the sentence when processing each word in the sentence. This process isparalleland extremely fast.Generation and loop
- Generation and LoopThe model calculates a probability distribution based on the understanding of all words to predict the next most likely word. After selecting and outputting this word, it is used as new input, and the entire process is repeated until a complete answer is generated.

The self-attention mechanism is the most critical innovation in Transformer. Taking the sentence "Apple's phone, its battery is very large" as an example, when the model processes the word "it", the self-attention mechanism helps the model determine that it is highly relevant to "apple" and "phone". The figure below shows the attention weight distribution during this process:
It is this ability toprocess in parallelanddeeply understand the global contextthat makes Transformer-based LLMs far surpass previous technologies (such as RNNs) in language tasks.
How to interact with LLMs: Introduction to Prompt Engineering
**Prompt** is the input you give to the LLM; it tells the model what you want, just like giving instructions to an assistant—the clearer the instruction, the better the result. The quality of the Prompt directly determines the quality of the answer.
A good Prompt is usually composed of the following four parts:
Basic Principles
-
Be specific and concrete: Avoid vague expressions. Do not sayWrite something about dogs, but instead sayWrite a short introduction of about 100 words about the personality characteristics of a Golden Retriever for children aged 6-8 using vivid and lively language.
-
Provide context: Tell the model your identity, background, and goals. For example:You are an experienced Python programming tutor. Please explain what a list comprehension is to a beginner who has just finished learning basic syntax and provide a simple example.
-
Specify format: If you need a specific output format, please state it clearly, for example:Please summarize the following points into three bullet pointsorPlease output in JSON format.
-
Chain-of-Thought: For complex problems, you can guide the model to reason step-by-step in the Prompt, for example:Please analyze this problem step by step, first list the known conditions, then derive the intermediate steps, and finally provide the conclusion.This method can significantly improve the accuracy of complex reasoning tasks.
Common application scenarios for LLM
| Scenario category | Specific Examples | Description |
|---|---|---|
| Content Creation and Editing | Writing emails, reports, blogs; continuing stories; polishing copy; translating texts of different styles | Quickly generating drafts and providing inspiration and various ways of expression |
| Information Retrieval and Summarization | Quickly reading long documents and extracting core ideas; Q&A based on knowledge bases | "Understanding" questions better than traditional search, capable of summarization and integration |
| Programming Assistance | Explaining code, generating code snippets, debugging errors, refactoring code, writing test cases | Acting as an all-day programming partner to greatly improve development efficiency |
| Conversation and Customer Service | Intelligent chatbots, personalized tutors, role-playing | Providing a humanized, contextually coherent interaction experience |
| Logical Reasoning and Analysis | Solving math problems, performing basic logical reasoning, analyzing data trends, making plans | Demonstrating surprising reasoning ability within a limited domain |
API calls and parameter settings
To build an AI Agent, you need to learn how to call an LLM via API.
In this chapter, we will use the OpenAI API as an example to introduce basic calling methods.
openai is a powerful Python library for interacting with a series of OpenAI models and services; for detailed information, refer to: Python OpenAI
Open source address:https://github.com/openai/openai-python
Basic API calls
1. Install the necessary libraries
pip install openai
Then you need to register an account on the OpenAI official website and generate an API Key on the API key page.
Instance
import
os
from
openai
import
OpenAI
client
=
OpenAI
(
This is the default and can be omitted
api_key
=
"The API key you applied for"
,
)
response
=
client.
responses
.
create
(
model
=
"gpt-4o"
,
instructions
=
"You are a coding assistant that talks like a pirate."
,
input
=
"How do I check if a Python object is an instance of a class?"
,
)
(
response.
output_text
)
Accessing openai in China is still a bit troublesome; many domestic services also support openai, such as DeepSeek and Alibaba's Qwen.
DeepSeek
The DeepSeek API is fully compatible with the OpenAI API format. By modifying a few configurations, you can directly use the OpenAI SDK or compatible tools to access the DeepSeek API.
Core configuration parameters:
| Parameters | Value/Description |
|---|---|
| base_url | Required, fixed value:https://api.deepseek.com(Can also be filledhttps://api.deepseek.com/v1, only for OpenAI compatibility, unrelated to v1 and model version) |
| api_key | Required, must first apply for a dedicated API Key on the DeepSeek official website (Application address:https://platform.deepseek.com/) |
| model | Required,
|
deepseek-v4-flash: Corresponding to DeepSeek'snon-thinking mode, fast response speed, suitable for general Q&A;: Corresponding to DeepSeek'sdeepseek-v4-prothinking modeThinking modehas stronger reasoning capabilities and is suitable for solving complex problems.Example
import
os
from
openai
import
OpenAI
Initialize client (core configuration: replace with your API Key)
client
=
OpenAI
(
api_key
=
os
.
environ
.
get
(
'DEEPSEEK_API_KEY'
)
,
It is recommended to configure it through environment variables, but you can also hardcode it (not recommended)
base_url
=
"https://api.deepseek.com"
DeepSeek fixed domain
)
Call chat API
try
:
response
=
client.
chat
.
completions
.
create
(
model
=
"deepseek-v4-flash"
,
Specify model, optional deepseek-v4-flash / deepseek-v4-pro
messages
=
[
{
"role"
:
"system"
,
"content"
:
"You are a helpful assistant"
}
,
System Role Definition
{
"role"
:
"user"
,
"content"
:
"Hello"
}
,
User question
]
,
stream
=
False
Non-streaming output (returns the complete result at once)
)
Print the reply content
(
"Reply result:"
,
response.
choices
[
0
]
.
message
.
content
)
except
Exception
as
e:
(
"Call failed:"
,
str
(
e
)
)
Alibaba Cloud Bailian
Tongyi Qianwen models on Alibaba Cloud Bailian support OpenAI compatible interfaces. You only need to adjust the API Key, BASE_URL, and model name to migrate your existing OpenAI code to use the Alibaba Cloud Bailian service.
We need to enable the Alibaba Cloud Bailian model service and obtain an API-KEY.
We can first access the Bailian model service platform using the Alibaba Cloud main account:https://bailian.console.aliyun.com/, then click the login in the upper right corner. After successful login, click the gear icon ⚙️ in the upper right corner, select API key, and copy the API key. If there is none, you can also create an API key:


Enabling Alibaba Cloud Bailian incurs no cost; charges will only apply for model calls (after exceeding the free quota), model deployment, and model tuning.
Now that we need to use the API, billing is based on tokens, but fortunately, they are not expensive. We can first purchase the cheapest package: Alibaba Cloud Bailian Large Model Service Platform
You can also directly use the Bailian and Volcengine Ark Coding Plan package:https://www.runoob.com/claude-code/coding-plan.html.
Usage
Next, we use the OpenAI SDK to access the Qwen model on Bailian service.
Non-streaming call example
Example
from
openai
import
OpenAI
import
os
def
get_response
(
)
:
client
=
OpenAI
(
api_key
=
"sk-xxx"
,
Please use the Alibaba Cloud Bailian API Key
base_url
=
"https://dashscope.aliyuncs.com/compatible-mode/v1"
,
Fill in the base_url of the DashScope SDK
)
completion
=
client.
chat
.
completions
.
create
(
model
=
"qwen-plus"
,
Here, we use qwen-plus as an example; you can replace the model name as needed. Model list: https://help.aliyun.com/zh/model-studio/getting-started/models
messages
=
[
{
'role'
:
'system'
,
'content'
:
'You are a helpful assistant.'
}
,
{
'role'
:
'user'
,
'content'
:
'Who are you?'
}
]
)
json data
#print(completion.model_dump_json())
(
completion.
choices
[
0
]
.
message
.
content
)
if
name
==
'main'
:
get_response
(
)
Running the code can yield the following results:
Original prompt (Chinese, left untranslated)
我是通义千问,阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我可以帮助你回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等,还能表达观点,玩游戏等。如果你有任何问题或需要帮助,欢迎随时告诉我!
Streaming call example
Instance
from
openai
import
OpenAI
def
get_response
(
)
:
client
=
OpenAI
(
api_key
=
"sk-xxx"
,
base_url
=
"https://dashscope.aliyuncs.com/compatible-mode/v1"
,
)
completion
=
client.
chat
.
completions
.
create
(
model
=
"qwen-plus"
,
messages
=
[
{
'role'
:
'system'
,
'content'
:
'You are a helpful assistant.'
}
,
{
'role'
:
'user'
,
'content'
:
'Who are you?'
}
]
,
stream
=
True
,
stream_options
=
{
"include_usage"
:
True
}
)
for
chunk
in
completion:
The chunk may not have choices or delta
if
hasattr
(
chunk
,
"choices"
)
and
len
(
chunk
.
choices
)
0
:
choice
=
chunk
.
choices
[
0
]
if
hasattr
(
choice
,
"delta"
)
and
hasattr
(
choice.
delta
,
"content"
)
:
(
choice.
delta
.
content
,
end
=
''
,
flush
=
True
)
if
name
==
'main'
:
get_response
(
)
Running the code can yield the following results:
Original prompt (Chinese, left untranslated)
我是通义千问,阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我可以帮助你回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等,还能表达观点,玩游戏等。如果你有任何问题或需要帮助,欢迎随时告诉我!
Mainstream large language models
Here is a compilation of the official websites and API documentation addresses for mainstream large language models:
