mirror of
https://github.com/n8n-io/n8n.git
synced 2025-03-05 20:50:17 -08:00
format and lintfix
This commit is contained in:
parent
e589c348b9
commit
f267eed22c
|
@ -1,30 +1,28 @@
|
||||||
|
import type { AgentAction, AgentFinish, AgentStep } from '@langchain/core/agents';
|
||||||
|
import type { CallbackManagerForChainRun, Callbacks } from '@langchain/core/callbacks/manager';
|
||||||
|
import { CallbackManager } from '@langchain/core/callbacks/manager';
|
||||||
|
import { Serializable } from '@langchain/core/load/serializable';
|
||||||
|
import { OutputParserException } from '@langchain/core/output_parsers';
|
||||||
|
import { Runnable, type RunnableConfig, patchConfig } from '@langchain/core/runnables';
|
||||||
import {
|
import {
|
||||||
type StructuredToolInterface,
|
type StructuredToolInterface,
|
||||||
type ToolInterface,
|
type ToolInterface,
|
||||||
ToolInputParsingException,
|
ToolInputParsingException,
|
||||||
Tool,
|
Tool,
|
||||||
} from '@langchain/core/tools';
|
} from '@langchain/core/tools';
|
||||||
import { Runnable, type RunnableConfig, patchConfig } from '@langchain/core/runnables';
|
import type { ChainValues } from '@langchain/core/utils/types';
|
||||||
import { AgentAction, AgentFinish, AgentStep } from '@langchain/core/agents';
|
import type { BaseMultiActionAgent, BaseSingleActionAgent } from 'langchain/dist/agents/agent';
|
||||||
import { ChainValues } from '@langchain/core/utils/types';
|
|
||||||
import {
|
|
||||||
CallbackManager,
|
|
||||||
CallbackManagerForChainRun,
|
|
||||||
Callbacks,
|
|
||||||
} from '@langchain/core/callbacks/manager';
|
|
||||||
import { OutputParserException } from '@langchain/core/output_parsers';
|
|
||||||
import { Serializable } from '@langchain/core/load/serializable';
|
|
||||||
import { SerializedLLMChain } from 'langchain/dist/chains/serde';
|
|
||||||
import { StoppingMethod } from 'langchain/dist/agents/types';
|
|
||||||
import {
|
import {
|
||||||
AgentRunnableSequence,
|
AgentRunnableSequence,
|
||||||
BaseMultiActionAgent,
|
|
||||||
BaseSingleActionAgent,
|
|
||||||
RunnableMultiActionAgent,
|
RunnableMultiActionAgent,
|
||||||
RunnableSingleActionAgent,
|
RunnableSingleActionAgent,
|
||||||
isRunnableAgent,
|
isRunnableAgent,
|
||||||
} from 'langchain/dist/agents/agent';
|
} from 'langchain/dist/agents/agent';
|
||||||
import { BaseChain, ChainInputs } from 'langchain/dist/chains/base';
|
import type { StoppingMethod } from 'langchain/dist/agents/types';
|
||||||
|
import type { ChainInputs } from 'langchain/dist/chains/base';
|
||||||
|
import { BaseChain } from 'langchain/dist/chains/base';
|
||||||
|
import type { SerializedLLMChain } from 'langchain/dist/chains/serde';
|
||||||
|
import { ApplicationError } from 'n8n-workflow';
|
||||||
|
|
||||||
interface AgentExecutorIteratorInput {
|
interface AgentExecutorIteratorInput {
|
||||||
agentExecutor: AgentExecutor;
|
agentExecutor: AgentExecutor;
|
||||||
|
@ -153,7 +151,7 @@ export class AgentExecutorIterator extends Serializable implements AgentExecutor
|
||||||
*/
|
*/
|
||||||
async onFirstStep(): Promise<void> {
|
async onFirstStep(): Promise<void> {
|
||||||
if (this.iterations === 0) {
|
if (this.iterations === 0) {
|
||||||
const callbackManager = await CallbackManager.configure(
|
const callbackManager = CallbackManager.configure(
|
||||||
this.callbacks ?? this.config?.callbacks,
|
this.callbacks ?? this.config?.callbacks,
|
||||||
this.agentExecutor.callbacks,
|
this.agentExecutor.callbacks,
|
||||||
this.tags ?? this.config?.tags,
|
this.tags ?? this.config?.tags,
|
||||||
|
@ -186,7 +184,7 @@ export class AgentExecutorIterator extends Serializable implements AgentExecutor
|
||||||
async _executeNextStep(
|
async _executeNextStep(
|
||||||
runManager?: CallbackManagerForChainRun,
|
runManager?: CallbackManagerForChainRun,
|
||||||
): Promise<AgentFinish | AgentStep[]> {
|
): Promise<AgentFinish | AgentStep[]> {
|
||||||
return this.agentExecutor._takeNextStep(
|
return await this.agentExecutor._takeNextStep(
|
||||||
this.nameToToolMap,
|
this.nameToToolMap,
|
||||||
this.inputs,
|
this.inputs,
|
||||||
this.intermediateSteps,
|
this.intermediateSteps,
|
||||||
|
@ -205,7 +203,7 @@ export class AgentExecutorIterator extends Serializable implements AgentExecutor
|
||||||
): Promise<Record<string, string | AgentStep[]>> {
|
): Promise<Record<string, string | AgentStep[]>> {
|
||||||
if ('returnValues' in nextStepOutput) {
|
if ('returnValues' in nextStepOutput) {
|
||||||
const output = await this.agentExecutor._return(
|
const output = await this.agentExecutor._return(
|
||||||
nextStepOutput as AgentFinish,
|
nextStepOutput,
|
||||||
this.intermediateSteps,
|
this.intermediateSteps,
|
||||||
runManager,
|
runManager,
|
||||||
);
|
);
|
||||||
|
@ -216,7 +214,7 @@ export class AgentExecutorIterator extends Serializable implements AgentExecutor
|
||||||
return output;
|
return output;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.intermediateSteps = this.intermediateSteps.concat(nextStepOutput as AgentStep[]);
|
this.intermediateSteps = this.intermediateSteps.concat(nextStepOutput);
|
||||||
|
|
||||||
let output: Record<string, string | AgentStep[]> = {};
|
let output: Record<string, string | AgentStep[]> = {};
|
||||||
if (Array.isArray(nextStepOutput) && nextStepOutput.length === 1) {
|
if (Array.isArray(nextStepOutput) && nextStepOutput.length === 1) {
|
||||||
|
@ -228,7 +226,7 @@ export class AgentExecutorIterator extends Serializable implements AgentExecutor
|
||||||
await this.setFinalOutputs(output);
|
await this.setFinalOutputs(output);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
output = { intermediateSteps: nextStepOutput as AgentStep[] };
|
output = { intermediateSteps: nextStepOutput };
|
||||||
return output;
|
return output;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -251,13 +249,13 @@ export class AgentExecutorIterator extends Serializable implements AgentExecutor
|
||||||
async _callNext(): Promise<Record<string, unknown>> {
|
async _callNext(): Promise<Record<string, unknown>> {
|
||||||
// final output already reached: stopiteration (final output)
|
// final output already reached: stopiteration (final output)
|
||||||
if (this.finalOutputs) {
|
if (this.finalOutputs) {
|
||||||
throw new Error(
|
throw new ApplicationError(
|
||||||
`Final outputs already reached: ${JSON.stringify(this.finalOutputs, null, 2)}`,
|
`Final outputs already reached: ${JSON.stringify(this.finalOutputs, null, 2)}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
// timeout/max iterations: stopiteration (stopped response)
|
// timeout/max iterations: stopiteration (stopped response)
|
||||||
if (!this.agentExecutor.shouldContinueGetter(this.iterations)) {
|
if (!this.agentExecutor.shouldContinueGetter(this.iterations)) {
|
||||||
return this._stop();
|
return await this._stop();
|
||||||
}
|
}
|
||||||
const nextStepOutput = await this._executeNextStep(this.runManager);
|
const nextStepOutput = await this._executeNextStep(this.runManager);
|
||||||
const output = await this._processNextStepOutput(nextStepOutput, this.runManager);
|
const output = await this._processNextStepOutput(nextStepOutput, this.runManager);
|
||||||
|
@ -266,8 +264,8 @@ export class AgentExecutorIterator extends Serializable implements AgentExecutor
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type ExtractToolType<T> = T extends { ToolType: infer ToolInterface }
|
type ExtractToolType<T> = T extends { ToolType: infer IToolInterface }
|
||||||
? ToolInterface
|
? IToolInterface
|
||||||
: StructuredToolInterface;
|
: StructuredToolInterface;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -280,7 +278,7 @@ export interface AgentExecutorInput extends ChainInputs {
|
||||||
| BaseSingleActionAgent
|
| BaseSingleActionAgent
|
||||||
| BaseMultiActionAgent
|
| BaseMultiActionAgent
|
||||||
| Runnable<ChainValues & { steps?: AgentStep[] }, AgentAction[] | AgentAction | AgentFinish>;
|
| Runnable<ChainValues & { steps?: AgentStep[] }, AgentAction[] | AgentAction | AgentFinish>;
|
||||||
tools: ExtractToolType<this['agent']>[];
|
tools: Array<ExtractToolType<this['agent']>>;
|
||||||
returnIntermediateSteps?: boolean;
|
returnIntermediateSteps?: boolean;
|
||||||
maxIterations?: number;
|
maxIterations?: number;
|
||||||
earlyStoppingMethod?: StoppingMethod;
|
earlyStoppingMethod?: StoppingMethod;
|
||||||
|
@ -337,7 +335,7 @@ export class AgentExecutor extends BaseChain<ChainValues, AgentExecutorOutput> {
|
||||||
|
|
||||||
agent: BaseSingleActionAgent | BaseMultiActionAgent;
|
agent: BaseSingleActionAgent | BaseMultiActionAgent;
|
||||||
|
|
||||||
tools: this['agent']['ToolType'][];
|
tools: Array<this['agent']['ToolType']>;
|
||||||
|
|
||||||
returnIntermediateSteps = false;
|
returnIntermediateSteps = false;
|
||||||
|
|
||||||
|
@ -410,7 +408,7 @@ export class AgentExecutor extends BaseChain<ChainValues, AgentExecutorOutput> {
|
||||||
if (this.agent._agentActionType() === 'multi') {
|
if (this.agent._agentActionType() === 'multi') {
|
||||||
for (const tool of this.tools) {
|
for (const tool of this.tools) {
|
||||||
if (tool.returnDirect) {
|
if (tool.returnDirect) {
|
||||||
throw new Error(
|
throw new ApplicationError(
|
||||||
`Tool with return direct ${tool.name} not supported for multi-action agent.`,
|
`Tool with return direct ${tool.name} not supported for multi-action agent.`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -474,7 +472,6 @@ export class AgentExecutor extends BaseChain<ChainValues, AgentExecutorOutput> {
|
||||||
try {
|
try {
|
||||||
output = await this.agent.plan(steps, inputs, runManager?.getChild(), config);
|
output = await this.agent.plan(steps, inputs, runManager?.getChild(), config);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// eslint-disable-next-line no-instanceof/no-instanceof
|
|
||||||
if (e instanceof OutputParserException) {
|
if (e instanceof OutputParserException) {
|
||||||
let observation;
|
let observation;
|
||||||
let text = e.message;
|
let text = e.message;
|
||||||
|
@ -503,14 +500,14 @@ export class AgentExecutor extends BaseChain<ChainValues, AgentExecutorOutput> {
|
||||||
}
|
}
|
||||||
// Check if the agent has finished
|
// Check if the agent has finished
|
||||||
if ('returnValues' in output) {
|
if ('returnValues' in output) {
|
||||||
return getOutput(output);
|
return await getOutput(output);
|
||||||
}
|
}
|
||||||
|
|
||||||
let actions: AgentAction[];
|
let actions: AgentAction[];
|
||||||
if (Array.isArray(output)) {
|
if (Array.isArray(output)) {
|
||||||
actions = output as AgentAction[];
|
actions = output;
|
||||||
} else {
|
} else {
|
||||||
actions = [output as AgentAction];
|
actions = [output];
|
||||||
}
|
}
|
||||||
|
|
||||||
const newSteps = await Promise.all(
|
const newSteps = await Promise.all(
|
||||||
|
@ -529,11 +526,12 @@ export class AgentExecutor extends BaseChain<ChainValues, AgentExecutorOutput> {
|
||||||
)
|
)
|
||||||
: `${action.tool} is not a valid tool, try another one.`;
|
: `${action.tool} is not a valid tool, try another one.`;
|
||||||
if (typeof observation !== 'string') {
|
if (typeof observation !== 'string') {
|
||||||
throw new Error('Received unsupported non-string response from tool call.');
|
throw new ApplicationError(
|
||||||
|
'Received unsupported non-string response from tool call.',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
// eslint-disable-next-line no-instanceof/no-instanceof
|
|
||||||
if (e instanceof ToolInputParsingException) {
|
if (e instanceof ToolInputParsingException) {
|
||||||
if (this.handleParsingErrors === true) {
|
if (this.handleParsingErrors === true) {
|
||||||
observation = 'Invalid or incomplete tool input. Please try again.';
|
observation = 'Invalid or incomplete tool input. Please try again.';
|
||||||
|
@ -561,7 +559,7 @@ export class AgentExecutor extends BaseChain<ChainValues, AgentExecutorOutput> {
|
||||||
const lastTool = toolsByName[lastStep.action.tool?.toLowerCase()];
|
const lastTool = toolsByName[lastStep.action.tool?.toLowerCase()];
|
||||||
|
|
||||||
if (lastTool?.returnDirect) {
|
if (lastTool?.returnDirect) {
|
||||||
return getOutput({
|
return await getOutput({
|
||||||
returnValues: { [this.agent.returnValues[0]]: lastStep.observation },
|
returnValues: { [this.agent.returnValues[0]]: lastStep.observation },
|
||||||
log: '',
|
log: '',
|
||||||
});
|
});
|
||||||
|
@ -572,7 +570,7 @@ export class AgentExecutor extends BaseChain<ChainValues, AgentExecutorOutput> {
|
||||||
|
|
||||||
const finish = await this.agent.returnStoppedResponse(this.earlyStoppingMethod, steps, inputs);
|
const finish = await this.agent.returnStoppedResponse(this.earlyStoppingMethod, steps, inputs);
|
||||||
|
|
||||||
return getOutput(finish);
|
return await getOutput(finish);
|
||||||
}
|
}
|
||||||
|
|
||||||
async _takeNextStep(
|
async _takeNextStep(
|
||||||
|
@ -586,7 +584,6 @@ export class AgentExecutor extends BaseChain<ChainValues, AgentExecutorOutput> {
|
||||||
try {
|
try {
|
||||||
output = await this.agent.plan(intermediateSteps, inputs, runManager?.getChild(), config);
|
output = await this.agent.plan(intermediateSteps, inputs, runManager?.getChild(), config);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// eslint-disable-next-line no-instanceof/no-instanceof
|
|
||||||
if (e instanceof OutputParserException) {
|
if (e instanceof OutputParserException) {
|
||||||
let observation;
|
let observation;
|
||||||
let text = e.message;
|
let text = e.message;
|
||||||
|
@ -620,9 +617,9 @@ export class AgentExecutor extends BaseChain<ChainValues, AgentExecutorOutput> {
|
||||||
|
|
||||||
let actions: AgentAction[];
|
let actions: AgentAction[];
|
||||||
if (Array.isArray(output)) {
|
if (Array.isArray(output)) {
|
||||||
actions = output as AgentAction[];
|
actions = output;
|
||||||
} else {
|
} else {
|
||||||
actions = [output as AgentAction];
|
actions = [output];
|
||||||
}
|
}
|
||||||
|
|
||||||
const result: AgentStep[] = [];
|
const result: AgentStep[] = [];
|
||||||
|
@ -636,10 +633,9 @@ export class AgentExecutor extends BaseChain<ChainValues, AgentExecutorOutput> {
|
||||||
try {
|
try {
|
||||||
observation = await tool.call(agentAction.toolInput, runManager?.getChild());
|
observation = await tool.call(agentAction.toolInput, runManager?.getChild());
|
||||||
if (typeof observation !== 'string') {
|
if (typeof observation !== 'string') {
|
||||||
throw new Error('Received unsupported non-string response from tool call.');
|
throw new ApplicationError('Received unsupported non-string response from tool call.');
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// eslint-disable-next-line no-instanceof/no-instanceof
|
|
||||||
if (e instanceof ToolInputParsingException) {
|
if (e instanceof ToolInputParsingException) {
|
||||||
if (this.handleParsingErrors === true) {
|
if (this.handleParsingErrors === true) {
|
||||||
observation = 'Invalid or incomplete tool input. Please try again.';
|
observation = 'Invalid or incomplete tool input. Please try again.';
|
||||||
|
@ -706,7 +702,7 @@ export class AgentExecutor extends BaseChain<ChainValues, AgentExecutorOutput> {
|
||||||
log: '',
|
log: '',
|
||||||
} as AgentFinish;
|
} as AgentFinish;
|
||||||
}
|
}
|
||||||
throw new Error(`Got unsupported early_stopping_method: ${earlyStoppingMethod}`);
|
throw new ApplicationError(`Got unsupported early_stopping_method: ${earlyStoppingMethod}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
async *_streamIterator(
|
async *_streamIterator(
|
||||||
|
@ -737,6 +733,6 @@ export class AgentExecutor extends BaseChain<ChainValues, AgentExecutorOutput> {
|
||||||
}
|
}
|
||||||
|
|
||||||
serialize(): SerializedLLMChain {
|
serialize(): SerializedLLMChain {
|
||||||
throw new Error('Cannot serialize an AgentExecutor');
|
throw new ApplicationError('Cannot serialize an AgentExecutor');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue