-
Notifications
You must be signed in to change notification settings - Fork 8.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Security Solution] [Elastic AI Assistant] LangChain Agents and Tools integration for ES|QL query generation via ELSER #167097
Merged
andrew-goldstein
merged 2 commits into
elastic:main
from
andrew-goldstein:assistant-langchain-agents-tools
Sep 25, 2023
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -7,16 +7,18 @@ | |
|
||
import { ElasticsearchClient, KibanaRequest, Logger } from '@kbn/core/server'; | ||
import type { PluginStartContract as ActionsPluginStart } from '@kbn/actions-plugin/server'; | ||
import { initializeAgentExecutorWithOptions } from 'langchain/agents'; | ||
import { RetrievalQAChain } from 'langchain/chains'; | ||
import { BufferMemory, ChatMessageHistory } from 'langchain/memory'; | ||
import { BaseMessage } from 'langchain/schema'; | ||
import { ChainTool, Tool } from 'langchain/tools'; | ||
|
||
import { ConversationalRetrievalQAChain } from 'langchain/chains'; | ||
import { ElasticsearchStore } from '../elasticsearch_store/elasticsearch_store'; | ||
import { ResponseBody } from '../helpers'; | ||
import { ActionsClientLlm } from '../llm/actions_client_llm'; | ||
import { ElasticsearchStore } from '../elasticsearch_store/elasticsearch_store'; | ||
import { KNOWLEDGE_BASE_INDEX_PATTERN } from '../../../routes/knowledge_base/constants'; | ||
|
||
export const executeCustomLlmChain = async ({ | ||
export const callAgentExecutor = async ({ | ||
actions, | ||
connectorId, | ||
esClient, | ||
|
@@ -34,31 +36,38 @@ export const executeCustomLlmChain = async ({ | |
}): Promise<ResponseBody> => { | ||
const llm = new ActionsClientLlm({ actions, connectorId, request, logger }); | ||
|
||
// Chat History Memory: in-memory memory, from client local storage, first message is the system prompt | ||
const pastMessages = langChainMessages.slice(0, -1); // all but the last message | ||
const latestMessage = langChainMessages.slice(-1); // the last message | ||
|
||
const memory = new BufferMemory({ | ||
chatHistory: new ChatMessageHistory(pastMessages), | ||
memoryKey: 'chat_history', | ||
memoryKey: 'chat_history', // this is the key expected by https://github.com/langchain-ai/langchainjs/blob/a13a8969345b0f149c1ca4a120d63508b06c52a5/langchain/src/agents/initialize.ts#L166 | ||
inputKey: 'input', | ||
outputKey: 'output', | ||
returnMessages: true, | ||
}); | ||
|
||
// ELSER backed ElasticsearchStore for Knowledge Base | ||
const esStore = new ElasticsearchStore(esClient, KNOWLEDGE_BASE_INDEX_PATTERN, logger); | ||
const chain = RetrievalQAChain.fromLLM(llm, esStore.asRetriever()); | ||
|
||
const tools: Tool[] = [ | ||
new ChainTool({ | ||
name: 'esql-language-knowledge-base', | ||
description: | ||
'Call this for knowledge on how to build an ESQL query, or answer questions about the ES|QL query language.', | ||
chain, | ||
}), | ||
]; | ||
|
||
// Chain w/ chat history memory and knowledge base retriever | ||
const chain = ConversationalRetrievalQAChain.fromLLM(llm, esStore.asRetriever(), { | ||
const executor = await initializeAgentExecutorWithOptions(tools, llm, { | ||
agentType: 'chat-conversational-react-description', | ||
memory, | ||
// See `qaChainOptions` from https://js.langchain.com/docs/modules/chains/popular/chat_vector_db | ||
qaChainOptions: { type: 'stuff' }, | ||
verbose: false, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. set this to |
||
}); | ||
await chain.call({ question: latestMessage[0].content }); | ||
|
||
// Chain w/ just knowledge base retriever | ||
// const chain = RetrievalQAChain.fromLLM(llm, esStore.asRetriever()); | ||
// await chain.call({ query: latestMessage[0].content }); | ||
await executor.call({ input: latestMessage[0].content }); | ||
|
||
// The assistant (on the client side) expects the same response returned | ||
// from the actions framework, so we need to return the same shape of data: | ||
return { | ||
connector_id: connectorId, | ||
data: llm.getActionResultData(), // the response from the actions framework | ||
|
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
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
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thoughts on doing this server side as to not leak the agent executor abstraction to the client? Or was there a specific reason this needed to be pushed to the client?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In summary of our offline discussion:
JSON.parse
of the response from the LLMx-pack/plugins/elastic_assistant/server/lib/langchain/execute_custom_llm_chain/index.ts
would look something like the following (psudocode):x-pack/packages/kbn-elastic-assistant/impl/assistant/api.tsx
In summary, it's possible, but given the above adds an additional server side JSON parse of the LLM response and requires some additional client side refactoring, we'll reconsider the above post FF.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thank you for taking the time to discuss offline and for summarizing here 🙏 , path forward sounds good to me 👍