/** * Converts the (raw) LLM output into a structured responses of type. The * {@link FormatProvider#getFormat()} method should provide the LLM prompt description of * the desired format. * * @param <T> Specifies the desired response type. * @author Mark Pollack * @author Christian Tzolov */ publicinterfaceStructuredOutputConverter<T> extendsConverter<String, T>, FormatProvider {
/** * Provides the expected format of the response, instructing that it should adhere to * the generated JSON schema. * @return The instruction format string. */ @Override public String getFormat() { Stringtemplate=""" Your response should be in JSON format. Do not include any explanations, only provide a RFC8259 compliant JSON response following this format without deviation. Do not include markdown code blocks in your response. Remove the ```json markdown from the output. Here is the JSON Schema instance your output must adhere to: ```%s``` """; return String.format(template, this.jsonSchema); }
原来就是一段提示词,我们通过debug看一下,这个getFormat方法被调用后最终提示词的内容:
1 2 3 4 5 6 7 8 9 10
Your response should be in JSON format. Do not include any explanations, only provide a RFC8259 compliant JSON response following this format without deviation. Do not include markdown code blocks in your response. Remove the ```json markdown from the output. Here is the JSON Schema instance your output must adhere to: ```{ "$schema" : "https://json-schema.org/draft/2020-12/schema", "type" : "object", "additionalProperties" : false }```
/** * Parses the given text to transform it to the desired target type. * @param text The LLM output in string format. * @return The parsed output in the desired target type. */ @SuppressWarnings("unchecked")
@Override public T convert( @NonNull String text) { try { // Remove leading and trailing whitespace text = text.trim();
// Check for and remove triple backticks and "json" identifier if (text.startsWith("```") && text.endsWith("```")) { // Remove the first line if it contains "```json" String[] lines = text.split("\n", 2); if (lines[0].trim().equalsIgnoreCase("```json")) { text = lines.length > 1 ? lines[1] : ""; } else { text = text.substring(3); // Remove leading ``` }
// Remove trailing ``` text = text.substring(0, text.length() - 3);
// Trim again to remove any potential whitespace text = text.trim(); } return (T) this.objectMapper.readValue(text, this.objectMapper.constructType(this.type)); } catch (JsonProcessingException e) { logger.error(SENSITIVE_DATA_MARKER, "Could not parse the given text to the desired target type: \"{}\" into {}", text, this.type); thrownewRuntimeException(e); } }
List<String> result = chatClient.prompt("请帮我推荐几本java相关的书").system("你是一个专业的图书推荐人员").call().entity(newListOutputConverter(newDefaultConversionService()));
Map<String,Object> result = chatClient.prompt("请帮我推荐几本java相关的书").system("你是一个专业的图书推荐人员").call().entity(newMapOutputConverter());