一、大模型
大模型(Large Model)是指参数规模庞大、训练数据量巨大、具有强泛化能力的人工智能模型,典型代表如 GPT、BERT、PaLM 等。它们通常基于深度神经网络,特别是 Transformer 架构,在自然语言处理、图像识别、代码生成等任务中表现出色。
1. 基本概念

本文介绍了大模型的基本概念、特征及应用方向,重点讲解了通过 API 调用和本地部署两种方式使用大语言模型。内容涵盖 DeepSeek API 的流式与非流式调用示例,以及使用 Ollama、Transformers 库进行本地模型部署的具体步骤和参数调优方法,适合希望掌握大模型落地技术的开发者参考。
大模型(Large Model)是指参数规模庞大、训练数据量巨大、具有强泛化能力的人工智能模型,典型代表如 GPT、BERT、PaLM 等。它们通常基于深度神经网络,特别是 Transformer 架构,在自然语言处理、图像识别、代码生成等任务中表现出色。

大模型是指在超大规模数据集上训练、拥有数十亿到千亿以上参数的人工智能模型,具备多任务、多模态能力,并能通过少量样本甚至零样本完成新任务。
大模型具备以下特征:

大模型开发是一个系统工程,涉及数据、模型、算力、训练、部署、安全与迭代等多个环节。

三个模块
项目展示
![]() |
|---|
![]() |
大模型通过 API 调用是目前最常见、最便捷的使用方式,用户无需训练模型,只需调用接口即可享受强大的 AI 能力,比如文本生成、翻译、图像识别、代码补全等。
API Key 或 Access Token。
大模型 API 调用将复杂的模型能力简化为标准化服务,核心价值在于:
DeepSeek 作为国内优秀的 LLM 平台,是一个不错的选择。
等模型生成完整结果后一次性返回,适合短文本、结构化内容提取等任务。
输出结果示例:
'明月几时有'是苏轼《水调歌头·明月几时有》中的名句,全文如下:
《水调歌头·明月几时有》
明月几时有?把酒问青天。不知天上宫阙,今夕是何年。我欲乘风归去,又恐琼楼玉宇,高处不胜寒。起舞弄清影,何似在人间。转朱阁,低绮户,照无眠。不应有恨,何事长向别时圆?人有悲欢离合,月有阴晴圆缺,此事古难全。但愿人长久,千里共婵娟。
赏析:
- 背景:此词作于宋神宗熙宁九年(1076 年)中秋,苏轼在密州(今山东诸城)任职时,怀念弟弟苏辙而写。
- 情感:以月起兴,围绕中秋明月展开想象,交织人间情怀与宇宙哲思,既有对亲人的思念,又有对人生无常的豁达。
- 名句:
- '人有悲欢离合,月有阴晴圆缺'道出世事无常的常态。
- '但愿人长久,千里共婵娟'成为表达远方亲友平安共勉的千古绝唱。
非流式输出代码:
# Please install OpenAI SDK first: pip3 install openai
from openai import OpenAI
client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://api.deepseek.com"
)
response = client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "system", "content": "You are a helpful assistant"},
{"role": "user", "content": "明月几时有"},
],
stream=False,
)
print(response.choices[0].message.content)
环境安装:
pip install openai
服务器将响应内容一段一段地实时返回,适合长文本、对话、写作等需要即时反馈的场景。

流式推理代码编写:
from openai import OpenAI
client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://api.deepseek.com"
)
response = client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "system", "content": "You are a helpful assistant"},
{"role": "user", "content": "明月几时有"},
],
stream=True,
)
# 流式输出
out = []
for chunk in response:
print(chunk.choices[0].delta.content)
out.append(chunk.choices[0].delta.content)
print('-' * 10)
print(''.join(out))
流式推理的实现—生成器:
import time
def test():
# 生成器函数
for i in range(10):
time.sleep(1)
yield i
if __name__ == "__main__":
aaa = test()
print(aaa) # aaa 是一个生成器,可以想象成一个队列,每读取一次,就会执行一次函数体
for a in aaa:
print(a) # 读取生成器中的值
| 项目 | 流式输出 | 非流式输出 |
|---|---|---|
| 返回方式 | 边生成边返回 | 全部生成后一次返回 |
| 响应速度 | 快 | 慢(尤其是长文本) |
| 使用体验 | 更自然(打字式) | 等待过程较长 |
| 编程复杂度 | 稍复杂(需拼接) | 简单 |
| 适用场景 | 对话生成、直播问答 | 简短回复、结构化处理 |
将代码封装为类,方便其他文件调用此功能。
非流式输出:
from openai import OpenAI
class DeepseekAPI:
def __init__(self, api_key): # 初始化方法
self.api_key = api_key # API 密钥
self.client = OpenAI(
api_key=api_key, base_url="https://api.deepseek.com"
) # 实例化 OpenAI 客户端
def inference(self, messages):
response = self.client.chat.completions.create(
model="deepseek-chat",
messages=messages, # 消息内容
stream=False, # 设置为 False 以获取完整响应
)
return response.choices[0].message.content # 返回完整响应
# 测试代码
if __name__ == "__main__":
api_key = "YOUR_API_KEY" # API 密钥
messages = [
{"role": "system", "content": "你是一名 AI 助手"},
{"role": "user", "content": "请简要介绍一下你自己"},
] # 定义消息内容
stream = False # 设置为 True 以获取流式输出,False 以获取完整响应
deepseek_api = DeepseekAPI(api_key) # 实例化 DeepseekAPI 类
result = deepseek_api.inference(messages) # 调用推理方法
print(result) # 打印响应内容
流式输出:
# 流式输出
from openai import OpenAI
class DeepseekAPI:
def __init__(self, api_key): # 初始化方法
self.api_key = api_key # API 密钥
self.client = OpenAI(
api_key=api_key, base_url="https://api.deepseek.com"
) # 实例化 OpenAI 客户端
def inference(self, messages):
response = self.client.chat.completions.create(
model="deepseek-chat",
messages=messages, # 消息内容
stream=True, # 设置为 True 以获取流式响应
)
for chunk in response: # 遍历响应的每个块
if chunk.choices: # 如果块中有返回内容
content = chunk.choices[0].delta.content # 获取内容
yield content # 逐块返回内容
# 测试代码
if __name__ == "__main__":
api_key = "YOUR_API_KEY" # API 密钥
messages = [
{"role": "system", "content": "你是一名乐于助人的人工智能助手"},
{"role": "user", "content": "请简要介绍一下你自己"},
] # 定义消息内容
stream = False # 设置为 True 以获取流式输出,False 以获取完整响应
deepseek_api = DeepseekAPI(api_key) # 实例化 DeepseekAPI 类
result = deepseek_api.inference(messages) # 调用推理方法
for chunk in result: # 遍历响应的每个块
print(chunk,) # 打印每个块的内容
各种大模型资源:
在国产大模型领域,Qwen 系列一直稳居前列,其出色的性能使其在多项评测中名列前茅。作为阿里巴巴的一项重要研发成果,Qwen 系列的开源版本在业内备受瞩目,且长期以来在各大榜单上表现优异。

这张图表展示了多个大语言模型(LLMs)在不同评估基准上的性能表现,各列的参数含义如下:
7B 表示模型有 70 亿参数。搜索对应的模型即可。 官方指导:通义千问 3-0.6B
搜索对应的模型即可。 官方指导:https://huggingface.co/Qwen/Qwen3-0.6B
Ollama 是一个开源工具,用于在本地计算机上快速运行、管理和部署大型语言模型(LLMs)。它支持多种开源模型(如 Llama 3、Mistral、Gemma、Qwen 等),并提供简单命令行操作,适合开发者和研究者本地测试 LLM。
官网:Ollama 支持的模型:Ollama Search
下载安装即可,Ollama 安装硬件要求:
| 命令 | 说明 |
|---|---|
ollama pull <模型名> | 下载模型(如 llama3) |
ollama run <模型名> | 运行模型交互式对话 |
ollama list | 查看已安装模型 |
ollama rm <模型名> | 删除模型 |

ollama pull qwen:7b # 下载 Qwen-7B
ollama run qwen:7b # 启动聊天
POST http://localhost:11434/api/chat
Content-Type: application/json
{
"model": "qwen3:0.6b",
"messages": [
{ "role": "user", "content": "LLM 是什么?" }
],
"stream": true
}
响应:
{
"message": {
"role": "assistant",
"content": "你好!我不知道实时天气信息,但你可以查看天气预报网站获取最新天气。"
},
"done": true
}
参考 Docker 部署文档。
大模型本地部署是指将大型预训练模型(如 GPT、Llama、BERT 等)完全部署在用户自有的硬件设备(如服务器、本地计算机)上,而非依赖云端 API 服务。
下载模型文件:
set HF_ENDPOINT=https://hf-mirror.com # 加速下载设置
huggingface-cli download deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B --local-dir ./deepseek # 下载模型文件
huggingface-cli download thenlper/gte-large --local-dir ./gte-large
huggingface-cli download BAAI/bge-base-zh --local-dir ./bge-base-zh
安装 huggingface 的下载工具 (python 库):
pip install huggingface_hub
从 huggingface 找到你要下载的模型。

利用 transformer 框架进行部署推理:Transformer 库的使用手册:Transformers 文档
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
# 一:加载模型
model_path = r"./modeldir" # 模型路径
device = "cuda:0" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 # 指定模型参数类型为 float16
model = AutoModelForCausalLM.from_pretrained(model_path, torch_dtype=torch_dtype).to(device)
# 加载模型并移动到 GPU
tokenizer = AutoTokenizer.from_pretrained(model_path) # 加载分词器
# 二:设置生成参数和输入消息
gen_kwargs = {
"max_length": 1024, # 生成的最大长度
"do_sample": True, # 是否使用概率采样
"top_k": 10, # 采样时的前 K 个候选词,越大越随机
"temperature": 0.7, # 生成丰富性,越大越有创造力
"top_p": 0.8, # 采样时的前 P 个候选词,越大越随机
"repetition_penalty": 1.2, # 重复惩罚系数,越大越不容易重复
}
# 定义消息内容
messages = [
{"role": "system", "content": "你是 AI 助手"},
{"role": "user", "content": "明月几时有"},
]
# 三:将输入数据转换为模型可接受的格式
inputs = tokenizer.apply_chat_template(
messages, add_generation_prompt=True, tokenize=True, return_tensors="pt", return_dict=True,
).to(device)
# 将输入数据移动到 GPU
# 四:生成输出
outputs = model.generate(**inputs, **gen_kwargs)
# 生成输出
outputs = outputs[:, inputs["input_ids"].shape[1]:] # 截取生成的输出
result = tokenizer.decode(outputs[0], skip_special_tokens=True) # 解码输出
# 五:打印结果
print(result) # 打印结果
| 应用场景 | 推荐设置 |
|---|---|
| 正常文本生成(如聊天) | 1.1~1.3(防止重复) |
| 模仿风格性强文本(如古诗) | 1.0(或略小) |
| 模型不断重复一句话? | 适当增大 penalty(如 1.5) |
temperature
| Token | Logits | Softmax(T=1) | Softmax(T=0.5) | Softmax(T=2) |
|---|---|---|---|---|
| "猫" | 4.0 | 0.60 | 0.80 | 0.40 |
| "狗" | 3.0 | 0.25 | 0.18 | 0.30 |
| "鸟" | 2.0 | 0.15 | 0.02 | 0.30 |
设置建议:通常设为 0.7-0.95。
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
class DeepSeek:
def __init__(self, model_path, device, torch_dtype):
self.device = device # 设定推理设备
self.model = AutoModelForCausalLM.from_pretrained(
model_path, torch_dtype=torch_dtype
).to(device) # 加载模型并移动到 GPU
self.tokenizer = AutoTokenizer.from_pretrained(model_path) # 加载分词器
def inference(self, messages, gen_kwargs):
inputs = self.tokenizer.apply_chat_template(
messages, add_generation_prompt=True, tokenize=True, return_tensors="pt", return_dict=True,
).to(self.device) # 将输入数据移动到 GPU
outputs = self.model.generate(**inputs, **gen_kwargs) # 生成输出
outputs = outputs[:, inputs["input_ids"].shape[1]:] # 截取生成的输出
result = self.tokenizer.decode(outputs[0], skip_special_tokens=True) # 解码输出
return result
if __name__ == "__main__":
# 一:设定模型路径和设备,加载模型
model_path = r"./modeldir" # 替换为你的模型路径
device = "cuda:0" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16
deepseek = DeepSeek(model_path, device, torch_dtype)
# 二:设定推理参数,推理消息
gen_kwargs = {
"max_length": 1024, # 生成的最大长度
"do_sample": True, # 是否使用概率采样
"top_k": 10, # 采样时的前 K 个候选词,越大越随机
"temperature": 0.7, # 生成丰富性,越大越有创造力
"top_p": 0.8, # 采样时的前 P 个候选词,越大越随机
"repetition_penalty": 1.2, # 重复惩罚系数,越大越不容易重复
}
messages = [
{"role": "system", "content": "你是一名乐于助人的人工智能助手"},
{"role": "user", "content": "写一个 js 判断用户验证码代码"},
] # 定义消息内容
result = deepseek.inference(messages, gen_kwargs) # 调用推理方法
print(result) # 打印结果
from transformers import AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamer
import torch
from threading import Thread
class DeepSeek:
def __init__(self, model_path, device, torch_dtype):
self.device = device # 设定推理设备
self.model = AutoModelForCausalLM.from_pretrained(
model_path, torch_dtype=torch_dtype
).to(device) # 加载模型并移动到 GPU
self.tokenizer = AutoTokenizer.from_pretrained(model_path) # 加载分词器
def inference(self, messages, gen_kwargs):
inputs = self.tokenizer.apply_chat_template(
messages, add_generation_prompt=True, tokenize=True, return_tensors="pt", return_dict=True,
).to(self.device) # 将输入数据移动到 GPU
streamer = TextIteratorStreamer(
self.tokenizer, skip_special_tokens=True
) # 创建流式输出对象
generation_kwargs = dict(**inputs, **gen_kwargs, streamer=streamer) # 生成参数
thread = Thread(
target=self.model.generate, kwargs=generation_kwargs
) # 创建线程
thread.start() # 启动线程进行生成
# 初始化生成文本
generated_text = ""
for new_text in streamer: # 流式输出生成的文本
generated_text += new_text # 累加生成的文本
yield new_text # 逐步返回生成的文本
if __name__ == "__main__":
# 一:设定模型路径和设备,加载模型
model_path = r"./modeldir" # 替换为你的模型路径
device = "cuda" # 指定推理设备为 GPU
torch_dtype = torch.float16
deepseek = DeepSeek(model_path, device, torch_dtype)
# 二:设定推理参数,推理消息
gen_kwargs = {
"max_length": 1024, # 生成的最大长度
"do_sample": True, # 是否使用概率采样
"top_k": 10, # 采样时的前 K 个候选词,越大越随机
"temperature": 0.7, # 生成丰富性,越大越有创造力
"top_p": 0.8, # 采样时的前 P 个候选词,越大越随机
"repetition_penalty": 1.2, # 重复惩罚系数,越大越不容易重复
}
messages = [
{"role": "system", "content": "你是一名乐于助人的人工智能助手"},
{"role": "user", "content": "请简要介绍一下你自己"},
] # 定义消息内容
response = deepseek.inference(messages, gen_kwargs) # 调用推理方法
# 初始化结果
result = ""
for chunk in response: # 流式输出生成的文本
result += chunk # 累加生成的文本
print(result) # 打印结果

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online