共50道题 | 难度分布:★★★★☆平均 | 20K+ AI应用岗位LLM输出控制必考
★★★★★
★★★★★
response_format: json_object或structured output。API层面约束输出。★★★★★
response_format: json_object):保证输出合法JSON,但不保证Schema合规。{"key": "value"}的任意JSON——字段名和结构不可控。response_format: json_schema):保证输出完全符合指定的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"]
}
★★★★★
"severity": {"enum": ["high", "medium", "low"]},则生成severity值时只允许这三个Token。★★★★
★★★★
★★★★★
// 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约束输出
@Tool(description = "输出代码审查结果")
public record CodeReviewResult(
@Description("严重级别") String severity,
@Description("问题描述") String description,
@Description("修复建议") String fixSuggestion
) {}
★★★★
$ref递归、patternProperties)。max_tokens。★★★★★
// 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>>() {});
entity()方法让结构化输出像调用一个Java方法一样简单。★★★★
try {
return chatClient.prompt().user(query).call().entity(Target.class);
} catch (OutputConversionException e) {
// 降级:用Prompt方法+手动解析
return fallbackParse(chatClient.prompt().user(query).call().content());
}
★★★★
ChatModel接口屏蔽了不同模型的差异。★★★★
String prompt = """
分析以下代码,以JSON格式输出:
{"issues": [{"severity": "high|medium|low", "description": "...", "fix": "..."}]}
只输出JSON,不要包含其他内容。
代码:
{code}
""";
`json`)增加可解析性。★★★★
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
★★★★
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) {}
★★★★
@JsonProperty或JSON Schema的enum约束字段值。
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;
}
★★★★
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);
★★★★
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);
★★★★
★★★
@lmql.query
def classify(text):
'''LMQL
"Classify: {text}\n"
"Category: [CLASSIFICATION]" where CLASSIFICATION in ["tech", "finance", "health"]
"Confidence: [CONFIDENCE]" where len(CONFIDENCE) < 5
'''
★★★★
json5)尝试解析。
public String repairJson(String broken) {
return chatClient.prompt()
.user("修复以下JSON格式错误:\n" + broken)
.call()
.content();
}
★★★★
★★★★
maxLength、在Prompt中限制"不超过5条"。★★★★
★★★★
★★★★★
// 定义输出模型
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);
★★★
★★★
★★★★
★★★★
★★★★
public record RAGSummary(
String answer,
List<Source> sources,
double confidence,
List<String> followUpQuestions
) {}
public record Source(String title, String excerpt, double relevance) {}
★★★★
★★★
★★★★
★★★
★★★★★
★★★★★
@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);
}
}
}
entity()方法一行搞定。★★★★
OutputConversionException → LLM输出不符合Schema。★★★★
★★★★★
chatClient.prompt().call().entity(Target.class)。