Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

experimental[patch]: Improve AutoGPT's output_parser to extract JSON code block #3656

Merged
merged 2 commits into from
Dec 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions langchain/src/experimental/autogpt/output_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,24 @@ import { BaseOutputParser } from "../../schema/output_parser.js";
import { AutoGPTAction } from "./schema.js";

/**
* Utility function used to preprocess a string to be parsed as JSON. It
* replaces single backslashes with double backslashes, while leaving
* Utility function used to preprocess a string to be parsed as JSON.
* It replaces single backslashes with double backslashes, while leaving
* already escaped ones intact.
* It also extracts the json code if it is inside a code block
*/
export function preprocessJsonInput(inputStr: string): string {
// Replace single backslashes with double backslashes,
// while leaving already escaped ones intact
const correctedStr = inputStr.replace(
/(?<!\\)\\(?!["\\/bfnrt]|u[0-9a-fA-F]{4})/g,
"\\\\"
);
return correctedStr;
const match = correctedStr.match(
/```(.*)(\r\n|\r|\n)(?<code>[\w\W\n]+)(\r\n|\r|\n)```/
);
if (match?.groups?.code) {
return match.groups.code.trim();
} else {
return correctedStr;
}
}

/**
Expand Down
12 changes: 12 additions & 0 deletions langchain/src/experimental/autogpt/tests/output_parser.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { test, expect } from "@jest/globals";
import { preprocessJsonInput } from "../output_parser.js";

test("should parse outputs correctly", () => {
expect(preprocessJsonInput("{'escaped':'\\a'}")).toBe("{'escaped':'\\\\a'}");

expect(preprocessJsonInput("```\n{}\n```")).toBe("{}");
expect(preprocessJsonInput("```json\n{}\n```")).toBe("{}");
expect(
preprocessJsonInput("I will do the following:\n\n```json\n{}\n```")
).toBe("{}");
});