【LLM大模型】Spring AI 提示词模版源码分析及简单的使用

本篇文章主要对Spring AI 提示词的实现源码进行剖析,并提供使用案例。对于如何写好提示词,提示的技术框架等,后续会出专题进行详尽的讨论。

提示词重要性

众所周知,ChatGPT 使用得好不好,和你的提问有很大的关系,这个提问又叫提示词、指令或者是prompt。

研究人员可利用提示工程来提高大语言模型处理复杂任务场景的能力,如问答和算术推理能力。开发人员可通过提示工程设计和研发出强大的技术,实现和大语言模型或其他生态工具的高效接轨。

但是虽然提示词很重要,但是在某些场景下,我们不得不承认,提示词是无法解决问题,后面会有文章说明。 比如一个场景:大模型对外部数据依赖比较严重时,问答系统,知识库系统等,那么需要什么技术解决呢?

提示词模板类结构

image.png

PromptTemplateStringActions 顶层接口

java
复制代码
package org.springframework.ai.chat.prompt;

import java.util.Map;

public interface PromptTemplateStringActions {

    // 根据模版以及填充词 生成提示词
    String render();
    // 根据模版生成提示词,并提供填充占位符的model,如果已经存在则会覆盖之前设置的
    String render(Map<String, Object> model);

}

PromptTemplateActions 接口

PromptTemplateActionsPromptTemplateStringActions 的子类,提供了两个生成提示词的接口,与父接口唯一不同的是返回值的对象不同。

java
复制代码
package org.springframework.ai.chat.prompt;

import java.util.Map;

public interface PromptTemplateActions extends PromptTemplateStringActions {
    // 根据提示词模板和填充词 生成Prompt对象
    Prompt create();

    // 根据提示词模板和填充词,并提供额外的model map 生成Prompt对象
    Prompt create(Map<String, Object> model);
}

对于PromptTemplateStringActionsPromptTemplateActions 两个接口的设计看着有些冗余,目前还不知道作者这么设计的意图是什么?咱们继续看其实现类,里面的实现是否相同以及使用的场景是啥?

经过思考一番后,作者设计意图是遵循设计六大原则的 单一职责和接口隔离原则,其次是在使用上更为方便。

PromptTemplate 实现类

这里只有关键核心代码

java
复制代码
public class PromptTemplate implements PromptTemplateActions, PromptTemplateMessageActions {

    private ST st;

    protected String template;
    
    // 可以根据Resource和String两种类型方式创建一个PromptTemplate对象
    public PromptTemplate(Resource resource) {
       try (InputStream inputStream = resource.getInputStream()) {
          this.template = StreamUtils.copyToString(inputStream, Charset.defaultCharset());
       }
       catch (IOException ex) {
          throw new RuntimeException("Failed to read resource", ex);
       }
       try {
          this.st = new ST(this.template, '{', '}');
       }
       catch (Exception ex) {
          throw new IllegalArgumentException("The template string is not valid.", ex);
       }
    }

    public PromptTemplate(String template) {
       this.template = template;
       // If the template string is not valid, an exception will be thrown
       try {
          this.st = new ST(this.template, '{', '}');
       }
       catch (Exception ex) {
          throw new IllegalArgumentException("The template string is not valid.", ex);
       }
    }

    public PromptTemplate(String template, Map<String, Object> model) {
       this.template = template;
       // If the template string is not valid, an exception will be thrown
       try {
          this.st = new ST(this.template, '{', '}');
          for (Entry<String, Object> entry : model.entrySet()) {
             add(entry.getKey(), entry.getValue());
          }
       }
       catch (Exception ex) {
          throw new IllegalArgumentException("The template string is not valid.", ex);
       }
    }

    public PromptTemplate(Resource resource, Map<String, Object> model) {
       try (InputStream inputStream = resource.getInputStream()) {
          this.template = StreamUtils.copyToString(inputStream, Charset.defaultCharset());
       }
       catch (IOException ex) {
          throw new RuntimeException("Failed to read resource", ex);
       }
       // If the template string is not valid, an exception will be thrown
       try {
          this.st = new ST(this.template, '{', '}');
          for (Entry<String, Object> entry : model.entrySet()) {
             this.add(entry.getKey(), entry.getValue());
          }
       }
       catch (Exception ex) {
          throw new IllegalArgumentException("The template string is not valid.", ex);
       }
    }

    public void add(String name, Object value) {
       this.st.add(name, value);
       this.dynamicModel.put(name, value);
    }

    // ------------  以下实现接口方法 -----------
    // Render Methods
    @Override
    public String render() {
       // validate方法就校验传入的map方法,与提示词模版中的占位符是否一致,如果不一致则抛出异常
       // 由于篇幅将校验方法删除了,详细内容可以看源码。
       validate(this.dynamicModel);
       // 生成提示词
       return st.render();
    }

    @Override
    public String render(Map<String, Object> model) {
       validate(model);
       for (Entry<String, Object> entry : model.entrySet()) {
          // 如果model中的key已经存在,则从st的map中移除
          if (this.st.getAttribute(entry.getKey()) != null) {
             this.st.remove(entry.getKey());
          }
          if (entry.getValue() instanceof Resource) {
             this.st.add(entry.getKey(), renderResource((Resource) entry.getValue()));
          }
          else {
             this.st.add(entry.getKey(), entry.getValue());
          }

       }
       return this.st.render();
    }

    private String renderResource(Resource resource) {
       try {
          return resource.getContentAsString(Charset.defaultCharset());
       }
       catch (IOException e) {
          throw new RuntimeException(e);
       }
    }
    
    
    // 根据生成的提示词,返回一个用户消息
    @Override
    public Message createMessage() {
       return new UserMessage(render());
    }

     // 根据生成的提示词,返回一个用户消息
    @Override
    public Message createMessage(List<Media> mediaList) {
       return new UserMessage(render(), mediaList);
    }

    // 根据生成的提示词,返回一个用户消息
    @Override
    public Message createMessage(Map<String, Object> model) {
       return new UserMessage(render(model));
    }
    // 根据提示词,返回一个提示词对象
    @Override
    public Prompt create() {
       return new Prompt(render(new HashMap<>()));
    }
    // 根据提示词,返回一个提示词对象
    @Override
    public Prompt create(Map<String, Object> model) {
       return new Prompt(render(model));
    }

}

实现类的实现是比较简单的,其魔法在于使用了 org.stringtemplate.v4.ST 模版解析,如果大家想深入了解其实现原理可以查看官网文档或者Github

Github:github.com/antlr/strin…

另外像Java还有类似的Freemark、Velocity等模版引擎,那么ST具有什么优势和其适应场景呢?在这里只是引出一个话题,大家可以根据自身情况进行学习。

PrompteTemplate三个子类

image.png 源码实现很简单,这里就不再贴代码了,简单介绍一下其作用;

  • AssistantPromptTemplate:创建大模型回复提示词对象
  • FunctionPromptTemplate:创建函数调用提示词对象
  • SystemPromptTemplate:创建系统提示词对象

ChatPromptTemplate 实现与上面介绍的基本上相似,不再做分析。

提示词模板使用示例

第一个案例

当我们输入导演名称,查询导演的最受欢迎的电影是什么?哪年发行的,电影讲述的什么内容?

提示词模版 film.st

请问{director}导演最受欢迎的电影是什么?哪年发行的,电影讲述的什么内容?

代码实现

java
复制代码
package com.ivy.controller;

import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class PromptTemplateController {

    @Resource
    private OpenAiChatModel openAiChatModel;


    @Value("classpath:film.st")
    private org.springframework.core.io.Resource template;

    @GetMapping("/prompt")
    public String prompt(String director) {

        Map<String, Object> map = Map.of("director", director);
        PromptTemplate promptTemplate = new PromptTemplate(template, map);
        Prompt prompt = promptTemplate.create();

        ChatClient chatClient = ChatClient.builder(openAiChatModel)
                .build();
        return chatClient.prompt(prompt).call().content();
    }
}

使用Postman验证

image.png

第二个小案例

当我们输入编程语言、描述、方法名称,生成一个方法

提示词模版设计 code.st

java
复制代码
/**
  * @language {language}
  * @method {methodName}
  * @describe {description}
  */

代码实现

java
复制代码
package com.ivy.controller;

import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class PromptTemplateController {

    @Resource
    private OpenAiChatModel openAiChatModel;
    
    @Value("classpath:code.st")
    private org.springframework.core.io.Resource codeTemplate;

    @GetMapping("/code")
    public String code(String language, String methodName, String description) {
        PromptTemplate promptTemplate = new PromptTemplate(codeTemplate);
        Prompt prompt = promptTemplate.create(
                Map.of("language", language, "methodName", methodName, "description", description)
        );
        ChatClient chatClient = ChatClient.builder(openAiChatModel)
                .build();
        return chatClient.prompt(prompt).call().content();
    }
}

Postman验证

当输入language=java&methodName=quickSort&description=写一个快速排序算法 时 image.png

当输入language=python&methodName=quickSort&description=写一个快速排序算法 时

image.png

代码示例

github.com/fangjieDevp…

总结

本篇文章主要对Spring AI 框架的提示词模板设计进行源码分析,目前看设计上还是比较简单,底层使用了org.stringtemplate.v4.ST框架实现。然后提供了两个小示例来演示使用。比如第一个小示例,相当于提问三个方面的问题,大家有没有什么想法,将这三个方面的内容组成一个Film对象格式化返回呢?Spring AI框架已经提供了这方面的支持,请看后续文章。

对于提示词工程相关的技术也会出一些系列文章,对提示词技术进行讲解与实践,敬请期待!!

如何系统的去学习大模型LLM ?

作为一名热心肠的互联网老兵,我意识到有很多经验和知识值得分享给大家,也可以通过我们的能力和经验解答大家在人工智能学习中的很多困惑,所以在工作繁忙的情况下还是坚持各种整理和分享。

但苦于知识传播途径有限,很多互联网行业朋友无法获得正确的资料得到学习提升,故此将并将重要的 AI大模型资料 包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来

所有资料 ⚡️ ,朋友们如果有需要全套 《LLM大模型入门+进阶学习资源包》,扫码获取~

👉CSDN大礼包🎁:全网最全《LLM大模型入门+进阶学习资源包》免费分享(安全链接,放心点击)👈

一、全套AGI大模型学习路线

AI大模型时代的学习之旅:从基础到前沿,掌握人工智能的核心技能!

img

二、640套AI大模型报告合集

这套包含640份报告的合集,涵盖了AI大模型的理论研究、技术实现、行业应用等多个方面。无论您是科研人员、工程师,还是对AI大模型感兴趣的爱好者,这套报告合集都将为您提供宝贵的信息和启示。

img

三、AI大模型经典PDF籍

随着人工智能技术的飞速发展,AI大模型已经成为了当今科技领域的一大热点。这些大型预训练模型,如GPT-3、BERT、XLNet等,以其强大的语言理解和生成能力,正在改变我们对人工智能的认识。 那以下这些PDF籍就是非常不错的学习资源。

img

在这里插入图片描述

四、AI大模型商业化落地方案

img

阶段1:AI大模型时代的基础理解

  • 目标:了解AI大模型的基本概念、发展历程和核心原理。
  • 内容
    • L1.1 人工智能简述与大模型起源
    • L1.2 大模型与通用人工智能
    • L1.3 GPT模型的发展历程
    • L1.4 模型工程
      - L1.4.1 知识大模型
      - L1.4.2 生产大模型
      - L1.4.3 模型工程方法论
      - L1.4.4 模型工程实践
    • L1.5 GPT应用案例

阶段2:AI大模型API应用开发工程

  • 目标:掌握AI大模型API的使用和开发,以及相关的编程技能。
  • 内容
    • L2.1 API接口
      - L2.1.1 OpenAI API接口
      - L2.1.2 Python接口接入
      - L2.1.3 BOT工具类框架
      - L2.1.4 代码示例
    • L2.2 Prompt框架
      - L2.2.1 什么是Prompt
      - L2.2.2 Prompt框架应用现状
      - L2.2.3 基于GPTAS的Prompt框架
      - L2.2.4 Prompt框架与Thought
      - L2.2.5 Prompt框架与提示词
    • L2.3 流水线工程
      - L2.3.1 流水线工程的概念
      - L2.3.2 流水线工程的优点
      - L2.3.3 流水线工程的应用
    • L2.4 总结与展望

阶段3:AI大模型应用架构实践

  • 目标:深入理解AI大模型的应用架构,并能够进行私有化部署。
  • 内容
    • L3.1 Agent模型框架
      - L3.1.1 Agent模型框架的设计理念
      - L3.1.2 Agent模型框架的核心组件
      - L3.1.3 Agent模型框架的实现细节
    • L3.2 MetaGPT
      - L3.2.1 MetaGPT的基本概念
      - L3.2.2 MetaGPT的工作原理
      - L3.2.3 MetaGPT的应用场景
    • L3.3 ChatGLM
      - L3.3.1 ChatGLM的特点
      - L3.3.2 ChatGLM的开发环境
      - L3.3.3 ChatGLM的使用示例
    • L3.4 LLAMA
      - L3.4.1 LLAMA的特点
      - L3.4.2 LLAMA的开发环境
      - L3.4.3 LLAMA的使用示例
    • L3.5 其他大模型介绍

阶段4:AI大模型私有化部署

  • 目标:掌握多种AI大模型的私有化部署,包括多模态和特定领域模型。
  • 内容
    • L4.1 模型私有化部署概述
    • L4.2 模型私有化部署的关键技术
    • L4.3 模型私有化部署的实施步骤
    • L4.4 模型私有化部署的应用场景

学习计划:

  • 阶段1:1-2个月,建立AI大模型的基础知识体系。
  • 阶段2:2-3个月,专注于API应用开发能力的提升。
  • 阶段3:3-4个月,深入实践AI大模型的应用架构和私有化部署。
  • 阶段4:4-5个月,专注于高级模型的应用和部署。
这份完整版的所有 ⚡️ 大模型 LLM 学习资料已经上传CSDN,朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费

全套 《LLM大模型入门+进阶学习资源包↓↓↓ 获取~

👉CSDN大礼包🎁:全网最全《LLM大模型入门+进阶学习资源包》免费分享(安全链接,放心点击)👈

  • 21
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值