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

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

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

未完待续。。。

相关推荐
云境筑桃源哇23 分钟前
海洋ALFA:主权与创新的交响,开启AI生态新纪元
人工智能
liliangcsdn35 分钟前
LLM复杂数值的提取计算场景示例
人工智能·python
小和尚同志41 分钟前
OpenCodeUI 让你随时随地 AI Coding
人工智能·aigc·ai编程
AI视觉网奇1 小时前
2d 数字人解决方案-待机动作
人工智能·计算机视觉
人工智能AI酱1 小时前
【AI深究】逻辑回归(Logistic Regression)全网最详细全流程详解与案例(附大量Python代码演示)| 数学原理、案例流程、代码演示及结果解读 | 决策边界、正则化、优缺点及工程建议
人工智能·python·算法·机器学习·ai·逻辑回归·正则化
爱喝可乐的老王1 小时前
机器学习监督学习模型--逻辑回归
人工智能·机器学习·逻辑回归
Ao0000001 小时前
机器学习——逻辑回归
人工智能·机器学习·逻辑回归
智算菩萨1 小时前
【How Far Are We From AGI】3 AGI的边界扩张——数字、物理与智能三重接口的技术实现与伦理困境
论文阅读·人工智能·深度学习·ai·agi
智算菩萨1 小时前
【How Far Are We From AGI】2 大模型的“灵魂“缺口:当感知、记忆与自我意识的迷雾尚未散去
人工智能·ai·agi·感知
deepxuan2 小时前
Day1--python三大库-Pandas
人工智能·python·pandas