-
-
Save ma-zah/74d492d872c5f66773930900abde9f2e to your computer and use it in GitHub Desktop.
on type safety in LangChain TS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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