Skip to content

Instantly share code, notes, and snippets.

@ma-zah
Created September 29, 2023 15:17
Show Gist options
  • Save ma-zah/74d492d872c5f66773930900abde9f2e to your computer and use it in GitHub Desktop.
Save ma-zah/74d492d872c5f66773930900abde9f2e to your computer and use it in GitHub Desktop.
on type safety in LangChain TS
/**
* Parses the given text and returns an `AgentAction` or `AgentFinish`
* object. If an `OutputFixingParser` is provided, it is used for parsing;
* otherwise, the base parser is used.
* @param text The text to parse.
* @param callbacks Optional callbacks for asynchronous operations.
* @returns A Promise that resolves to an `AgentAction` or `AgentFinish` object.
*/
async parse(text: string): Promise<AgentAction | AgentFinish> {
try {
const regex = /```(?:json)?(.*)(```)/gs;
const actionMatch = regex.exec(text);
if (actionMatch === null) {
throw new OutputParserException(
`Could not parse an action. The agent action must be within a markdown code block,
and "action" must be a provided tool or "Final Answer"`
);
}
const response = JSON.parse(actionMatch[1].trim());
const { action, action_input } = response;
if (action === "Final Answer") {
return { returnValues: { output: action_input }, log: text };
}
return { tool: action, toolInput: action_input || {}, log: text };
} catch (e) {
throw new OutputParserException(
`Failed to parse. Text: "${text}". Error: ${e}`
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment