Skip to content

Commit

Permalink
Merge pull request HamaWhiteGG#27 from HamaWhiteGG/dev
Browse files Browse the repository at this point in the history
support structured output parser
  • Loading branch information
HamaWhiteGG authored Jul 3, 2023
2 parents de2be50 + 2376dd9 commit ad36889
Show file tree
Hide file tree
Showing 18 changed files with 648 additions and 37 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import com.hw.langchain.agents.agent.Agent;
import com.hw.langchain.agents.agent.AgentOutputParser;
import com.hw.langchain.agents.chat.output.parser.ChatOutputParser;
import com.hw.langchain.agents.initialize.Initialize;
import com.hw.langchain.base.language.BaseLanguageModel;
import com.hw.langchain.chains.llm.LLMChain;
import com.hw.langchain.prompts.base.BasePromptTemplate;
Expand All @@ -38,6 +39,7 @@

import static com.hw.langchain.agents.chat.prompt.Prompt.*;
import static com.hw.langchain.agents.utils.Utils.validateToolsSingleInput;
import static com.hw.langchain.prompts.utils.FormatUtils.formatTemplate;

/**
* @author HamaWhite
Expand Down Expand Up @@ -92,10 +94,7 @@ public static BasePromptTemplate createPrompt(List<BaseTool> tools, String syste
String toolStrings =
String.join("\n", tools.stream().map(tool -> tool.getName() + ": " + tool.getDescription()).toList());

formatInstructions = formatInstructions.replace("{tool_names}", toolNames);
// In Python format() method, the curly braces '{{}}' are used to represent the output '{}'.
formatInstructions = formatInstructions.replace("{{{{", "{{").replace("}}}}", "}}");

formatInstructions = formatTemplate(formatInstructions, Map.of("tool_names", toolNames));
String template =
String.join("\n\n", systemMessagePrefix, toolStrings, formatInstructions, systemMessageSuffix);

Expand All @@ -110,6 +109,7 @@ public static BasePromptTemplate createPrompt(List<BaseTool> tools, String syste

/**
* Construct an agent from an LLM and tools.
* This method will be called by the {@link Initialize#initializeAgent} using MethodUtils.invokeStaticMethod.
*/
public static Agent fromLLMAndTools(BaseLanguageModel llm, List<BaseTool> tools, Map<String, Object> kwargs) {
return fromLLMAndTools(llm, tools, null, SYSTEM_MESSAGE_PREFIX, SYSTEM_MESSAGE_SUFFIX, HUMAN_MESSAGE,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@
*/
public class Initialize {

private Initialize() {
}

public static AgentExecutor initializeAgent(List<BaseTool> tools, BaseLanguageModel llm, AgentType agent) {
return initializeAgent(tools, llm, agent, null, Map.of(), Map.of());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@

import static com.google.common.base.Preconditions.checkArgument;
import static com.hw.langchain.agents.mrkl.prompt.Prompt.*;
import static com.hw.langchain.prompts.utils.FormatUtils.formatTemplate;

/**
* Agent for the MRKL chain.
Expand Down Expand Up @@ -63,10 +64,7 @@ public static PromptTemplate createPrompt(List<BaseTool> tools, String prefix, S
String.join("\n", tools.stream().map(tool -> tool.getName() + ": " + tool.getDescription()).toList());
String toolNames = String.join(", ", tools.stream().map(BaseTool::getName).toList());

formatInstructions = formatInstructions.replace("{tool_names}", toolNames);
// In Python format() method, the curly braces '{{}}' are used to represent the output '{}'.
formatInstructions = formatInstructions.replace("{{{{", "{{").replace("}}}}", "}}");

formatInstructions = formatTemplate(formatInstructions, Map.of("tool_names", toolNames));
String template = String.join("\n\n", prefix, toolStrings, formatInstructions, suffix);

if (inputVariables == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ public class Prompt {
Relevant Table Names:
""";

public static PromptTemplate DECIDER_PROMPT = new PromptTemplate(List.of("query", "table_names"),
_DECIDER_TEMPLATE,
public static PromptTemplate DECIDER_PROMPT = new PromptTemplate(_DECIDER_TEMPLATE,
List.of("query", "table_names"),
new CommaSeparatedListOutputParser());

private static String _mysql_prompt =
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.hw.langchain.output.parsers;

/**
* @author HamaWhite
*/
public class FormatInstructions {

public static String STRUCTURED_FORMAT_INSTRUCTIONS =
"""
The output should be a markdown code snippet formatted in the following schema, including the leading and trailing "```json" and "```":
```json
{{
{format}
}}
```""";

public static String PYDANTIC_FORMAT_INSTRUCTIONS =
"""
The output should be formatted as a JSON instance that conforms to the JSON schema below.
As an example, for the schema {{"properties": {{"foo": {{"title": "Foo", "description": "a list of strings", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}}}
the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of the schema. The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
Here is the output schema:
```
{schema}
```""";
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.hw.langchain.output.parsers.json;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hw.langchain.schema.OutputParserException;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @author HamaWhite
*/
public class Json {

private Json() {

}

private static final Pattern PATTERN = Pattern.compile("```(json)?(.*?)```", Pattern.DOTALL);

/**
* Parse a JSON string from a Markdown string.
*
* @param jsonString The Markdown string.
* @return The parsed JSON object as a Python dictionary.
*/
public static JsonNode parseJsonMarkdown(String jsonString) {
// Try to find JSON string within triple backticks
Matcher matcher = PATTERN.matcher(jsonString);

// If match found, use the content within the backticks,otherwise assume the entire string is a JSON string
String jsonStr = matcher.find() ? matcher.group(2) : jsonString;

// Strip whitespace and newlines from the start and end
jsonStr = jsonStr.strip();
try {
// Parse the JSON string into a JsonNode
return new ObjectMapper().readTree(jsonStr);
} catch (JsonProcessingException e) {
throw new OutputParserException("Got invalid JSON object. Error: " + e.getMessage());
}
}

/**
* Parse a JSON string from a Markdown string and check that it contains the expected keys.
*
* @param markdown The Markdown string.
* @param expectedKeys The expected keys in the JSON string.
* @return The parsed JSON object as a JsonNode.
*/
public static JsonNode parseAndCheckJsonMarkdown(String markdown, List<String> expectedKeys) {
JsonNode jsonNode = parseJsonMarkdown(markdown);
for (String key : expectedKeys) {
if (!jsonNode.has(key)) {
throw new OutputParserException(String.format(
"Got invalid return object. Expected key `%s` to be present, but got %s", key, jsonNode));
}
}
return jsonNode;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.hw.langchain.output.parsers.structured;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
* @author HamaWhite
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResponseSchema {

private String name;

private String description;

private String type = "string";

public ResponseSchema(String name, String description) {
this.name = name;
this.description = description;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.hw.langchain.output.parsers.structured;

import com.fasterxml.jackson.databind.JsonNode;
import com.hw.langchain.schema.BaseOutputParser;

import java.util.List;
import java.util.Map;

import static com.hw.langchain.output.parsers.FormatInstructions.STRUCTURED_FORMAT_INSTRUCTIONS;
import static com.hw.langchain.output.parsers.json.Json.parseAndCheckJsonMarkdown;
import static com.hw.langchain.prompts.utils.FormatUtils.formatTemplate;

/**
* @author HamaWhite
*/
public class StructuredOutputParser extends BaseOutputParser<JsonNode> {

private static final String LINE_TEMPLATE = "\t\"{name}\": {type} // {description}";

private final List<ResponseSchema> responseSchemas;

public StructuredOutputParser(List<ResponseSchema> responseSchemas) {
this.responseSchemas = responseSchemas;
}

public static StructuredOutputParser fromResponseSchemas(List<ResponseSchema> responseSchemas) {
return new StructuredOutputParser(responseSchemas);
}

private String getSubString(ResponseSchema schema) {
Map<String, Object> kwargs = Map.of("name", schema.getName(),
"description", schema.getDescription(),
"type", schema.getType());
return formatTemplate(LINE_TEMPLATE, kwargs);
}

@Override
public JsonNode parse(String text) {
var expectedKeys = responseSchemas.stream()
.map(ResponseSchema::getName)
.toList();
return parseAndCheckJsonMarkdown(text, expectedKeys);
}

@Override
public String getFormatInstructions() {
var schemaStr = String.join("\n", responseSchemas.stream().map(this::getSubString).toList());
return formatTemplate(STRUCTURED_FORMAT_INSTRUCTIONS, Map.of("format", schemaStr));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,11 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

/**
* Base class for all prompt templates, returning a prompt.
*
* @author HamaWhite
*/
@Data
Expand All @@ -48,11 +50,16 @@ public abstract class BasePromptTemplate {

protected Map<String, Object> partialVariables = new HashMap<>();

public BasePromptTemplate(List<String> inputVariables) {
protected BasePromptTemplate(List<String> inputVariables) {
this.inputVariables = inputVariables;
}

protected BasePromptTemplate(List<String> inputVariables, Map<String, Object> partialVariables) {
this.inputVariables = inputVariables;
this.partialVariables = partialVariables;
}

public BasePromptTemplate(List<String> inputVariables, BaseOutputParser<?> outputParser) {
protected BasePromptTemplate(List<String> inputVariables, BaseOutputParser<?> outputParser) {
this.inputVariables = inputVariables;
this.outputParser = outputParser;
}
Expand All @@ -62,10 +69,32 @@ public BasePromptTemplate(List<String> inputVariables, BaseOutputParser<?> outpu
*/
public abstract PromptValue formatPrompt(Map<String, Object> kwargs);

/**
* Merge the partial variables and user variables into a single map.
*
* @param kwargs Additional user variables provided.
* @return Merged map containing partial variables and user variables.
*/
public Map<String, Object> mergePartialAndUserVariables(Map<String, Object> kwargs) {
var mergedVariables = new HashMap<String, Object>(partialVariables.size() + kwargs.size());
// Add partial variables
partialVariables.forEach((key, value) -> {
if (value instanceof String stringValue) {
mergedVariables.put(key, stringValue);
} else if (value instanceof Supplier<?> supplier) {
mergedVariables.put(key, supplier.get());
}
});
// Add user variables
mergedVariables.putAll(kwargs);
return mergedVariables;
}

/**
* Format the prompt with the inputs.
*
* @param kwargs Any arguments to be passed to the prompt template.
* @return A formatted string.
* @return A formatted string.
*/
public abstract String format(Map<String, Object> kwargs);

Expand Down
Loading

0 comments on commit ad36889

Please sign in to comment.