SpringAI整合OpenAI系列(二)
一、提示词(Prompt)
Prompt:引导 AI 模型生成特定输出的输入格式,Prompt 的设计和措辞会显著影响模型的响应,讲点人话就是:你和AI对话的内容。 Prompt在最初只是简单的内容的问答,随着模型不断的完整和发展OpenAI总结了6种比较好的策略,被称之为Prompt engineering分别是:
-
Write clear instructions: 清晰的表达
-
Provide reference text: 相应参考格式
-
Split complex tasks into simpler subtasks: 拆解问题
-
Give the model time to "think"
-
Use external tools
-
Test changes systematically
清晰的问答策略,能够使得模型更容易理解你的需求,从而保证程序运行的稳定。所以在设计问题的时候,尽量遵循这些原则,使得大模型能够提供符合需求的答案。

二、Structured Outputs结构化输出
在程序设计中,非结构化的数据,我们很难对数据进行解析和处理,标准的结构化内容的输出,可以便于系统集成,所以我们需要利用SpringAI中的结构化输出的能力,集成对大模型的调用。

三、代码实现
按照以上两个概念,我们来具体实现我们的功能,需求是这样的,我需要对大模型对话,要求返回结构化的数据。
Spring AI中将数据结构化输出的实现类
org.springframework.ai.converter.BeanOutputConverter
你会发现这个convert方法的主要目的将你需要返回的数据结构,告诉大模型,然后大模型返回了一个可序列化的一个对象。

接下来,我们根据这个原理来实现功能。主要的思路是参考 BeanOutputConverter,改写成我们自己的对象。由于我们定义的字段很多时候没有严格遵循英文命名规范,因此在字段类名上,我们应该加入一些注释或说明,以便将提问请求转化为封装好的提示词,最终返回相应的数据结构。
/**
* 这个是结构化输出的封装类
* @param <T>
*/
public class DataBeanOutputConverter<T> implements StructuredOutputConverter<T> {
private final Logger logger;
private final Type type;
private final ObjectMapper objectMapper;
private String jsonSchema;
public DataBeanOutputConverter(Class<T> clazz) {
this(ParameterizedTypeReference.forType(clazz));
}
public DataBeanOutputConverter(Class<T> clazz, ObjectMapper objectMapper) {
this(ParameterizedTypeReference.forType(clazz), objectMapper);
}
public DataBeanOutputConverter(ParameterizedTypeReference<T> typeRef) {
this((Type)typeRef.getType(), (ObjectMapper)null);
}
public DataBeanOutputConverter(ParameterizedTypeReference<T> typeRef, ObjectMapper objectMapper) {
this(typeRef.getType(), objectMapper);
}
private DataBeanOutputConverter(Type type, ObjectMapper objectMapper) {
this.logger = LoggerFactory.getLogger(BeanOutputConverter.class);
Objects.requireNonNull(type, "Type cannot be null;");
this.type = type;
this.objectMapper = objectMapper != null ? objectMapper : this.getObjectMapper();
this.generateSchema();
}
private void generateSchema() {
&nb

最低0.47元/天 解锁文章
7153

被折叠的 条评论
为什么被折叠?



