Runoob Tutorial ArchiveEnglish

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.

runoob llm work

We can imagine a large language model asan extremely diligent student with an excellent memory.:

Its "large" nature is mainly reflected in two aspects:

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:

d689a96f f89a 4a55 83d7 fe5aa789d836

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:

The way Transformer works is similar to this; its core process is divided into three stages:

  1. Input processing: Your words are broken down into words or characters (Tokens) and converted into numbers that computers can understand (vectors).
  2. 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
  3. 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.

llm runoob transf scaled

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:

Self-attention mechanism diagram Shows the attention weights of the query word "it" over other words in the sentence. A thicker arc means stronger attention: "it" attends strongly to "apple" and "phone", but has lower weights for "battery" and "very big". Apple Phone It Battery Very big "it" (the query word, highlighted) attention weights over each word High weight Mid weight Low weight The thicker and darker the arc, the more the model attends to that word.

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:

Prompt basic structure diagram A good prompt consists of four modules: context (role and background), instructions (task objective), examples (reference demonstrations, optional), and format requirements (output format). Together they produce better outputs. Context Role and background + Instruction Clarify the task objective + Example (optional) Examples and counterexamples + Format requirements Output format and length The four modules together form a clear, complete prompt.

Basic Principles

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?"

,

)

print

(

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's
  • deepseek-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

       

    print

    (

    "Reply result:"

    ,

    response.

    choices

    [

    0

    ]

    .

    message

    .

    content

    )

    except

    Exception

    as

    e:

       

    print

    (

    "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:

    83536c84 3956 4679 ad14 99d53e69769 scaled

    p994 9

    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

    f9be5f87 ed 4d85 b a4 ad854 31 d6f

    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())

       

    print

    (

    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"

    )

    :

                   

    print

    (

    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:

    Model name Company/organization Official website/API documentation address
    GPT series OpenAI Official Website:https://openai.com/
    API Address:https://platform.openai.com/docs/api-reference
    Claude Series Anthropic Official Website:https://www.anthropic.com/
    API Address:https://docs.anthropic.com/claude/reference/getting-started-with-the-api
    Gemini Series Google Official Website:https://deepmind.google/technologies/gemini/
    API Address:https://docs.gemini.com/rest-api/
    Tongyi Qianwen Alibaba Official Website:https://www.qianwen.com/
    API Address:https://help.aliyun.com/zh/dashscope/developer-reference/api-details
    Wenxin Yiyan Baidu Official website:https://yiyan.baidu.com/
    API address:https://qianfan.cloud.baidu.com/docs/
    Zhipu AI Zhipu AI Official website:https://chatglm.cn/
    API address:https://open.bigmodel.cn/dev/api
    Kimi Moonshot AI Official Website:https://kimi.moonshot.cn/
    API Address:https://platform.moonshot.cn/docs/api/chat
    DeepSeek Series DeepSeek Official Website:https://www.deepseek.com/
    API Address:https://api-docs.deepseek.com/
    Llama Series Meta Official Website:https://www.llama.com/
    API Address:https://www.llama.com/docs/overview/
    Grok Series xAI Official Website:https://x.ai/
    API Address:https://docs.x.ai/overview
    MiniMax MiniMax Official website:https://www.minimaxi.com/
    API address:https://api.minimax.chat/docs/api/
    BaiChuan Intelligence BaiChuan Intelligence Official website:https://www.baichuan-ai.com/
    API address:https://platform.baichuan-ai.com/docs/api
    Ollama Ollama Official Website:https://ollama.com/
    API Address:https://github.com/ollama/ollama/blob/main/docs/api.md
    Doubao Large Model ByteDance Official Website:https://www.doubao.com/
    API Address:https://www.volcengine.com/docs/82379/1399008?lang=zh