Skip to content

Commit

Permalink
refactor: two output parsing methods for if runnable vs no runnable i…
Browse files Browse the repository at this point in the history
…s passed in
  • Loading branch information
bracesproul committed Oct 16, 2023
1 parent 07af29c commit fdd8ff8
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
25 changes: 21 additions & 4 deletions langchain/src/agents/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import {
StoppingMethod,
} from "./types.js";
import { Runnable } from "../schema/runnable/base.js";
import { StringOutputParser } from "../schema/output_parser.js";

/**
* Record type for arguments passed to output parsers.
Expand Down Expand Up @@ -416,12 +415,30 @@ export abstract class Agent<
newInputs.stop = this._stop();
}

const output = await this.runnable.invoke(newInputs, callbackManager);

/**
* The output type for this is a little weird, depending on if a
* runnable was passed in or not.
*
* If a runnable is passed in (and not an LLMChain), then the output is
* `AgentAction | AgentFinish`.
* If an LLMChain was passed, the output will be `{ text: string }`.
*/
const output = (await this.runnable.invoke(newInputs, callbackManager)) as
| {
text: string;
}
| AgentAction
| AgentFinish;

if (!this.outputParser) {
throw new Error("Output parser not set");
}
return this.outputParser.parse(output, callbackManager);

if ("text" in output) {
return this.outputParser.parse(output.text, callbackManager);
}

return this.outputParser.parseAgentOutput(output, callbackManager);
}

/**
Expand Down
7 changes: 6 additions & 1 deletion langchain/src/agents/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Callbacks } from "../callbacks/manager.js";
import { LLMChain } from "../chains/llm_chain.js";
import { SerializedLLMChain } from "../chains/serde.js";
import {
Expand Down Expand Up @@ -47,7 +48,11 @@ export interface RunnableAgentInput<
*/
export abstract class AgentActionOutputParser extends BaseOutputParser<
AgentAction | AgentFinish
> {}
> {
async parseAgentOutput(output: AgentFinish | AgentAction, _callbackManager?: Callbacks) {
return output;
}
}

/**
* Type representing the stopping method for an agent. It can be either
Expand Down

0 comments on commit fdd8ff8

Please sign in to comment.