← 返回首页 ❓ 面试题库
📑 本篇章节导航 (共6章,点击直达)
一、结构化输出基础(1-7)二、OpenAI Structured Outputs(8-13)三、输出控制高级技巧(14-20)四、输出控制场景实战(21-28)五、高级主题(29-35)六、面试总结(36-50)

Q61 - 结构化输出与大模型输出控制

共50道题 | 难度分布:★★★★☆平均 | 20K+ AI应用岗位LLM输出控制必考

一、结构化输出基础(1-7)

为什么需要LLM结构化输出?

★★★★★

LLM结构化输出的三种方法?

★★★★★

JSON Mode vs Structured Outputs的区别?

★★★★★

JSON Schema约束详解?

★★★★


{
  "type": "object",
  "properties": {
    "issues": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "severity": {"type": "string", "enum": ["high", "medium", "low"]},
          "description": {"type": "string"},
          "fix": {"type": "string"}
        },
        "required": ["severity", "description"]
      }
    }
  },
  "required": ["issues"]
}

Constrained Decoding(受限解码)原理?

★★★★★

logits mask工作原理?

★★★★

结构化输出的可靠性等级?

★★★★

二、OpenAI Structured Outputs(8-13)

OpenAI Structured Outputs API使用?

★★★★★


// Spring AI中使用Structured Output
@Bean
public ChatClient chatClient(ChatModel chatModel) {
    return ChatClient.builder(chatModel).build();
}

// 方式1:通过BeanOutputConverter
BeanOutputConverter<CodeReview> converter =
    new BeanOutputConverter<>(CodeReview.class);
String format = converter.getFormat();

String response = chatClient.prompt()
    .user(u -> u.text("分析以下代码:{code}").param("code", code))
    .call()
    .content();

CodeReview review = converter.convert(response);

Function Calling作为结构化输出的替代方案?

★★★★


// 用Function Calling约束输出
@Tool(description = "输出代码审查结果")
public record CodeReviewResult(
    @Description("严重级别") String severity,
    @Description("问题描述") String description,
    @Description("修复建议") String fixSuggestion
) {}

OpenAI Structured Outputs的局限性?

★★★★

Spring AI的结构化输出支持?

★★★★★


// Spring AI直接映射到Java Record
public record CodeReview(
    String severity,
    String description,
    String fixSuggestion,
    List<String> affectedFiles
) {}

// 方式1:entity()方法(最简洁)
CodeReview review = chatClient.prompt()
    .user("分析以下Java代码的安全性")
    .call()
    .entity(CodeReview.class);

// 方式2:List输出
List<Issue> issues = chatClient.prompt()
    .user("列出这段代码的所有问题")
    .call()
    .entity(new ParameterizedTypeReference<List<Issue>>() {});

错误处理与重试?

★★★★


try {
    return chatClient.prompt().user(query).call().entity(Target.class);
} catch (OutputConversionException e) {
    // 降级:用Prompt方法+手动解析
    return fallbackParse(chatClient.prompt().user(query).call().content());
}

多模型的结构化输出适配?

★★★★

三、输出控制高级技巧(14-20)

Prompt方法实现结构化输出?

★★★★


String prompt = """
分析以下代码,以JSON格式输出:
{"issues": [{"severity": "high|medium|low", "description": "...", "fix": "..."}]}
只输出JSON,不要包含其他内容。
代码:
{code}
""";

Pydantic模型集成?

★★★★


from pydantic import BaseModel
from openai import OpenAI

class CodeReview(BaseModel):
    severity: str
    description: str
    fix: str

client = OpenAI()
response = client.beta.chat.completions.parse(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Review this code"}],
    response_format=CodeReview
)
review = response.choices[0].message.parsed

Instructor库(Python)?

★★★★


import instructor
from pydantic import BaseModel

client = instructor.from_openai(OpenAI())

class Review(BaseModel):
    severity: str
    description: str

review = client.chat.completions.create(
    model="gpt-4o",
    response_model=Review,
    messages=[{"role": "user", "content": "Review this code"}]
)

流式结构化输出?

★★★★


for partial in client.chat.completions.create_partial(
    model="gpt-4o",
    response_model=Review,
    messages=[...]
):
    print(partial.severity)  # 字段完成后立即可用

复杂嵌套结构的处理?

★★★★


public record CodeAnalysis(
    String summary,
    List<Issue> issues,
    Metrics metrics
) {}
public record Issue(String severity, String desc) {}
public record Metrics(int complexity, double coverage) {}

枚举值和常量约束?

★★★★


public record Issue(
    @JsonProperty(required = true) String severity, // "high","medium","low"
    String description
) {}
// 或在Spring AI中使用枚举
public enum Severity { HIGH, MEDIUM, LOW }
public record Issue(Severity severity, String description) {}

输出验证与后处理?

★★★★


public CodeReview validate(CodeReview review) {
    if (review.issues().size() > 20) throw new ValidationException("Too many issues");
    if (!Set.of("high","medium","low").contains(review.severity()))
        throw new ValidationException("Invalid severity");
    return review;
}

四、输出控制场景实战(21-28)

API参数提取?

★★★★


public record SearchParams(
    String keyword,
    String category,
    Double minPrice,
    Double maxPrice,
    String sortBy // "price","date","rating"
) {}

SearchParams params = chatClient.prompt()
    .user("帮我找便宜的Java书籍,按价格排序")
    .call()
    .entity(SearchParams.class);
// → {keyword:"Java书籍", category:"book", sortBy:"price"}

数据库记录生成?

★★★★


public record Product(
    String name,
    String category,
    BigDecimal price,
    List<String> tags,
    String description
) {}

Product product = chatClient.prompt()
    .user("从以下商品描述中提取信息:{description}")
    .call()
    .entity(Product.class);
productRepository.save(product);

代码生成与AST控制?

★★★★


public record ApiSpec(
    String path,
    String method,
    List<Param> params,
    String returnType,
    String businessLogic
) {}

表格数据提取?

★★★★


List<TableRow> rows = chatClient.prompt()
    .user("从以下文本中提取表格数据:{text}")
    .call()
    .entity(new ParameterizedTypeReference<List<TableRow>>() {});

分类任务的结构化输出?

★★★★


public record Classification(
    String category,     // "tech","finance","health"
    double confidence,   // 0.0-1.0
    String reasoning
) {}

多语言翻译的结构化控制?

★★★★


public record Translation(
    String original,
    String translated,
    String language,
    double confidence
) {}

文档摘要的结构化控制?

★★★★


public record DocumentSummary(
    String title,
    List<String> keyPoints,
    List<String> keywords,
    String category,
    String sentiment,
    int readingTimeMinutes
) {}

表单填充场景?

★★★★


public record UserForm(
    String name,
    String email,
    String phone,
    String address,
    String company,
    String purpose
) {}

UserForm form = chatClient.prompt()
    .user("我叫张三,邮箱zhangsan@company.com,想咨询AI培训")
    .call()
    .entity(UserForm.class);

五、高级主题(29-35)

Outlines库(Constrained Decoding)?

★★★★

LMQL查询语言?

★★★


@lmql.query
def classify(text):
    '''LMQL
    "Classify: {text}\n"
    "Category: [CLASSIFICATION]" where CLASSIFICATION in ["tech", "finance", "health"]
    "Confidence: [CONFIDENCE]" where len(CONFIDENCE) < 5
    '''

自修复输出?

★★★★


public String repairJson(String broken) {
    return chatClient.prompt()
        .user("修复以下JSON格式错误:\n" + broken)
        .call()
        .content();
}

批量结构化输出?

★★★★

输出长度控制?

★★★★

输出一致性保证?

★★★★

安全与Prompt注入对结构化输出的影响?

★★★★

六、面试总结(36-50)

Java Record作为结构化输出模型?

★★★★★


// 定义输出模型
public record CodeReviewResult(
    @JsonProperty(required = true) String summary,
    List<Issue> issues,
    int overallScore,
    String recommendation
) {}

public record Issue(
    Severity severity,
    String location,
    String description,
    String fixSuggestion
) {}

public enum Severity { CRITICAL, HIGH, MEDIUM, LOW, INFO }

// 使用
CodeReviewResult result = chatClient.prompt()
    .user("审查以下代码:\n" + code)
    .call()
    .entity(CodeReviewResult.class);

XML格式输出控制?

★★★

Markdown表格输出控制?

★★★

多步骤结构化输出?

★★★★

结构化输出的性能影响?

★★★★

与RAG结合的结构化输出?

★★★★


public record RAGSummary(
    String answer,
    List<Source> sources,
    double confidence,
    List<String> followUpQuestions
) {}
public record Source(String title, String excerpt, double relevance) {}

结构化输出的测试策略?

★★★★

结构化输出的A/B测试?

★★★

低代码/无代码场景的结构化输出?

★★★★

结构化输出的未来趋势?

★★★

面试高频:结构化输出最佳实践总结?

★★★★★

Spring AI结构化输出完整示例?

★★★★★


@Configuration
public class StructuredOutputConfig {

    // 定义输出模型
    public record TaskExtraction(
        String taskName,
        String assignee,
        String dueDate,
        Priority priority,
        List<String> subtasks,
        String notes
    ) {}

    public enum Priority { URGENT, HIGH, MEDIUM, LOW }

    @RestController
    @RequestMapping("/api/tasks")
    public static class TaskController {
        private final ChatClient chatClient;

        @PostMapping("/extract")
        public TaskExtraction extract(@RequestBody String description) {
            return chatClient.prompt()
                .system("从任务描述中提取结构化信息。日期格式:yyyy-MM-dd。")
                .user(description)
                .call()
                .entity(TaskExtraction.class);
        }
    }
}

结构化输出的常见错误与排查?

★★★★

结构化输出 vs 模板引擎?

★★★★

结构化输出面试高频10连问?

★★★★★