一起学大模型 - 一起动笔练习prompt的用法

文章目录

  • 前言
  • 一、代码演示
  • 二、代码解析
    • [1. 导入所需的库和模块:](#1. 导入所需的库和模块:)
    • [2. 设置日志记录和初始化模型:](#2. 设置日志记录和初始化模型:)
    • [3. 定义一个函数用于清理GPU内存:](#3. 定义一个函数用于清理GPU内存:)
    • [4. 定义一个继承自LLM基类的QianWenChatLLM类,并实现对话生成的逻辑:](#4. 定义一个继承自LLM基类的QianWenChatLLM类,并实现对话生成的逻辑:)
    • [5. 示例代码的主体部分:](#5. 示例代码的主体部分:)
  • 三、运行结果
  • 总结

前言

在之前的文章里面我们学习了Langchain的prompt接口的知识,光学习是不够的。

让我们一起练习一下Langchain prompt的用法,并更加合理地组织它。prompt的组织方法没有特定的规范,可以使用不同的前缀来标注用户、AI、历史记录或已知信息,这是可变的。只要格式明确,大模型就可以正确识别。


一、代码演示

python 复制代码
import os
import torch
from typing import List, Optional

from langchain.chains import LLMChain
from langchain.llms.base import LLM
from langchain_core.prompts import HumanMessagePromptTemplate, ChatPromptTemplate
from modelscope import AutoModelForCausalLM, AutoTokenizer
from modelscope import GenerationConfig
import logging
import torch

from configs import log_verbose

logger = logging.getLogger(__name__)

tokenizer = AutoTokenizer.from_pretrained("I:/aimodels/Qwen/Qwen-1_8B-Chat", trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained("I:/aimodels/Qwen/Qwen-1_8B-Chat", device_map="cuda", trust_remote_code=True).eval()
model.generation_config = GenerationConfig.from_pretrained("I:/aimodels/Qwen/Qwen-1_8B-Chat", trust_remote_code=True)


def torch_gc():
    try:
        if torch.cuda.is_available():
            # with torch.cuda.device(DEVICE):
            torch.cuda.empty_cache()
            torch.cuda.ipc_collect()
        elif torch.backends.mps.is_available():
            try:
                from torch.mps import empty_cache
                empty_cache()
            except Exception as e:
                msg = ("如果您使用的是 macOS 建议将 pytorch 版本升级至 2.0.0 或更高版本,"
                       "以支持及时清理 torch 产生的内存占用。")
                logger.error(f'{e.__class__.__name__}: {msg}',
                             exc_info=e if log_verbose else None)
    except Exception:
        ...


# wrap the qwen model with langchain LLM base class
class QianWenChatLLM(LLM):
    max_length = 10000
    temperature: float = 0.01
    top_p = 0.9

    def __init__(self):
        super().__init__()

    @property
    def _llm_type(self):
        return "ChatLLM"

    def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
        print(prompt)
        response, history = model.chat(tokenizer, prompt, history=None)
        torch_gc()
        return response


if __name__ == '__main__':
    qwllm = QianWenChatLLM()
    print('@@@ qianwen LLM created')

    # 使用qwllm对话

    qwllm.temperature = 0.01
    qwllm.top_p = 0.9
    qwllm.max_length = 10000



    human_prompt = "{input}"
    human_message_template = HumanMessagePromptTemplate.from_template(human_prompt)

    chat_prompt = ChatPromptTemplate.from_messages(
        [("human", "我们来玩成语接龙,我先来,生龙活虎"),
         ("ai", "虎头虎脑"),
         ("human", "{input}")])

    chain = LLMChain(prompt=chat_prompt, llm=qwllm, verbose=True)
    print(chain({"input": "恼羞成怒"}))

    chat_prompt2 = ChatPromptTemplate.from_messages(
        ['<指令>这里是我通过工具获取的当前信息。请你根据这些信息进行提取并有调理,简洁的回答问题。如果无法从中得到答案,请说 "根据已知信息无法回答该问题",答案请使用中文。 </指令>\n'
        '<已知信息>{context}</已知信息>\n'
        '<问题>{question}</问题>\n']
    )

    # 取当前时间,格式是年月日时分秒
    import datetime
    now = datetime.datetime.now()
    now_time = now.strftime("%Y-%m-%d %H:%M:%S")

    chain2 = LLMChain(prompt=chat_prompt2, llm=qwllm, verbose=True)
    print(chain2({"context": "当前的时间是" + now_time, "question": "请问现在几点了?"}))

二、代码解析

这段代码主要是使用了一个名为"Qwen"的预训练语言模型进行对话生成。以下是代码的解释:

1. 导入所需的库和模块:

python 复制代码
import os
import torch
from typing import List, Optional
from langchain.chains import LLMChain
from langchain.llms.base import LLM
from langchain_core.prompts import HumanMessagePromptTemplate, ChatPromptTemplate
from modelscope import AutoModelForCausalLM, AutoTokenizer
from modelscope import GenerationConfig
import logging
import torch
from configs import log_verbose

2. 设置日志记录和初始化模型:

python 复制代码
logger = logging.getLogger(__name__)
# 使用预训练模型的tokenizer和model
tokenizer = AutoTokenizer.from_pretrained("I:/aimodels/Qwen/Qwen-1_8B-Chat", trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained("I:/aimodels/Qwen/Qwen-1_8B-Chat", device_map="cuda", trust_remote_code=True).eval()
model.generation_config = GenerationConfig.from_pretrained("I:/aimodels/Qwen/Qwen-1_8B-Chat", trust_remote_code=True)

3. 定义一个函数用于清理GPU内存:

python 复制代码
def torch_gc():
    try:
        if torch.cuda.is_available():
            torch.cuda.empty_cache()
            torch.cuda.ipc_collect()
        elif torch.backends.mps.is_available():
            try:
                from torch.mps import empty_cache
                empty_cache()
            except Exception as e:
                msg = "如果您使用的是 macOS 建议将 pytorch 版本升级至 2.0.0 或更高版本,以支持及时清理 torch 产生的内存占用。"
                logger.error(f'{e.__class__.__name__}: {msg}', exc_info=e if log_verbose else None)
    except Exception:
        ...

4. 定义一个继承自LLM基类的QianWenChatLLM类,并实现对话生成的逻辑:

python 复制代码
class QianWenChatLLM(LLM):
    max_length = 10000
    temperature: float = 0.01
    top_p = 0.9

    def __init__(self):
        super().__init__()

    @property
    def _llm_type(self):
        return "ChatLLM"

    def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
        print(prompt)
        response, history = model.chat(tokenizer, prompt, history=None)
        torch_gc()
        return response

5. 示例代码的主体部分:

python 复制代码
if __name__ == '__main__':
    qwllm = QianWenChatLLM()
    print('@@@ qianwen LLM created')

    # 使用qwllm对话

    qwllm.temperature = 0.01
    qwllm.top_p = 0.9
    qwllm.max_length = 10000

    human_prompt = "{input}"
    human_message_template = HumanMessagePromptTemplate.from_template(human_prompt)

    chat_prompt = ChatPromptTemplate.from_messages(
        [("human", "我们来玩成语接龙,我先来,生龙活虎"),
         ("ai", "虎头虎脑"),
         ("human", "{input}")])

    chain = LLMChain(prompt=chat_prompt, llm=qwllm, verbose=True)
    print(chain({"input": "恼羞成怒"}))

    chat_prompt2 = ChatPromptTemplate.from_messages(
        ['<指令>这里是我通过工具获取的当前信息。请你根据这些信息进行提取并有调理,简洁的回答问题。如果无法从中得到答案,请说 "根据已知信息无法回答该问题",答案请使用中文。 </指令>\n'
        '<已知信息>{context}</已知信息>\n'
        '<问题>{question}</问题>\n']
    )

    # 取当前时间,格式是年月日时分秒
    import datetime
    now = datetime.datetime.now()
    now_time = now.strftime("%Y-%m-%d %H:%M:%S")

    chain2 = LLMChain(prompt=chat_prompt2, llm=qwllm, verbose=True)
    print(chain2({"context": "当前的时间是" + now_time, "question": "请问现在几点了?"}))

在主体部分,首先创建了一个QianWenChatLLM的实例qwllm,并设置了生成对话时的参数。接下来定义了两个对话的模板prompt,用于生成聊天对话。然后创建了LLMChain实例chain,将prompt和qwllm传入,最后调用chain生成对话并打印结果。

代码的最后部分,又创建了一个LLMChain实例chain2,其中的prompt包含了当前的时间信息,然后调用chain2生成对话并打印结果。


三、运行结果

总结

在上面的代码,我们可以看出Langchain的prompt对文本组织结构和角色的分配是很灵活。但是并不代表就可以随便写。不同的写法出来的结果是不一样的。 在实际的运用中也需要不断的调优,达到更好的效果。

大家可以一起练习一下,并在练习的过程中排查各种问题,提升自己对prompt的理解

相关推荐
是二狗诶1 天前
提取ChatGPT默认prompt提示词bug
chatgpt·prompt
东皇太一在此2 天前
Prompt Engineering
prompt
风雨中的小七2 天前
解密Prompt系列33. LLM之图表理解任务-多模态篇
prompt
会python的小孩3 天前
有哪些好的 Stable Diffusion 提示词(Prompt)可以参考?
人工智能·windows·tcp/ip·ai作画·stable diffusion·prompt
大耳朵爱学习3 天前
周鸿祎:大模型不是风口和泡沫,将引领新工业革命
人工智能·机器学习·语言模型·自然语言处理·prompt·职场发展
AI小白龙*4 天前
开源模型破局OpenAI服务限制,15分钟灵活搭建RAG和Agent应用
llm·prompt·embedding·agent·ai大模型·rag·大模型部署
猫头虎4 天前
最新榜单出炉!2024年6月AI行业微信公众号排行榜
人工智能·科技·微信·chatgpt·prompt·aigc·ai-native
木乐乐数据5 天前
用 AI 生成绘本,含大量 prompt
prompt
猫头虎5 天前
猫头虎分享[可灵AI」官方推荐的驯服指南-V1.0
人工智能·stable diffusion·prompt·aigc·ai编程·ai写作·ai-native
AI小白龙*6 天前
LLM大模型实战 —— DB-GPT阿里云部署指南
阿里云·大模型·llm·prompt·embedding·ai大模型·大模型部署