结构化输出
1. JSON Schema
java
@Test
void test08() {
ResponseFormat responseFormat = ResponseFormat.builder()
.type(ResponseFormatType.JSON) // type can be either TEXT (default) or JSON
.jsonSchema(JsonSchema.builder()
.name("Person") // OpenAI requires specifying the name for the schema
.rootElement(JsonObjectSchema.builder() // see [1] below
.addStringProperty("name")
.addIntegerProperty("age")
.addNumberProperty("height")
.addBooleanProperty("married")
.required("name", "age", "height", "married") // see [2] below
.build())
.build())
.build();
UserMessage userMessage = UserMessage.from("""
John is 42 years old and lives an independent life.
He stands 1.75 meters tall and carries himself with confidence.
Currently unmarried, he enjoys the freedom to focus on his personal goals and interests.
""");
ChatRequest chatRequest = ChatRequest.builder()
.responseFormat(responseFormat)
.messages(userMessage)
.build();
ChatResponse chat = BASE_MODEL.chat(chatRequest);
AiMessage aiMessage = chat.aiMessage();
}
DeepSeek 似乎不支持这个JSON的格式声明
AiService中使用, 在springboot中不需要额外的声明就可以返回POJO
java
interface PersonExtractor {
Person extractPersonFrom(String text);
}
@Test
void test08() {
PersonExtractor personExtractor = AiServices.create(PersonExtractor.class, BASE_MODEL);
String text = """
John is 42 years old and lives an independent life.
He stands 1.75 meters tall and carries himself with confidence.
Currently unmarried, he enjoys the freedom to focus on his personal goals and interests.
""";
Person person = personExtractor.extractPersonFrom(text);
System.out.println(person); // Person[name=John, age=42, height=1.75, married=false]
}
属性的必填和可选, 使用 @JsonProperty(required = true)
java
class Address {
@Description("街道地址")
@JsonProperty(required = true)
public String street;
}
Polymorphic Types 多态类型
java
sealed interface Animal permits Dog, Cat {}
record Dog(String name, String breed) implements Animal {}
record Cat(String name, boolean indoor) implements Animal {}
interface AnimalExtractor {
Animal extractAnimalFrom(String text);
}