AI开发结构化输出
Ai结构化输出有三种实现方式:
- 利用大模型的JSON schema
- 利用Prompt+JSON Mode
- 利用Prompt
默认使用的是Prompt模式,强制大模型按用户提示词下写的包含特定字段的JSON文本。下面测试一下结构化输出,不过我们无需关心上面的开发模式,只需要修改方法的返回值,框架就可以自动帮我们实现结构化输出。
1.AiCodeService
在AiCodeService中添加两个方法,其中一个方法输出结构化的信息,record方法相当于定义了一个Report对象,其中里面有两个属性。
package com.example.aicode.ai;import dev.langchain4j.service.SystemMessage;
import dev.langchain4j.service.spring.AiService;import java.util.List;/*** @author zhou* @version 1.0* @description TODO* @date 2025/9/16 21:45*/
public interface AiCodeService {@SystemMessage(fromResource = "system-prompt.txt")String chat(String userMessage);@SystemMessage(fromResource = "system-prompt.txt")Report chatForReport(String userMessage);//学习报告record Report(String name, List<String> suggestionList){}
}
2.测试
testChatForReport()方法将以Report对象形式输出生成的内容。
package com.example.aicode.ai;import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class AiCodeServiceTest {@Resourceprivate AiCodeService aiCodeService;@Testvoid chat() {String chat = aiCodeService.chat("你好,我是一名程序员");System.out.println(chat);}@Testvoid testChatForReport() {String userMessage = "你好,我是一名程序员,学习一年半,请帮我制定一个学习报告";AiCodeService.Report report = aiCodeService.chatForReport(userMessage);System.out.println(report);}
}
3.输出结果