个人随笔
目录
SpringAI2.0结构化输出的简单使用
2026-11-03 21:12:27

大型语言模型是“输入文本、输出文本”的系统。一旦下游代码需要根据某个字段进行路由、持久化某个值,或基于结果做出分支决策,这些文本就必须被转换为具有明确类型的记录。结构化输出正是弥合这一鸿沟的手段:模型被引导生成符合特定模式的文本,而应用程序则将其解析回类型化的对象,以便代码库中的其他部分能够像处理任何其他领域类型一样对其进行操作。

Spring AI 直接在上公开结构化输出ChatClient流畅的 API 通过.entity(…​)您可以为希望返回的形状定义一个 Java 类型,Spring AI 会负责其余工作:系统会根据您的类型生成 JSON 模式,模型会被指示遵循该模式,并且响应会被反序列化为您的类型。

一、简单例子

1、输出普通单个对象

先定义个record

  1. public record Topic(
  2. String topic,//问题
  3. List<String> infos//响应信息
  4. ) {}

用.entity设置

  1. @GetMapping("/ask3")
  2. public Topic ask3(String topic){
  3. Topic result = openaiChatClient
  4. .prompt()
  5. .system("您是一位资深系统架构师") //系统 提示词 ,这里如果设置了会覆盖创建chatClient那里设置的系统提示词
  6. .user(u -> u.text("请介绍一下{topic}的三个优点").param("topic",topic))
  7. .call()
  8. .entity(Topic.class);
  9. return result;
  10. }

请求可以看到 结果

  1. {"topic":"PHP的三个优点","infos":["语法简单且上手快,适合快速开发Web应用","与HTML集成方便,模板开发效率高","生态成熟且部署成本低,拥有丰富的框架和开源资源"]}

我们也可以看下大模型输入输出

  1. request: ChatClientRequest[prompt=Prompt{messages=[SystemMessage{textContent='您是一位资深系统架构师', messageType=SYSTEM, metadata={messageType=SYSTEM}}, UserMessage{content='请介绍一下php的三个优点', metadata={messageType=USER}, messageType=USER}], modelOptions=org.springframework.ai.openai.OpenAiChatOptions@51fa12f0}, context={spring.ai.chat.client.output.format=Your response should be in JSON format.
  2. Do not include any explanations, only provide a RFC8259 compliant JSON response following this format without deviation.
  3. Do not include markdown code blocks in your response.
  4. Remove the ```json markdown from the output.
  5. Here is the JSON Schema instance your output must adhere to:
  6. ```{
  7. "$schema" : "https://json-schema.org/draft/2020-12/schema",
  8. "type" : "object",
  9. "properties" : {
  10. "infos" : {
  11. "type" : "array",
  12. "items" : {
  13. "type" : "string"
  14. }
  15. },
  16. "topic" : {
  17. "type" : "string"
  18. }
  19. },
  20. "required" : [ "infos", "topic" ],
  21. "additionalProperties" : false
  22. }
  23. }]

可以看到是我们的提示词要求大模型返回固定的json格式的字符串

  1. response: {
  2. "metadata" : {
  3. "empty" : false,
  4. "id" : "chatcmpl-8b06354f-89b9-9e8f-b70f-57c396fda6f2",
  5. "model" : "qwen3.8-flash",
  6. "promptMetadata" : [ ],
  7. "rateLimit" : {
  8. "requestsLimit" : 0,
  9. "requestsRemaining" : 0,
  10. "requestsReset" : "PT0S",
  11. "tokensLimit" : 0,
  12. "tokensRemaining" : 0,
  13. "tokensReset" : "PT0S"
  14. },
  15. "usage" : {
  16. "promptTokens" : 259,
  17. "completionTokens" : 135,
  18. "totalTokens" : 394,
  19. "cacheReadInputTokens" : 0,
  20. "nativeUsage" : {
  21. "completion_tokens" : 135,
  22. "prompt_tokens" : 259,
  23. "total_tokens" : 394,
  24. "completion_tokens_details" : {
  25. "reasoning_tokens" : 68,
  26. "valid" : true,
  27. "text_tokens" : 135
  28. },
  29. "prompt_tokens_details" : {
  30. "cached_tokens" : 0,
  31. "valid" : true,
  32. "text_tokens" : 259
  33. },
  34. "valid" : true
  35. }
  36. }
  37. },
  38. "result" : {
  39. "metadata" : {
  40. "contentFilters" : [ ],
  41. "empty" : true,
  42. "finishReason" : "STOP"
  43. },
  44. "output" : {
  45. "media" : [ ],
  46. "messageType" : "ASSISTANT",
  47. "metadata" : {
  48. "role" : "assistant",
  49. "messageType" : "ASSISTANT",
  50. "finishReason" : "STOP",
  51. "refusal" : "",
  52. "annotations" : [ { } ],
  53. "index" : 0,
  54. "id" : "chatcmpl-8b06354f-89b9-9e8f-b70f-57c396fda6f2",
  55. "reasoningContent" : "我们需要回答用户:请介绍一下php的三个优点。要求 JSON 格式,RFC8259,不能 markdown,必须符合 schema:对象含 infos 字符串数组和 topic 字符串,additionalProperties false。必须只输出 JSON。需要中文内容。三个优点。确保无解释。工具已调用满足要求。最终只 JSON。"
  56. },
  57. "text" : "{\n \"topic\": \"PHP的三个优点\",\n \"infos\": [\n \"语法简单且上手快,适合快速开发Web应用\",\n \"与HTML集成方便,模板开发效率高\",\n \"生态成熟且部署成本低,拥有丰富的框架和开源资源\"\n ]\n}",
  58. "toolCalls" : [ ]
  59. }
  60. },
  61. "results" : [ {
  62. "metadata" : {
  63. "contentFilters" : [ ],
  64. "empty" : true,
  65. "finishReason" : "STOP"
  66. },
  67. "output" : {
  68. "media" : [ ],
  69. "messageType" : "ASSISTANT",
  70. "metadata" : {
  71. "role" : "assistant",
  72. "messageType" : "ASSISTANT",
  73. "finishReason" : "STOP",
  74. "refusal" : "",
  75. "annotations" : [ { } ],
  76. "index" : 0,
  77. "id" : "chatcmpl-8b06354f-89b9-9e8f-b70f-57c396fda6f2",
  78. "reasoningContent" : "我们需要回答用户:请介绍一下php的三个优点。要求 JSON 格式,RFC8259,不能 markdown,必须符合 schema:对象含 infos 字符串数组和 topic 字符串,additionalProperties false。必须只输出 JSON。需要中文内容。三个优点。确保无解释。工具已调用满足要求。最终只 JSON。"
  79. },
  80. "text" : "{\n \"topic\": \"PHP的三个优点\",\n \"infos\": [\n \"语法简单且上手快,适合快速开发Web应用\",\n \"与HTML集成方便,模板开发效率高\",\n \"生态成熟且部署成本低,拥有丰富的框架和开源资源\"\n ]\n}",
  81. "toolCalls" : [ ]
  82. }
  83. } ]
  84. }

2、输出List结果

先定义pojo

  1. public class Book {
  2. @JsonPropertyDescription("作者名称")
  3. private String a;
  4. @JsonPropertyDescription("书本名称")
  5. private String b;
  6. public String getA() {
  7. return a;
  8. }
  9. public void setA(String a) {
  10. this.a = a;
  11. }
  12. public String getB() {
  13. return b;
  14. }
  15. public void setB(String b) {
  16. this.b = b;
  17. }
  18. @Override
  19. public String toString() {
  20. return "Book{" +
  21. "a='" + a + '\'' +
  22. ", b='" + b + '\'' +
  23. '}';
  24. }
  25. }

记得最好用@JsonPropertyDescription标注这个字段是干什么的,这样给大模型的提示词也会加上这个

  1. "items" : {
  2. "type" : "object",
  3. "properties" : {
  4. "a" : {
  5. "type" : "string",
  6. "description" : "作者名称"
  7. },
  8. "b" : {
  9. "type" : "string",
  10. "description" : "书本名称"
  11. }
  12. },

如果不定义可能大模型理解不了就会出错。

请求

  1. @GetMapping("/ask4")
  2. public List<Book> ask4(String topic){
  3. List<Book> result = openaiChatClient
  4. .prompt()
  5. .system("您是一位资深书本推荐家") //系统 提示词 ,这里如果设置了会覆盖创建chatClient那里设置的系统提示词
  6. .user(u -> u.text("请推荐关于{topic}类型的三本书").param("topic",topic))
  7. .call()
  8. .entity(new ParameterizedTypeReference<List<Book>>() {});
  9. return result;
  10. }

结果

  1. [{"a":"辰东","b":"遮天"},{"a":"唐家三少","b":"斗罗大陆"},{"a":"天蚕土豆","b":"斗破苍穹"}]

看看LLM输出

  1. "finishReason" : "STOP",
  2. "index" : 0,
  3. "annotations" : [ { } ],
  4. "id" : "chatcmpl-7fb3afd2-75c0-9cab-a910-a6b5023899fa",
  5. "reasoningContent" : "我们需要回答用户:请推荐关于玄幻类型的三本书。响应必须 JSON 格式,RFC8259 兼容,不要解释,不要 markdown 代码块。需要符合 schema:数组,每项对象只有 a(作者名称)和 b(书本名称),required a,b,additionalProperties false。需要选择玄幻类型三本书。考虑中文玄幻/奇幻网文:辰东《遮天》、唐家三少《斗罗大陆》、天蚕土豆《斗破苍穹》。这些都是玄幻类型。输出纯 JSON 数组。确保无代码块。"
  6. },
  7. "text" : "[\n {\n \"a\": \"辰东\",\n \"b\": \"遮天\"\n },\n {\n \"a\": \"唐家三少\",\n \"b\": \"斗罗大陆\"\n },\n {\n \"a\": \"天蚕土豆\",\n \"b\": \"斗破苍穹\"\n }\n]",
  8. "toolCalls" : [ ]
  9. }
 2

啊!这个可能是世界上最丑的留言输入框功能~


当然,也是最丑的留言列表

有疑问发邮件到 : suibibk@qq.com 侵权立删
Copyright : 个人随笔   备案号 : 粤ICP备18099399号-2