File size: 1,507 Bytes
3b6afc0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
const CustomAgent = require('./CustomAgent');
const { CustomOutputParser } = require('./outputParser');
const { AgentExecutor } = require('langchain/agents');
const { LLMChain } = require('langchain/chains');
const { BufferMemory, ChatMessageHistory } = require('langchain/memory');
const {
ChatPromptTemplate,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
} = require('langchain/prompts');
const initializeCustomAgent = async ({
tools,
model,
pastMessages,
currentDateString,
...rest
}) => {
let prompt = CustomAgent.createPrompt(tools, { currentDateString, model: model.modelName });
const chatPrompt = ChatPromptTemplate.fromPromptMessages([
new SystemMessagePromptTemplate(prompt),
HumanMessagePromptTemplate.fromTemplate(`{chat_history}
Query: {input}
{agent_scratchpad}`),
]);
const outputParser = new CustomOutputParser({ tools });
const memory = new BufferMemory({
chatHistory: new ChatMessageHistory(pastMessages),
// returnMessages: true, // commenting this out retains memory
memoryKey: 'chat_history',
humanPrefix: 'User',
aiPrefix: 'Assistant',
inputKey: 'input',
outputKey: 'output',
});
const llmChain = new LLMChain({
prompt: chatPrompt,
llm: model,
});
const agent = new CustomAgent({
llmChain,
outputParser,
allowedTools: tools.map((tool) => tool.name),
});
return AgentExecutor.fromAgentAndTools({ agent, tools, memory, ...rest });
};
module.exports = initializeCustomAgent;
|