一起学大模型 - 一起动笔练习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的理解

相关推荐
Swizard5 天前
逐行解剖:扒开 Lovable Agent 源码,看顶级 AI 是如何“思考”与“动刀”的
ai·prompt
杜子不疼.6 天前
大模型应用开发实战:从 Prompt 工程到企业级落地全流程
prompt
觅特科技-互站6 天前
告别手动微调Prompt:DevOps用陌讯Skills重构AI运维工作流
运维·prompt·线性回归·kmeans·devops
小马_xiaoen6 天前
AI Prompt 工程完全指南:从入门到精通的提示词设计艺术
人工智能·prompt
Swizard7 天前
还在无脑堆砌提示词?三分钟看懂 Vercel v0 价值千万的 System Prompt 底层逻辑
ai·prompt
Loo国昌7 天前
【AI应用开发实战】Guardrail风险控制中间件:Agent系统的安全防线
人工智能·python·安全·自然语言处理·中间件·prompt
啦啦啦_99997 天前
SpringAI Alibaba(SAA) 之 Prompt
prompt
AC赳赳老秦7 天前
DeepSeek助力云原生AI降本:容器化部署资源优化与算力利用率提升技巧
网络·python·django·prompt·tornado·ai-native·deepseek
Loo国昌8 天前
【AI应用开发实战】09_Prompt工程与模板管理:构建可演进的LLM交互层
大数据·人工智能·后端·python·自然语言处理·prompt
minhuan8 天前
大模型应用:遗传算法 (GA)+大模型:自动化进化最优Prompt与模型参数.95
prompt·大模型应用·遗传算法 ga·prompt自动调优