用 Python + LLM 实现一个智能对话

大型语言模型LLM最近比较火,所以我也来用LLM写个智能对话玩玩。

简介

大语言模型LLM全称是Large Language Models。LLM是指具有巨大参数量和极高语言理解能力的神经网络模型。这些模型被训练来理解和生成自然语言文本,能够执行多种自然语言处理(NLP)任务,如文本生成、翻译、摘要、问答等。 所以LLM可以做以下事情:

  • 文本生成:LLM可以生成各种类型的文本,如新闻、文章、小说等。
  • 智能对话系统:LLM可以用于构建智能对话系统,能够理解用户输入并生成合理的回复。
  • 信息检索和摘要:LLM可以帮助搜索引擎生成更准确的搜索结果摘要。
  • 语言翻译:LLM可以将一种语言翻译成另一种语言。
  • 语言理解和分析:LLM可以用于解析和理解自然语言文本,提取其中的信息和意义。

安装依赖

主要是安装transformers和torch

bash 复制代码
pip install transformers
bash 复制代码
pip install torch

加载模型和分词器

python 复制代码
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
model = GPT2LMHeadModel.from_pretrained("gpt2")

实现对话逻辑

python 复制代码
def chat(prompt, max_length=200):
    # 将输入文本编码成模型可识别的tokens
    input_ids = tokenizer.encode(prompt, return_tensors="pt")
    # 生成对话
    response_ids = model.generate(input_ids, max_length=max_length, num_return_sequences=1, temperature=0.9)
    # 解码tokens成文本字符串
    response_text = tokenizer.decode(response_ids[0], skip_special_tokens=True)
    return response_text

调用聊天函数

这里是循环聊天

python 复制代码
while True:
    user_input = input("You:")
    if user_input.lower() == "exit":
        print("Goodbye!")
        break
    response = chat(user_input)
    print("Bot:", response)

完整代码

python 复制代码
from transformers import GPT2LMHeadModel, GPT2Tokenizer

# 加载预训练的GPT-2模型和分词器
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
model = GPT2LMHeadModel.from_pretrained("gpt2")

def chat(prompt, max_length=200):
    # 将输入文本编码成模型可识别的tokens
    input_ids = tokenizer.encode(prompt, return_tensors="pt")

    # 生成对话response
    response_ids = model.generate(input_ids, max_length=max_length, num_return_sequences=1, temperature=0.9)

    # 解码response tokens成文本
    response_text = tokenizer.decode(response_ids[0], skip_special_tokens=True)
    return response_text

# 进入对话循环
while True:
    user_input = input("You:")
    if user_input.lower() == "exit":
        print("Goodbye!")
        break
    response = chat(user_input)
    print("Bot:", response)

目前模型训练还不够智能,所以对话稍显逊色。

之后实现有前端界面的,之后再更新文章。

未完待续。。。

相关推荐
aweiname2008几秒前
安装 Nunchaku
人工智能·深度学习·ai生视频
格林威2 分钟前
Windows 实时性补丁(RTX / WSL2)
linux·运维·人工智能·windows·数码相机·计算机视觉·工业相机
DeepModel2 分钟前
通俗易懂讲透随机梯度下降法(SGD)
人工智能·python·算法·机器学习
yuhulkjv3358 分钟前
ChatGPT Gemini Claude Grok导出的Excel公式失效
人工智能·ai·chatgpt·excel·豆包·deepseek·ai导出鸭
AI服务老曹8 分钟前
异构计算时代的安防底座:基于 x86/ARM 双架构与多芯片适配的 AI 视频云平台架构解析
arm开发·人工智能·架构
人工智能AI技术9 分钟前
Spring Boot AI接入观测云MCP最佳实践
人工智能
海兰10 分钟前
【第1篇 】生成式AI的崛起:从语言模型到智能体
人工智能·语言模型·自然语言处理
TK云大师-KK11 分钟前
2026年4月TikTok矩阵运营系统横向评测TOP5
大数据·网络·人工智能·矩阵·自动化·新媒体运营
sun_tao113 分钟前
Prompt工程实践
人工智能·llm·prompt·agent
ofoxcoding13 分钟前
Claude 做 AI Agent 实战教程:从零搭建一个能自主执行任务的智能体(2026)
人工智能·ai