@langchain/classic 1.0.34 → 1.0.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/dist/agents/chat/index.cjs.map +1 -1
- package/dist/agents/chat/index.js.map +1 -1
- package/dist/agents/chat/outputParser.cjs.map +1 -1
- package/dist/agents/chat/outputParser.d.cts +2 -2
- package/dist/agents/chat/outputParser.js.map +1 -1
- package/dist/agents/chat_convo/index.cjs.map +1 -1
- package/dist/agents/chat_convo/index.js.map +1 -1
- package/dist/agents/chat_convo/outputParser.cjs.map +1 -1
- package/dist/agents/chat_convo/outputParser.js.map +1 -1
- package/dist/agents/executor.cjs.map +1 -1
- package/dist/agents/executor.js.map +1 -1
- package/dist/agents/format_scratchpad/log.cjs.map +1 -1
- package/dist/agents/format_scratchpad/log.js.map +1 -1
- package/dist/agents/format_scratchpad/log_to_message.cjs.map +1 -1
- package/dist/agents/format_scratchpad/log_to_message.js.map +1 -1
- package/dist/agents/initialize.cjs.map +1 -1
- package/dist/agents/initialize.js.map +1 -1
- package/dist/agents/mrkl/index.cjs.map +1 -1
- package/dist/agents/mrkl/index.js.map +1 -1
- package/dist/agents/mrkl/outputParser.cjs.map +1 -1
- package/dist/agents/mrkl/outputParser.d.cts +1 -1
- package/dist/agents/mrkl/outputParser.js.map +1 -1
- package/dist/agents/openai_functions/index.cjs.map +1 -1
- package/dist/agents/openai_functions/index.js.map +1 -1
- package/dist/agents/openai_tools/index.cjs.map +1 -1
- package/dist/agents/openai_tools/index.js.map +1 -1
- package/dist/agents/react/index.cjs.map +1 -1
- package/dist/agents/react/index.js.map +1 -1
- package/dist/agents/react/output_parser.cjs.map +1 -1
- package/dist/agents/react/output_parser.js.map +1 -1
- package/dist/agents/structured_chat/index.cjs.map +1 -1
- package/dist/agents/structured_chat/index.js.map +1 -1
- package/dist/agents/structured_chat/outputParser.cjs.map +1 -1
- package/dist/agents/structured_chat/outputParser.js.map +1 -1
- package/dist/agents/tool_calling/index.cjs.map +1 -1
- package/dist/agents/tool_calling/index.js.map +1 -1
- package/dist/agents/toolkits/conversational_retrieval/openai_functions.cjs.map +1 -1
- package/dist/agents/toolkits/conversational_retrieval/openai_functions.js.map +1 -1
- package/dist/agents/toolkits/conversational_retrieval/tool.cjs.map +1 -1
- package/dist/agents/toolkits/conversational_retrieval/tool.js.map +1 -1
- package/dist/agents/toolkits/json/json.cjs.map +1 -1
- package/dist/agents/toolkits/json/json.js.map +1 -1
- package/dist/agents/toolkits/openapi/openapi.cjs.map +1 -1
- package/dist/agents/toolkits/openapi/openapi.js.map +1 -1
- package/dist/agents/toolkits/sql/sql.cjs.map +1 -1
- package/dist/agents/toolkits/sql/sql.js.map +1 -1
- package/dist/agents/toolkits/vectorstore/vectorstore.cjs.map +1 -1
- package/dist/agents/toolkits/vectorstore/vectorstore.js.map +1 -1
- package/dist/agents/xml/index.cjs.map +1 -1
- package/dist/agents/xml/index.js.map +1 -1
- package/dist/chains/analyze_documents_chain.cjs.map +1 -1
- package/dist/chains/analyze_documents_chain.js.map +1 -1
- package/dist/chains/api/api_chain.cjs.map +1 -1
- package/dist/chains/api/api_chain.js.map +1 -1
- package/dist/chains/api/prompts.js.map +1 -1
- package/dist/chains/base.cjs.map +1 -1
- package/dist/chains/base.js.map +1 -1
- package/dist/chains/chat_vector_db_chain.cjs.map +1 -1
- package/dist/chains/chat_vector_db_chain.js.map +1 -1
- package/dist/chains/combine_docs_chain.cjs.map +1 -1
- package/dist/chains/combine_docs_chain.js.map +1 -1
- package/dist/chains/combine_documents/base.cjs.map +1 -1
- package/dist/chains/combine_documents/base.js.map +1 -1
- package/dist/chains/combine_documents/reduce.cjs.map +1 -1
- package/dist/chains/combine_documents/reduce.js.map +1 -1
- package/dist/chains/constitutional_ai/constitutional_prompts.cjs.map +1 -1
- package/dist/chains/constitutional_ai/constitutional_prompts.js.map +1 -1
- package/dist/chains/conversational_retrieval_chain.cjs.map +1 -1
- package/dist/chains/conversational_retrieval_chain.js.map +1 -1
- package/dist/chains/graph_qa/cypher.cjs.map +1 -1
- package/dist/chains/graph_qa/cypher.js.map +1 -1
- package/dist/chains/graph_qa/prompts.cjs.map +1 -1
- package/dist/chains/graph_qa/prompts.js.map +1 -1
- package/dist/chains/history_aware_retriever.cjs.map +1 -1
- package/dist/chains/history_aware_retriever.js.map +1 -1
- package/dist/chains/llm_chain.cjs.map +1 -1
- package/dist/chains/llm_chain.js.map +1 -1
- package/dist/chains/openai_functions/base.cjs.map +1 -1
- package/dist/chains/openai_functions/base.js.map +1 -1
- package/dist/chains/openai_functions/openapi.cjs.map +1 -1
- package/dist/chains/openai_functions/openapi.js.map +1 -1
- package/dist/chains/query_constructor/index.cjs.map +1 -1
- package/dist/chains/query_constructor/index.js.map +1 -1
- package/dist/chains/query_constructor/parser.cjs.map +1 -1
- package/dist/chains/query_constructor/parser.js.map +1 -1
- package/dist/chains/query_constructor/prompt.cjs.map +1 -1
- package/dist/chains/query_constructor/prompt.js.map +1 -1
- package/dist/chains/question_answering/load.cjs.map +1 -1
- package/dist/chains/question_answering/load.js.map +1 -1
- package/dist/chains/question_answering/map_reduce_prompts.cjs.map +1 -1
- package/dist/chains/question_answering/map_reduce_prompts.js.map +1 -1
- package/dist/chains/question_answering/refine_prompts.cjs.map +1 -1
- package/dist/chains/question_answering/refine_prompts.js.map +1 -1
- package/dist/chains/question_answering/stuff_prompts.cjs.map +1 -1
- package/dist/chains/question_answering/stuff_prompts.js.map +1 -1
- package/dist/chains/retrieval.cjs.map +1 -1
- package/dist/chains/retrieval.js.map +1 -1
- package/dist/chains/router/multi_prompt.cjs.map +1 -1
- package/dist/chains/router/multi_prompt.js.map +1 -1
- package/dist/chains/router/multi_retrieval_qa.cjs.map +1 -1
- package/dist/chains/router/multi_retrieval_qa.js.map +1 -1
- package/dist/chains/sql_db/sql_db_chain.cjs.map +1 -1
- package/dist/chains/sql_db/sql_db_chain.js.map +1 -1
- package/dist/chains/summarization/load.cjs.map +1 -1
- package/dist/chains/summarization/load.js.map +1 -1
- package/dist/chains/summarization/refine_prompts.cjs.map +1 -1
- package/dist/chains/summarization/refine_prompts.js.map +1 -1
- package/dist/chains/summarization/stuff_prompts.cjs.map +1 -1
- package/dist/chains/summarization/stuff_prompts.js.map +1 -1
- package/dist/chat_models/universal.cjs.map +1 -1
- package/dist/chat_models/universal.js.map +1 -1
- package/dist/document_loaders/fs/json.cjs.map +1 -1
- package/dist/document_loaders/fs/json.js.map +1 -1
- package/dist/document_loaders/fs/multi_file.cjs.map +1 -1
- package/dist/document_loaders/fs/multi_file.js.map +1 -1
- package/dist/document_transformers/openai_functions.cjs.map +1 -1
- package/dist/document_transformers/openai_functions.js.map +1 -1
- package/dist/evaluation/agents/prompt.cjs.map +1 -1
- package/dist/evaluation/agents/prompt.js.map +1 -1
- package/dist/evaluation/comparison/pairwise.cjs.map +1 -1
- package/dist/evaluation/comparison/pairwise.js.map +1 -1
- package/dist/evaluation/comparison/prompt.cjs.map +1 -1
- package/dist/evaluation/comparison/prompt.js.map +1 -1
- package/dist/evaluation/criteria/criteria.cjs.map +1 -1
- package/dist/evaluation/criteria/criteria.js.map +1 -1
- package/dist/evaluation/criteria/prompt.cjs.map +1 -1
- package/dist/evaluation/criteria/prompt.js.map +1 -1
- package/dist/evaluation/embedding_distance/base.cjs.map +1 -1
- package/dist/evaluation/embedding_distance/base.js.map +1 -1
- package/dist/evaluation/qa/eval_chain.cjs.map +1 -1
- package/dist/evaluation/qa/eval_chain.js.map +1 -1
- package/dist/evaluation/qa/prompt.cjs.map +1 -1
- package/dist/evaluation/qa/prompt.js.map +1 -1
- package/dist/experimental/autogpt/agent.cjs.map +1 -1
- package/dist/experimental/autogpt/agent.js.map +1 -1
- package/dist/experimental/autogpt/prompt.cjs.map +1 -1
- package/dist/experimental/autogpt/prompt.js.map +1 -1
- package/dist/experimental/autogpt/prompt_generator.cjs.map +1 -1
- package/dist/experimental/autogpt/prompt_generator.js.map +1 -1
- package/dist/experimental/babyagi/agent.cjs.map +1 -1
- package/dist/experimental/babyagi/agent.js.map +1 -1
- package/dist/experimental/babyagi/task_creation.cjs.map +1 -1
- package/dist/experimental/babyagi/task_creation.js.map +1 -1
- package/dist/experimental/babyagi/task_execution.cjs.map +1 -1
- package/dist/experimental/babyagi/task_execution.js.map +1 -1
- package/dist/experimental/babyagi/task_prioritization.cjs.map +1 -1
- package/dist/experimental/babyagi/task_prioritization.js.map +1 -1
- package/dist/experimental/chains/violation_of_expectations/violation_of_expectations_chain.cjs.map +1 -1
- package/dist/experimental/chains/violation_of_expectations/violation_of_expectations_chain.js.map +1 -1
- package/dist/experimental/generative_agents/generative_agent.cjs.map +1 -1
- package/dist/experimental/generative_agents/generative_agent.js.map +1 -1
- package/dist/experimental/generative_agents/generative_agent_memory.cjs.map +1 -1
- package/dist/experimental/generative_agents/generative_agent_memory.js.map +1 -1
- package/dist/experimental/masking/regex_masking_transformer.cjs.map +1 -1
- package/dist/experimental/masking/regex_masking_transformer.js.map +1 -1
- package/dist/experimental/openai_assistant/index.cjs.map +1 -1
- package/dist/experimental/openai_assistant/index.js.map +1 -1
- package/dist/experimental/plan_and_execute/agent_executor.cjs.map +1 -1
- package/dist/experimental/plan_and_execute/agent_executor.js.map +1 -1
- package/dist/experimental/plan_and_execute/base.cjs.map +1 -1
- package/dist/experimental/plan_and_execute/base.js.map +1 -1
- package/dist/experimental/prompts/handlebars.cjs.map +1 -1
- package/dist/experimental/prompts/handlebars.js.map +1 -1
- package/dist/hub/base.cjs.map +1 -1
- package/dist/hub/base.js.map +1 -1
- package/dist/hub/index.cjs.map +1 -1
- package/dist/hub/index.js.map +1 -1
- package/dist/hub/node.cjs.map +1 -1
- package/dist/hub/node.js.map +1 -1
- package/dist/memory/buffer_memory.cjs.map +1 -1
- package/dist/memory/buffer_memory.js.map +1 -1
- package/dist/memory/buffer_token_memory.cjs.map +1 -1
- package/dist/memory/buffer_token_memory.js.map +1 -1
- package/dist/memory/buffer_window_memory.cjs.map +1 -1
- package/dist/memory/buffer_window_memory.js.map +1 -1
- package/dist/memory/entity_memory.cjs.map +1 -1
- package/dist/memory/entity_memory.js.map +1 -1
- package/dist/memory/prompt.cjs.map +1 -1
- package/dist/memory/prompt.js.map +1 -1
- package/dist/memory/summary.cjs.map +1 -1
- package/dist/memory/summary.js.map +1 -1
- package/dist/output_parsers/expression.cjs.map +1 -1
- package/dist/output_parsers/expression.js.map +1 -1
- package/dist/output_parsers/expression_type_handlers/base.cjs.map +1 -1
- package/dist/output_parsers/expression_type_handlers/base.js.map +1 -1
- package/dist/output_parsers/expression_type_handlers/factory.cjs.map +1 -1
- package/dist/output_parsers/expression_type_handlers/factory.js.map +1 -1
- package/dist/output_parsers/expression_type_handlers/identifier_handler.cjs.map +1 -1
- package/dist/output_parsers/expression_type_handlers/identifier_handler.js.map +1 -1
- package/dist/output_parsers/expression_type_handlers/property_assignment_handler.cjs.map +1 -1
- package/dist/output_parsers/expression_type_handlers/property_assignment_handler.js.map +1 -1
- package/dist/output_parsers/expression_type_handlers/string_literal_handler.cjs.map +1 -1
- package/dist/output_parsers/expression_type_handlers/string_literal_handler.js.map +1 -1
- package/dist/output_parsers/fix.cjs.map +1 -1
- package/dist/output_parsers/fix.js.map +1 -1
- package/dist/output_parsers/http_response.cjs.map +1 -1
- package/dist/output_parsers/http_response.js.map +1 -1
- package/dist/output_parsers/openai_functions.cjs.map +1 -1
- package/dist/output_parsers/openai_functions.js.map +1 -1
- package/dist/output_parsers/openai_tools.cjs.map +1 -1
- package/dist/output_parsers/openai_tools.js.map +1 -1
- package/dist/output_parsers/prompts.cjs.map +1 -1
- package/dist/output_parsers/prompts.js.map +1 -1
- package/dist/output_parsers/structured.cjs.map +1 -1
- package/dist/output_parsers/structured.js.map +1 -1
- package/dist/retrievers/contextual_compression.cjs.map +1 -1
- package/dist/retrievers/contextual_compression.js.map +1 -1
- package/dist/retrievers/document_compressors/chain_extract.cjs.map +1 -1
- package/dist/retrievers/document_compressors/chain_extract.js.map +1 -1
- package/dist/retrievers/ensemble.cjs.map +1 -1
- package/dist/retrievers/ensemble.js.map +1 -1
- package/dist/retrievers/hyde.cjs.map +1 -1
- package/dist/retrievers/hyde.js.map +1 -1
- package/dist/retrievers/multi_query.cjs.map +1 -1
- package/dist/retrievers/multi_query.js.map +1 -1
- package/dist/retrievers/multi_vector.cjs.map +1 -1
- package/dist/retrievers/multi_vector.js.map +1 -1
- package/dist/retrievers/parent_document.cjs.map +1 -1
- package/dist/retrievers/parent_document.js.map +1 -1
- package/dist/retrievers/score_threshold.cjs.map +1 -1
- package/dist/retrievers/score_threshold.js.map +1 -1
- package/dist/smith/runner_utils.cjs.map +1 -1
- package/dist/smith/runner_utils.js.map +1 -1
- package/dist/storage/encoder_backed.cjs.map +1 -1
- package/dist/storage/encoder_backed.js.map +1 -1
- package/dist/storage/file_system.cjs.map +1 -1
- package/dist/storage/file_system.js.map +1 -1
- package/dist/tools/json.cjs.map +1 -1
- package/dist/tools/json.js.map +1 -1
- package/dist/tools/requests.cjs.map +1 -1
- package/dist/tools/requests.js.map +1 -1
- package/dist/tools/retriever.cjs.map +1 -1
- package/dist/tools/retriever.js.map +1 -1
- package/dist/tools/sql.cjs.map +1 -1
- package/dist/tools/sql.js.map +1 -1
- package/dist/tools/webbrowser.cjs.map +1 -1
- package/dist/tools/webbrowser.js.map +1 -1
- package/dist/util/hub.cjs.map +1 -1
- package/dist/util/hub.js.map +1 -1
- package/dist/util/load.cjs.map +1 -1
- package/dist/util/load.js.map +1 -1
- package/dist/util/openapi.cjs.map +1 -1
- package/dist/util/openapi.js.map +1 -1
- package/dist/util/sql_utils.cjs.map +1 -1
- package/dist/util/sql_utils.js.map +1 -1
- package/dist/vectorstores/memory.cjs.map +1 -1
- package/dist/vectorstores/memory.js.map +1 -1
- package/package.json +47 -48
package/dist/hub/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/hub/index.ts"],"sourcesContent":["import { Runnable } from \"@langchain/core/runnables\";\nimport type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport { load } from \"../load/index.js\";\nimport {\n basePush,\n basePull,\n generateModelImportMap,\n generateOptionalImportMap,\n bindOutputSchema,\n} from \"./base.js\";\n\nexport { basePush as push };\n\n/**\n * Pull a prompt from the hub.\n *\n * @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.\n * @param options.apiKey LangSmith API key to use when pulling the prompt\n * @param options.apiUrl LangSmith API URL to use when pulling the prompt\n * @param options.includeModel Whether to also instantiate and attach a model instance to the prompt,\n * if the prompt has associated model metadata. If set to true, invoking the resulting pulled prompt will\n * also invoke the instantiated model. For non-OpenAI models, you must also set \"modelClass\" to the\n * correct class of the model.\n * @param options.modelClass If includeModel is true, the class of the model to instantiate. Required\n * for non-OpenAI models. If you are running in Node or another environment that supports dynamic imports,\n * you may instead import this function from \"langchain/hub/node\" and pass \"includeModel: true\" instead\n * of specifying this parameter.\n * @param options.secrets A map of secrets to use when loading, e.g.\n * {'OPENAI_API_KEY': 'sk-...'}`.\n * If a secret is not found in the map, it will be loaded from the\n * environment if `secrets_from_env` is `True`. Should only be needed when\n * `includeModel` is `true`.\n * @param options.secretsFromEnv Whether to load secrets from environment variables.\n * Use with caution and only with trusted prompts.\n * @returns\n */\nexport async function pull<T extends Runnable>(\n ownerRepoCommit: string,\n options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n modelClass?: new (...args: any[]) => BaseLanguageModel;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n }\n) {\n const promptObject = await basePull(ownerRepoCommit, options);\n try {\n const loadedPrompt = await load<T>(\n JSON.stringify(promptObject.manifest),\n options?.secrets,\n generateOptionalImportMap(options?.modelClass),\n generateModelImportMap(options?.modelClass),\n options?.secretsFromEnv\n );\n return bindOutputSchema(loadedPrompt);\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n if (options?.includeModel) {\n throw new Error(\n [\n e.message,\n \"\",\n `To load prompts with an associated non-OpenAI model, you must use the \"langchain/hub/node\" entrypoint, or pass a \"modelClass\" parameter like this:`,\n \"\",\n \"```\",\n `import { pull } from \"langchain/hub\";`,\n `import { ChatAnthropic } from \"@langchain/anthropic\";`,\n \"\",\n `const prompt = await pull(\"my-prompt\", {`,\n ` includeModel: true,`,\n ` modelClass: ChatAnthropic,`,\n `});`,\n \"```\",\n ].join(\"\\n\")\n );\n } else {\n throw e;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,eAAsB,KACpB,iBACA,SASA;CACA,MAAM,eAAe,MAAM,SAAS,iBAAiB,QAAQ;AAC7D,KAAI;AAQF,SAAO,
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/hub/index.ts"],"sourcesContent":["import { Runnable } from \"@langchain/core/runnables\";\nimport type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport { load } from \"../load/index.js\";\nimport {\n basePush,\n basePull,\n generateModelImportMap,\n generateOptionalImportMap,\n bindOutputSchema,\n} from \"./base.js\";\n\nexport { basePush as push };\n\n/**\n * Pull a prompt from the hub.\n *\n * @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.\n * @param options.apiKey LangSmith API key to use when pulling the prompt\n * @param options.apiUrl LangSmith API URL to use when pulling the prompt\n * @param options.includeModel Whether to also instantiate and attach a model instance to the prompt,\n * if the prompt has associated model metadata. If set to true, invoking the resulting pulled prompt will\n * also invoke the instantiated model. For non-OpenAI models, you must also set \"modelClass\" to the\n * correct class of the model.\n * @param options.modelClass If includeModel is true, the class of the model to instantiate. Required\n * for non-OpenAI models. If you are running in Node or another environment that supports dynamic imports,\n * you may instead import this function from \"langchain/hub/node\" and pass \"includeModel: true\" instead\n * of specifying this parameter.\n * @param options.secrets A map of secrets to use when loading, e.g.\n * {'OPENAI_API_KEY': 'sk-...'}`.\n * If a secret is not found in the map, it will be loaded from the\n * environment if `secrets_from_env` is `True`. Should only be needed when\n * `includeModel` is `true`.\n * @param options.secretsFromEnv Whether to load secrets from environment variables.\n * Use with caution and only with trusted prompts.\n * @returns\n */\nexport async function pull<T extends Runnable>(\n ownerRepoCommit: string,\n options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n modelClass?: new (...args: any[]) => BaseLanguageModel;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n }\n) {\n const promptObject = await basePull(ownerRepoCommit, options);\n try {\n const loadedPrompt = await load<T>(\n JSON.stringify(promptObject.manifest),\n options?.secrets,\n generateOptionalImportMap(options?.modelClass),\n generateModelImportMap(options?.modelClass),\n options?.secretsFromEnv\n );\n return bindOutputSchema(loadedPrompt);\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n if (options?.includeModel) {\n throw new Error(\n [\n e.message,\n \"\",\n `To load prompts with an associated non-OpenAI model, you must use the \"langchain/hub/node\" entrypoint, or pass a \"modelClass\" parameter like this:`,\n \"\",\n \"```\",\n `import { pull } from \"langchain/hub\";`,\n `import { ChatAnthropic } from \"@langchain/anthropic\";`,\n \"\",\n `const prompt = await pull(\"my-prompt\", {`,\n ` includeModel: true,`,\n ` modelClass: ChatAnthropic,`,\n `});`,\n \"```\",\n ].join(\"\\n\")\n );\n } else {\n throw e;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,eAAsB,KACpB,iBACA,SASA;CACA,MAAM,eAAe,MAAM,SAAS,iBAAiB,QAAQ;AAC7D,KAAI;AAQF,SAAO,iBAAiB,MAPG,KACzB,KAAK,UAAU,aAAa,SAAS,EACrC,SAAS,SACT,0BAA0B,SAAS,WAAW,EAC9C,uBAAuB,SAAS,WAAW,EAC3C,SAAS,eACV,CACoC;UAE9B,GAAQ;AACf,MAAI,SAAS,aACX,OAAM,IAAI,MACR;GACE,EAAE;GACF;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACD,CAAC,KAAK,KAAK,CACb;MAED,OAAM"}
|
package/dist/hub/node.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.cjs","names":["basePull","getChatModelByClassName","bindOutputSchema","load","generateOptionalImportMap","generateModelImportMap"],"sources":["../../src/hub/node.ts"],"sourcesContent":["import { Runnable } from \"@langchain/core/runnables\";\nimport {\n basePull,\n generateModelImportMap,\n generateOptionalImportMap,\n bindOutputSchema,\n} from \"./base.js\";\nimport { load } from \"../load/index.js\";\nimport { getChatModelByClassName } from \"../chat_models/universal.js\";\n\nexport { basePush as push } from \"./base.js\";\n\nfunction _idEquals(a: string[], b: string[]): boolean {\n if (!Array.isArray(a) || !Array.isArray(b)) {\n return false;\n }\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n\nfunction isRunnableBinding(a: string[]): boolean {\n const wellKnownIds = [\n [\"langchain_core\", \"runnables\", \"RunnableBinding\"],\n [\"langchain\", \"schema\", \"runnable\", \"RunnableBinding\"],\n ];\n return wellKnownIds.some((id) => _idEquals(a, id));\n}\n\n/**\n * Infer modelProvider from the id namespace to avoid className collisions.\n * For non-langchain packages, extracts the provider name from the namespace.\n * e.g., [\"langchain\", \"chat_models\", \"vertexai\", \"ChatVertexAI\"] -> \"google-vertexai\"\n * e.g., [\"langchain_deepseek\", \"chat_models\", \"ChatDeepSeek\"] -> \"deepseek\"\n * @param idArray The full id array from the manifest\n * @returns The inferred modelProvider key or undefined\n */\nexport function inferModelProviderFromNamespace(\n idArray: string[]\n): string | undefined {\n if (!Array.isArray(idArray) || idArray.length < 2) {\n return undefined;\n }\n\n // Check namespace parts (excluding the className at the end)\n const namespace = idArray.slice(0, -1);\n\n // Look for a part that looks like a provider package (not langchain/langchain_core)\n for (const part of namespace) {\n // Skip standard langchain packages\n if (\n part === \"langchain\" ||\n part === \"langchain_core\" ||\n part === \"chat_models\" ||\n part === \"runnables\" ||\n part === \"schema\"\n ) {\n continue;\n }\n\n // If it starts with \"langchain_\", extract the provider name\n // e.g., \"langchain_google_genai\" -> \"google-genai\"\n // e.g., \"langchain_deepseek\" -> \"deepseek\"\n if (part.startsWith(\"langchain_\")) {\n const providerName = part.slice(\"langchain_\".length);\n // Convert underscores to hyphens to match MODEL_PROVIDER_CONFIG keys\n return providerName.replace(/_/g, \"-\");\n }\n\n // Handle special cases for Google providers that need prefix\n if (part.includes(\"vertexai_web\")) {\n return \"google-vertexai-web\";\n } else if (part.includes(\"vertexai\")) {\n return \"google-vertexai\";\n } else if (part.includes(\"genai\") || part.includes(\"google_genai\")) {\n return \"google-genai\";\n }\n\n // For other provider-looking parts, use as-is with underscores converted to hyphens\n // e.g., \"openai\" -> \"openai\", \"anthropic\" -> \"anthropic\"\n if (\n !part.includes(\"langchain\") &&\n part !== \"chat_models\" &&\n part !== \"runnables\"\n ) {\n return part.replace(/_/g, \"-\");\n }\n }\n\n return undefined;\n}\n\n/**\n * Pull a prompt from the hub.\n * @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.\n * @param options.apiKey LangSmith API key to use when pulling the prompt\n * @param options.apiUrl LangSmith API URL to use when pulling the prompt\n * @param options.includeModel Whether to also instantiate and attach a model instance to the prompt,\n * if the prompt has associated model metadata. If set to true, invoking the resulting pulled prompt will\n * also invoke the instantiated model. You must have the appropriate LangChain integration package installed.\n * @param options.secrets A map of secrets to use when loading, e.g.\n * {'OPENAI_API_KEY': 'sk-...'}`.\n * If a secret is not found in the map, it will be loaded from the\n * environment if `secrets_from_env` is `True`. Should only be needed when\n * `includeModel` is `true`.\n * @param options.secretsFromEnv Whether to load secrets from environment variables.\n * Use with caution and only with trusted prompts.\n * @returns\n */\nexport async function pull<T extends Runnable>(\n ownerRepoCommit: string,\n options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n }\n) {\n const promptObject = await basePull(ownerRepoCommit, options);\n let modelClass;\n if (options?.includeModel) {\n const chatModelObject = isRunnableBinding(\n promptObject.manifest.kwargs?.last?.id\n )\n ? promptObject.manifest.kwargs?.last?.kwargs?.bound\n : promptObject.manifest.kwargs?.last;\n\n if (Array.isArray(chatModelObject?.id)) {\n const modelName = chatModelObject?.id.at(-1);\n\n if (modelName) {\n const modelProvider = inferModelProviderFromNamespace(\n chatModelObject.id\n );\n modelClass = await getChatModelByClassName(modelName, modelProvider);\n if (!modelClass) {\n console.warn(\n `Received unknown model name from prompt hub: \"${modelName}\"`\n );\n }\n }\n }\n }\n const loadedPrompt = await load<T>(\n JSON.stringify(promptObject.manifest),\n options?.secrets,\n generateOptionalImportMap(modelClass),\n generateModelImportMap(modelClass),\n options?.secretsFromEnv\n );\n return bindOutputSchema(loadedPrompt);\n}\n"],"mappings":";;;;;AAYA,SAAS,UAAU,GAAa,GAAsB;AACpD,KAAI,CAAC,MAAM,QAAQ,EAAE,IAAI,CAAC,MAAM,QAAQ,EAAE,CACxC,QAAO;AAET,KAAI,EAAE,WAAW,EAAE,OACjB,QAAO;AAET,MAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,IAC5B,KAAI,EAAE,OAAO,EAAE,GACb,QAAO;AAGX,QAAO;;AAGT,SAAS,kBAAkB,GAAsB;AAK/C,
|
|
1
|
+
{"version":3,"file":"node.cjs","names":["basePull","getChatModelByClassName","bindOutputSchema","load","generateOptionalImportMap","generateModelImportMap"],"sources":["../../src/hub/node.ts"],"sourcesContent":["import { Runnable } from \"@langchain/core/runnables\";\nimport {\n basePull,\n generateModelImportMap,\n generateOptionalImportMap,\n bindOutputSchema,\n} from \"./base.js\";\nimport { load } from \"../load/index.js\";\nimport { getChatModelByClassName } from \"../chat_models/universal.js\";\n\nexport { basePush as push } from \"./base.js\";\n\nfunction _idEquals(a: string[], b: string[]): boolean {\n if (!Array.isArray(a) || !Array.isArray(b)) {\n return false;\n }\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n\nfunction isRunnableBinding(a: string[]): boolean {\n const wellKnownIds = [\n [\"langchain_core\", \"runnables\", \"RunnableBinding\"],\n [\"langchain\", \"schema\", \"runnable\", \"RunnableBinding\"],\n ];\n return wellKnownIds.some((id) => _idEquals(a, id));\n}\n\n/**\n * Infer modelProvider from the id namespace to avoid className collisions.\n * For non-langchain packages, extracts the provider name from the namespace.\n * e.g., [\"langchain\", \"chat_models\", \"vertexai\", \"ChatVertexAI\"] -> \"google-vertexai\"\n * e.g., [\"langchain_deepseek\", \"chat_models\", \"ChatDeepSeek\"] -> \"deepseek\"\n * @param idArray The full id array from the manifest\n * @returns The inferred modelProvider key or undefined\n */\nexport function inferModelProviderFromNamespace(\n idArray: string[]\n): string | undefined {\n if (!Array.isArray(idArray) || idArray.length < 2) {\n return undefined;\n }\n\n // Check namespace parts (excluding the className at the end)\n const namespace = idArray.slice(0, -1);\n\n // Look for a part that looks like a provider package (not langchain/langchain_core)\n for (const part of namespace) {\n // Skip standard langchain packages\n if (\n part === \"langchain\" ||\n part === \"langchain_core\" ||\n part === \"chat_models\" ||\n part === \"runnables\" ||\n part === \"schema\"\n ) {\n continue;\n }\n\n // If it starts with \"langchain_\", extract the provider name\n // e.g., \"langchain_google_genai\" -> \"google-genai\"\n // e.g., \"langchain_deepseek\" -> \"deepseek\"\n if (part.startsWith(\"langchain_\")) {\n const providerName = part.slice(\"langchain_\".length);\n // Convert underscores to hyphens to match MODEL_PROVIDER_CONFIG keys\n return providerName.replace(/_/g, \"-\");\n }\n\n // Handle special cases for Google providers that need prefix\n if (part.includes(\"vertexai_web\")) {\n return \"google-vertexai-web\";\n } else if (part.includes(\"vertexai\")) {\n return \"google-vertexai\";\n } else if (part.includes(\"genai\") || part.includes(\"google_genai\")) {\n return \"google-genai\";\n }\n\n // For other provider-looking parts, use as-is with underscores converted to hyphens\n // e.g., \"openai\" -> \"openai\", \"anthropic\" -> \"anthropic\"\n if (\n !part.includes(\"langchain\") &&\n part !== \"chat_models\" &&\n part !== \"runnables\"\n ) {\n return part.replace(/_/g, \"-\");\n }\n }\n\n return undefined;\n}\n\n/**\n * Pull a prompt from the hub.\n * @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.\n * @param options.apiKey LangSmith API key to use when pulling the prompt\n * @param options.apiUrl LangSmith API URL to use when pulling the prompt\n * @param options.includeModel Whether to also instantiate and attach a model instance to the prompt,\n * if the prompt has associated model metadata. If set to true, invoking the resulting pulled prompt will\n * also invoke the instantiated model. You must have the appropriate LangChain integration package installed.\n * @param options.secrets A map of secrets to use when loading, e.g.\n * {'OPENAI_API_KEY': 'sk-...'}`.\n * If a secret is not found in the map, it will be loaded from the\n * environment if `secrets_from_env` is `True`. Should only be needed when\n * `includeModel` is `true`.\n * @param options.secretsFromEnv Whether to load secrets from environment variables.\n * Use with caution and only with trusted prompts.\n * @returns\n */\nexport async function pull<T extends Runnable>(\n ownerRepoCommit: string,\n options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n }\n) {\n const promptObject = await basePull(ownerRepoCommit, options);\n let modelClass;\n if (options?.includeModel) {\n const chatModelObject = isRunnableBinding(\n promptObject.manifest.kwargs?.last?.id\n )\n ? promptObject.manifest.kwargs?.last?.kwargs?.bound\n : promptObject.manifest.kwargs?.last;\n\n if (Array.isArray(chatModelObject?.id)) {\n const modelName = chatModelObject?.id.at(-1);\n\n if (modelName) {\n const modelProvider = inferModelProviderFromNamespace(\n chatModelObject.id\n );\n modelClass = await getChatModelByClassName(modelName, modelProvider);\n if (!modelClass) {\n console.warn(\n `Received unknown model name from prompt hub: \"${modelName}\"`\n );\n }\n }\n }\n }\n const loadedPrompt = await load<T>(\n JSON.stringify(promptObject.manifest),\n options?.secrets,\n generateOptionalImportMap(modelClass),\n generateModelImportMap(modelClass),\n options?.secretsFromEnv\n );\n return bindOutputSchema(loadedPrompt);\n}\n"],"mappings":";;;;;AAYA,SAAS,UAAU,GAAa,GAAsB;AACpD,KAAI,CAAC,MAAM,QAAQ,EAAE,IAAI,CAAC,MAAM,QAAQ,EAAE,CACxC,QAAO;AAET,KAAI,EAAE,WAAW,EAAE,OACjB,QAAO;AAET,MAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,IAC5B,KAAI,EAAE,OAAO,EAAE,GACb,QAAO;AAGX,QAAO;;AAGT,SAAS,kBAAkB,GAAsB;AAK/C,QAAO,CAHL;EAAC;EAAkB;EAAa;EAAkB,EAClD;EAAC;EAAa;EAAU;EAAY;EAAkB,CAErC,CAAC,MAAM,OAAO,UAAU,GAAG,GAAG,CAAC;;;;;;;;;;AAWpD,SAAgB,gCACd,SACoB;AACpB,KAAI,CAAC,MAAM,QAAQ,QAAQ,IAAI,QAAQ,SAAS,EAC9C;CAIF,MAAM,YAAY,QAAQ,MAAM,GAAG,GAAG;AAGtC,MAAK,MAAM,QAAQ,WAAW;AAE5B,MACE,SAAS,eACT,SAAS,oBACT,SAAS,iBACT,SAAS,eACT,SAAS,SAET;AAMF,MAAI,KAAK,WAAW,aAAa,CAG/B,QAFqB,KAAK,MAAM,GAEb,CAAC,QAAQ,MAAM,IAAI;AAIxC,MAAI,KAAK,SAAS,eAAe,CAC/B,QAAO;WACE,KAAK,SAAS,WAAW,CAClC,QAAO;WACE,KAAK,SAAS,QAAQ,IAAI,KAAK,SAAS,eAAe,CAChE,QAAO;AAKT,MACE,CAAC,KAAK,SAAS,YAAY,IAC3B,SAAS,iBACT,SAAS,YAET,QAAO,KAAK,QAAQ,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;AAwBpC,eAAsB,KACpB,iBACA,SAOA;CACA,MAAM,eAAe,MAAMA,aAAAA,SAAS,iBAAiB,QAAQ;CAC7D,IAAI;AACJ,KAAI,SAAS,cAAc;EACzB,MAAM,kBAAkB,kBACtB,aAAa,SAAS,QAAQ,MAAM,GACrC,GACG,aAAa,SAAS,QAAQ,MAAM,QAAQ,QAC5C,aAAa,SAAS,QAAQ;AAElC,MAAI,MAAM,QAAQ,iBAAiB,GAAG,EAAE;GACtC,MAAM,YAAY,iBAAiB,GAAG,GAAG,GAAG;AAE5C,OAAI,WAAW;AAIb,iBAAa,MAAMC,8BAAAA,wBAAwB,WAHrB,gCACpB,gBAAgB,GAEiD,CAAC;AACpE,QAAI,CAAC,WACH,SAAQ,KACN,iDAAiD,UAAU,GAC5D;;;;AAYT,QAAOC,aAAAA,iBAAiB,MAPGC,mBAAAA,KACzB,KAAK,UAAU,aAAa,SAAS,EACrC,SAAS,SACTC,aAAAA,0BAA0B,WAAW,EACrCC,aAAAA,uBAAuB,WAAW,EAClC,SAAS,eACV,CACoC"}
|
package/dist/hub/node.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.js","names":[],"sources":["../../src/hub/node.ts"],"sourcesContent":["import { Runnable } from \"@langchain/core/runnables\";\nimport {\n basePull,\n generateModelImportMap,\n generateOptionalImportMap,\n bindOutputSchema,\n} from \"./base.js\";\nimport { load } from \"../load/index.js\";\nimport { getChatModelByClassName } from \"../chat_models/universal.js\";\n\nexport { basePush as push } from \"./base.js\";\n\nfunction _idEquals(a: string[], b: string[]): boolean {\n if (!Array.isArray(a) || !Array.isArray(b)) {\n return false;\n }\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n\nfunction isRunnableBinding(a: string[]): boolean {\n const wellKnownIds = [\n [\"langchain_core\", \"runnables\", \"RunnableBinding\"],\n [\"langchain\", \"schema\", \"runnable\", \"RunnableBinding\"],\n ];\n return wellKnownIds.some((id) => _idEquals(a, id));\n}\n\n/**\n * Infer modelProvider from the id namespace to avoid className collisions.\n * For non-langchain packages, extracts the provider name from the namespace.\n * e.g., [\"langchain\", \"chat_models\", \"vertexai\", \"ChatVertexAI\"] -> \"google-vertexai\"\n * e.g., [\"langchain_deepseek\", \"chat_models\", \"ChatDeepSeek\"] -> \"deepseek\"\n * @param idArray The full id array from the manifest\n * @returns The inferred modelProvider key or undefined\n */\nexport function inferModelProviderFromNamespace(\n idArray: string[]\n): string | undefined {\n if (!Array.isArray(idArray) || idArray.length < 2) {\n return undefined;\n }\n\n // Check namespace parts (excluding the className at the end)\n const namespace = idArray.slice(0, -1);\n\n // Look for a part that looks like a provider package (not langchain/langchain_core)\n for (const part of namespace) {\n // Skip standard langchain packages\n if (\n part === \"langchain\" ||\n part === \"langchain_core\" ||\n part === \"chat_models\" ||\n part === \"runnables\" ||\n part === \"schema\"\n ) {\n continue;\n }\n\n // If it starts with \"langchain_\", extract the provider name\n // e.g., \"langchain_google_genai\" -> \"google-genai\"\n // e.g., \"langchain_deepseek\" -> \"deepseek\"\n if (part.startsWith(\"langchain_\")) {\n const providerName = part.slice(\"langchain_\".length);\n // Convert underscores to hyphens to match MODEL_PROVIDER_CONFIG keys\n return providerName.replace(/_/g, \"-\");\n }\n\n // Handle special cases for Google providers that need prefix\n if (part.includes(\"vertexai_web\")) {\n return \"google-vertexai-web\";\n } else if (part.includes(\"vertexai\")) {\n return \"google-vertexai\";\n } else if (part.includes(\"genai\") || part.includes(\"google_genai\")) {\n return \"google-genai\";\n }\n\n // For other provider-looking parts, use as-is with underscores converted to hyphens\n // e.g., \"openai\" -> \"openai\", \"anthropic\" -> \"anthropic\"\n if (\n !part.includes(\"langchain\") &&\n part !== \"chat_models\" &&\n part !== \"runnables\"\n ) {\n return part.replace(/_/g, \"-\");\n }\n }\n\n return undefined;\n}\n\n/**\n * Pull a prompt from the hub.\n * @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.\n * @param options.apiKey LangSmith API key to use when pulling the prompt\n * @param options.apiUrl LangSmith API URL to use when pulling the prompt\n * @param options.includeModel Whether to also instantiate and attach a model instance to the prompt,\n * if the prompt has associated model metadata. If set to true, invoking the resulting pulled prompt will\n * also invoke the instantiated model. You must have the appropriate LangChain integration package installed.\n * @param options.secrets A map of secrets to use when loading, e.g.\n * {'OPENAI_API_KEY': 'sk-...'}`.\n * If a secret is not found in the map, it will be loaded from the\n * environment if `secrets_from_env` is `True`. Should only be needed when\n * `includeModel` is `true`.\n * @param options.secretsFromEnv Whether to load secrets from environment variables.\n * Use with caution and only with trusted prompts.\n * @returns\n */\nexport async function pull<T extends Runnable>(\n ownerRepoCommit: string,\n options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n }\n) {\n const promptObject = await basePull(ownerRepoCommit, options);\n let modelClass;\n if (options?.includeModel) {\n const chatModelObject = isRunnableBinding(\n promptObject.manifest.kwargs?.last?.id\n )\n ? promptObject.manifest.kwargs?.last?.kwargs?.bound\n : promptObject.manifest.kwargs?.last;\n\n if (Array.isArray(chatModelObject?.id)) {\n const modelName = chatModelObject?.id.at(-1);\n\n if (modelName) {\n const modelProvider = inferModelProviderFromNamespace(\n chatModelObject.id\n );\n modelClass = await getChatModelByClassName(modelName, modelProvider);\n if (!modelClass) {\n console.warn(\n `Received unknown model name from prompt hub: \"${modelName}\"`\n );\n }\n }\n }\n }\n const loadedPrompt = await load<T>(\n JSON.stringify(promptObject.manifest),\n options?.secrets,\n generateOptionalImportMap(modelClass),\n generateModelImportMap(modelClass),\n options?.secretsFromEnv\n );\n return bindOutputSchema(loadedPrompt);\n}\n"],"mappings":";;;;AAYA,SAAS,UAAU,GAAa,GAAsB;AACpD,KAAI,CAAC,MAAM,QAAQ,EAAE,IAAI,CAAC,MAAM,QAAQ,EAAE,CACxC,QAAO;AAET,KAAI,EAAE,WAAW,EAAE,OACjB,QAAO;AAET,MAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,IAC5B,KAAI,EAAE,OAAO,EAAE,GACb,QAAO;AAGX,QAAO;;AAGT,SAAS,kBAAkB,GAAsB;AAK/C,
|
|
1
|
+
{"version":3,"file":"node.js","names":[],"sources":["../../src/hub/node.ts"],"sourcesContent":["import { Runnable } from \"@langchain/core/runnables\";\nimport {\n basePull,\n generateModelImportMap,\n generateOptionalImportMap,\n bindOutputSchema,\n} from \"./base.js\";\nimport { load } from \"../load/index.js\";\nimport { getChatModelByClassName } from \"../chat_models/universal.js\";\n\nexport { basePush as push } from \"./base.js\";\n\nfunction _idEquals(a: string[], b: string[]): boolean {\n if (!Array.isArray(a) || !Array.isArray(b)) {\n return false;\n }\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n\nfunction isRunnableBinding(a: string[]): boolean {\n const wellKnownIds = [\n [\"langchain_core\", \"runnables\", \"RunnableBinding\"],\n [\"langchain\", \"schema\", \"runnable\", \"RunnableBinding\"],\n ];\n return wellKnownIds.some((id) => _idEquals(a, id));\n}\n\n/**\n * Infer modelProvider from the id namespace to avoid className collisions.\n * For non-langchain packages, extracts the provider name from the namespace.\n * e.g., [\"langchain\", \"chat_models\", \"vertexai\", \"ChatVertexAI\"] -> \"google-vertexai\"\n * e.g., [\"langchain_deepseek\", \"chat_models\", \"ChatDeepSeek\"] -> \"deepseek\"\n * @param idArray The full id array from the manifest\n * @returns The inferred modelProvider key or undefined\n */\nexport function inferModelProviderFromNamespace(\n idArray: string[]\n): string | undefined {\n if (!Array.isArray(idArray) || idArray.length < 2) {\n return undefined;\n }\n\n // Check namespace parts (excluding the className at the end)\n const namespace = idArray.slice(0, -1);\n\n // Look for a part that looks like a provider package (not langchain/langchain_core)\n for (const part of namespace) {\n // Skip standard langchain packages\n if (\n part === \"langchain\" ||\n part === \"langchain_core\" ||\n part === \"chat_models\" ||\n part === \"runnables\" ||\n part === \"schema\"\n ) {\n continue;\n }\n\n // If it starts with \"langchain_\", extract the provider name\n // e.g., \"langchain_google_genai\" -> \"google-genai\"\n // e.g., \"langchain_deepseek\" -> \"deepseek\"\n if (part.startsWith(\"langchain_\")) {\n const providerName = part.slice(\"langchain_\".length);\n // Convert underscores to hyphens to match MODEL_PROVIDER_CONFIG keys\n return providerName.replace(/_/g, \"-\");\n }\n\n // Handle special cases for Google providers that need prefix\n if (part.includes(\"vertexai_web\")) {\n return \"google-vertexai-web\";\n } else if (part.includes(\"vertexai\")) {\n return \"google-vertexai\";\n } else if (part.includes(\"genai\") || part.includes(\"google_genai\")) {\n return \"google-genai\";\n }\n\n // For other provider-looking parts, use as-is with underscores converted to hyphens\n // e.g., \"openai\" -> \"openai\", \"anthropic\" -> \"anthropic\"\n if (\n !part.includes(\"langchain\") &&\n part !== \"chat_models\" &&\n part !== \"runnables\"\n ) {\n return part.replace(/_/g, \"-\");\n }\n }\n\n return undefined;\n}\n\n/**\n * Pull a prompt from the hub.\n * @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.\n * @param options.apiKey LangSmith API key to use when pulling the prompt\n * @param options.apiUrl LangSmith API URL to use when pulling the prompt\n * @param options.includeModel Whether to also instantiate and attach a model instance to the prompt,\n * if the prompt has associated model metadata. If set to true, invoking the resulting pulled prompt will\n * also invoke the instantiated model. You must have the appropriate LangChain integration package installed.\n * @param options.secrets A map of secrets to use when loading, e.g.\n * {'OPENAI_API_KEY': 'sk-...'}`.\n * If a secret is not found in the map, it will be loaded from the\n * environment if `secrets_from_env` is `True`. Should only be needed when\n * `includeModel` is `true`.\n * @param options.secretsFromEnv Whether to load secrets from environment variables.\n * Use with caution and only with trusted prompts.\n * @returns\n */\nexport async function pull<T extends Runnable>(\n ownerRepoCommit: string,\n options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n }\n) {\n const promptObject = await basePull(ownerRepoCommit, options);\n let modelClass;\n if (options?.includeModel) {\n const chatModelObject = isRunnableBinding(\n promptObject.manifest.kwargs?.last?.id\n )\n ? promptObject.manifest.kwargs?.last?.kwargs?.bound\n : promptObject.manifest.kwargs?.last;\n\n if (Array.isArray(chatModelObject?.id)) {\n const modelName = chatModelObject?.id.at(-1);\n\n if (modelName) {\n const modelProvider = inferModelProviderFromNamespace(\n chatModelObject.id\n );\n modelClass = await getChatModelByClassName(modelName, modelProvider);\n if (!modelClass) {\n console.warn(\n `Received unknown model name from prompt hub: \"${modelName}\"`\n );\n }\n }\n }\n }\n const loadedPrompt = await load<T>(\n JSON.stringify(promptObject.manifest),\n options?.secrets,\n generateOptionalImportMap(modelClass),\n generateModelImportMap(modelClass),\n options?.secretsFromEnv\n );\n return bindOutputSchema(loadedPrompt);\n}\n"],"mappings":";;;;AAYA,SAAS,UAAU,GAAa,GAAsB;AACpD,KAAI,CAAC,MAAM,QAAQ,EAAE,IAAI,CAAC,MAAM,QAAQ,EAAE,CACxC,QAAO;AAET,KAAI,EAAE,WAAW,EAAE,OACjB,QAAO;AAET,MAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,IAC5B,KAAI,EAAE,OAAO,EAAE,GACb,QAAO;AAGX,QAAO;;AAGT,SAAS,kBAAkB,GAAsB;AAK/C,QAAO,CAHL;EAAC;EAAkB;EAAa;EAAkB,EAClD;EAAC;EAAa;EAAU;EAAY;EAAkB,CAErC,CAAC,MAAM,OAAO,UAAU,GAAG,GAAG,CAAC;;;;;;;;;;AAWpD,SAAgB,gCACd,SACoB;AACpB,KAAI,CAAC,MAAM,QAAQ,QAAQ,IAAI,QAAQ,SAAS,EAC9C;CAIF,MAAM,YAAY,QAAQ,MAAM,GAAG,GAAG;AAGtC,MAAK,MAAM,QAAQ,WAAW;AAE5B,MACE,SAAS,eACT,SAAS,oBACT,SAAS,iBACT,SAAS,eACT,SAAS,SAET;AAMF,MAAI,KAAK,WAAW,aAAa,CAG/B,QAFqB,KAAK,MAAM,GAEb,CAAC,QAAQ,MAAM,IAAI;AAIxC,MAAI,KAAK,SAAS,eAAe,CAC/B,QAAO;WACE,KAAK,SAAS,WAAW,CAClC,QAAO;WACE,KAAK,SAAS,QAAQ,IAAI,KAAK,SAAS,eAAe,CAChE,QAAO;AAKT,MACE,CAAC,KAAK,SAAS,YAAY,IAC3B,SAAS,iBACT,SAAS,YAET,QAAO,KAAK,QAAQ,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;AAwBpC,eAAsB,KACpB,iBACA,SAOA;CACA,MAAM,eAAe,MAAM,SAAS,iBAAiB,QAAQ;CAC7D,IAAI;AACJ,KAAI,SAAS,cAAc;EACzB,MAAM,kBAAkB,kBACtB,aAAa,SAAS,QAAQ,MAAM,GACrC,GACG,aAAa,SAAS,QAAQ,MAAM,QAAQ,QAC5C,aAAa,SAAS,QAAQ;AAElC,MAAI,MAAM,QAAQ,iBAAiB,GAAG,EAAE;GACtC,MAAM,YAAY,iBAAiB,GAAG,GAAG,GAAG;AAE5C,OAAI,WAAW;AAIb,iBAAa,MAAM,wBAAwB,WAHrB,gCACpB,gBAAgB,GAEiD,CAAC;AACpE,QAAI,CAAC,WACH,SAAQ,KACN,iDAAiD,UAAU,GAC5D;;;;AAYT,QAAO,iBAAiB,MAPG,KACzB,KAAK,UAAU,aAAa,SAAS,EACrC,SAAS,SACT,0BAA0B,WAAW,EACrC,uBAAuB,WAAW,EAClC,SAAS,eACV,CACoC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buffer_memory.cjs","names":["BaseChatMemory"],"sources":["../../src/memory/buffer_memory.ts"],"sourcesContent":["import { InputValues, MemoryVariables } from \"@langchain/core/memory\";\nimport { getBufferString } from \"@langchain/core/messages\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the input parameters of the `BufferMemory` class.\n */\nexport interface BufferMemoryInput extends BaseChatMemoryInput {\n humanPrefix?: string;\n aiPrefix?: string;\n memoryKey?: string;\n}\n\n/**\n * The `BufferMemory` class is a type of memory component used for storing\n * and managing previous chat messages. It is a wrapper around\n * `ChatMessageHistory` that extracts the messages into an input variable.\n * This class is particularly useful in applications like chatbots where\n * it is essential to remember previous interactions. Note: The memory\n * instance represents the history of a single conversation. Therefore, it\n * is not recommended to share the same history or memory instance between\n * two different chains. If you deploy your LangChain app on a serverless\n * environment, do not store memory instances in a variable, as your\n * hosting provider may reset it by the next time the function is called.\n * @example\n * ```typescript\n * // Initialize the memory to store chat history and set up the language model with a specific temperature.\n * const memory = new BufferMemory({ memoryKey: \"chat_history\" });\n * const model = new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0.9 });\n *\n * // Create a prompt template for a friendly conversation between a human and an AI.\n * const prompt =\n * PromptTemplate.fromTemplate(`The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n *\n * Current conversation:\n * {chat_history}\n * Human: {input}\n * AI:`);\n *\n * // Set up the chain with the language model, prompt, and memory.\n * const chain = new LLMChain({ llm: model, prompt, memory });\n *\n * // Example usage of the chain to continue the conversation.\n * // The `call` method sends the input to the model and returns the AI's response.\n * const res = await chain.call({ input: \"Hi! I'm Jim.\" });\n * console.log({ res });\n *\n * ```\n */\nexport class BufferMemory extends BaseChatMemory implements BufferMemoryInput {\n humanPrefix = \"Human\";\n\n aiPrefix = \"AI\";\n\n memoryKey = \"history\";\n\n constructor(fields?: BufferMemoryInput) {\n super({\n chatHistory: fields?.chatHistory,\n returnMessages: fields?.returnMessages ?? false,\n inputKey: fields?.inputKey,\n outputKey: fields?.outputKey,\n });\n this.humanPrefix = fields?.humanPrefix ?? this.humanPrefix;\n this.aiPrefix = fields?.aiPrefix ?? this.aiPrefix;\n this.memoryKey = fields?.memoryKey ?? this.memoryKey;\n }\n\n get memoryKeys() {\n return [this.memoryKey];\n }\n\n /**\n * Loads the memory variables. It takes an `InputValues` object as a\n * parameter and returns a `Promise` that resolves with a\n * `MemoryVariables` object.\n * @param _values `InputValues` object.\n * @returns A `Promise` that resolves with a `MemoryVariables` object.\n */\n async loadMemoryVariables(_values: InputValues): Promise<MemoryVariables> {\n const messages = await this.chatHistory.getMessages();\n if (this.returnMessages) {\n const result = {\n [this.memoryKey]: messages,\n };\n return result;\n }\n const result = {\n [this.memoryKey]: getBufferString(\n messages,\n this.humanPrefix,\n this.aiPrefix\n ),\n };\n return result;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,IAAa,eAAb,cAAkCA,2BAAAA,eAA4C;CAC5E,cAAc;CAEd,WAAW;CAEX,YAAY;CAEZ,YAAY,QAA4B;AACtC,QAAM;GACJ,aAAa,QAAQ;GACrB,gBAAgB,QAAQ,kBAAkB;GAC1C,UAAU,QAAQ;GAClB,WAAW,QAAQ;GACpB,CAAC;AACF,OAAK,cAAc,QAAQ,eAAe,KAAK;AAC/C,OAAK,WAAW,QAAQ,YAAY,KAAK;AACzC,OAAK,YAAY,QAAQ,aAAa,KAAK;;CAG7C,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,UAAU;;;;;;;;;CAUzB,MAAM,oBAAoB,SAAgD;EACxE,MAAM,WAAW,MAAM,KAAK,YAAY,aAAa;AACrD,MAAI,KAAK,eAIP,
|
|
1
|
+
{"version":3,"file":"buffer_memory.cjs","names":["BaseChatMemory"],"sources":["../../src/memory/buffer_memory.ts"],"sourcesContent":["import { InputValues, MemoryVariables } from \"@langchain/core/memory\";\nimport { getBufferString } from \"@langchain/core/messages\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the input parameters of the `BufferMemory` class.\n */\nexport interface BufferMemoryInput extends BaseChatMemoryInput {\n humanPrefix?: string;\n aiPrefix?: string;\n memoryKey?: string;\n}\n\n/**\n * The `BufferMemory` class is a type of memory component used for storing\n * and managing previous chat messages. It is a wrapper around\n * `ChatMessageHistory` that extracts the messages into an input variable.\n * This class is particularly useful in applications like chatbots where\n * it is essential to remember previous interactions. Note: The memory\n * instance represents the history of a single conversation. Therefore, it\n * is not recommended to share the same history or memory instance between\n * two different chains. If you deploy your LangChain app on a serverless\n * environment, do not store memory instances in a variable, as your\n * hosting provider may reset it by the next time the function is called.\n * @example\n * ```typescript\n * // Initialize the memory to store chat history and set up the language model with a specific temperature.\n * const memory = new BufferMemory({ memoryKey: \"chat_history\" });\n * const model = new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0.9 });\n *\n * // Create a prompt template for a friendly conversation between a human and an AI.\n * const prompt =\n * PromptTemplate.fromTemplate(`The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n *\n * Current conversation:\n * {chat_history}\n * Human: {input}\n * AI:`);\n *\n * // Set up the chain with the language model, prompt, and memory.\n * const chain = new LLMChain({ llm: model, prompt, memory });\n *\n * // Example usage of the chain to continue the conversation.\n * // The `call` method sends the input to the model and returns the AI's response.\n * const res = await chain.call({ input: \"Hi! I'm Jim.\" });\n * console.log({ res });\n *\n * ```\n */\nexport class BufferMemory extends BaseChatMemory implements BufferMemoryInput {\n humanPrefix = \"Human\";\n\n aiPrefix = \"AI\";\n\n memoryKey = \"history\";\n\n constructor(fields?: BufferMemoryInput) {\n super({\n chatHistory: fields?.chatHistory,\n returnMessages: fields?.returnMessages ?? false,\n inputKey: fields?.inputKey,\n outputKey: fields?.outputKey,\n });\n this.humanPrefix = fields?.humanPrefix ?? this.humanPrefix;\n this.aiPrefix = fields?.aiPrefix ?? this.aiPrefix;\n this.memoryKey = fields?.memoryKey ?? this.memoryKey;\n }\n\n get memoryKeys() {\n return [this.memoryKey];\n }\n\n /**\n * Loads the memory variables. It takes an `InputValues` object as a\n * parameter and returns a `Promise` that resolves with a\n * `MemoryVariables` object.\n * @param _values `InputValues` object.\n * @returns A `Promise` that resolves with a `MemoryVariables` object.\n */\n async loadMemoryVariables(_values: InputValues): Promise<MemoryVariables> {\n const messages = await this.chatHistory.getMessages();\n if (this.returnMessages) {\n const result = {\n [this.memoryKey]: messages,\n };\n return result;\n }\n const result = {\n [this.memoryKey]: getBufferString(\n messages,\n this.humanPrefix,\n this.aiPrefix\n ),\n };\n return result;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,IAAa,eAAb,cAAkCA,2BAAAA,eAA4C;CAC5E,cAAc;CAEd,WAAW;CAEX,YAAY;CAEZ,YAAY,QAA4B;AACtC,QAAM;GACJ,aAAa,QAAQ;GACrB,gBAAgB,QAAQ,kBAAkB;GAC1C,UAAU,QAAQ;GAClB,WAAW,QAAQ;GACpB,CAAC;AACF,OAAK,cAAc,QAAQ,eAAe,KAAK;AAC/C,OAAK,WAAW,QAAQ,YAAY,KAAK;AACzC,OAAK,YAAY,QAAQ,aAAa,KAAK;;CAG7C,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,UAAU;;;;;;;;;CAUzB,MAAM,oBAAoB,SAAgD;EACxE,MAAM,WAAW,MAAM,KAAK,YAAY,aAAa;AACrD,MAAI,KAAK,eAIP,QAAO,GAFJ,KAAK,YAAY,UAEP;AASf,SAAO,GANJ,KAAK,aAAA,GAAA,yBAAA,iBACJ,UACA,KAAK,aACL,KAAK,SACN,EAEU"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buffer_memory.js","names":[],"sources":["../../src/memory/buffer_memory.ts"],"sourcesContent":["import { InputValues, MemoryVariables } from \"@langchain/core/memory\";\nimport { getBufferString } from \"@langchain/core/messages\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the input parameters of the `BufferMemory` class.\n */\nexport interface BufferMemoryInput extends BaseChatMemoryInput {\n humanPrefix?: string;\n aiPrefix?: string;\n memoryKey?: string;\n}\n\n/**\n * The `BufferMemory` class is a type of memory component used for storing\n * and managing previous chat messages. It is a wrapper around\n * `ChatMessageHistory` that extracts the messages into an input variable.\n * This class is particularly useful in applications like chatbots where\n * it is essential to remember previous interactions. Note: The memory\n * instance represents the history of a single conversation. Therefore, it\n * is not recommended to share the same history or memory instance between\n * two different chains. If you deploy your LangChain app on a serverless\n * environment, do not store memory instances in a variable, as your\n * hosting provider may reset it by the next time the function is called.\n * @example\n * ```typescript\n * // Initialize the memory to store chat history and set up the language model with a specific temperature.\n * const memory = new BufferMemory({ memoryKey: \"chat_history\" });\n * const model = new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0.9 });\n *\n * // Create a prompt template for a friendly conversation between a human and an AI.\n * const prompt =\n * PromptTemplate.fromTemplate(`The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n *\n * Current conversation:\n * {chat_history}\n * Human: {input}\n * AI:`);\n *\n * // Set up the chain with the language model, prompt, and memory.\n * const chain = new LLMChain({ llm: model, prompt, memory });\n *\n * // Example usage of the chain to continue the conversation.\n * // The `call` method sends the input to the model and returns the AI's response.\n * const res = await chain.call({ input: \"Hi! I'm Jim.\" });\n * console.log({ res });\n *\n * ```\n */\nexport class BufferMemory extends BaseChatMemory implements BufferMemoryInput {\n humanPrefix = \"Human\";\n\n aiPrefix = \"AI\";\n\n memoryKey = \"history\";\n\n constructor(fields?: BufferMemoryInput) {\n super({\n chatHistory: fields?.chatHistory,\n returnMessages: fields?.returnMessages ?? false,\n inputKey: fields?.inputKey,\n outputKey: fields?.outputKey,\n });\n this.humanPrefix = fields?.humanPrefix ?? this.humanPrefix;\n this.aiPrefix = fields?.aiPrefix ?? this.aiPrefix;\n this.memoryKey = fields?.memoryKey ?? this.memoryKey;\n }\n\n get memoryKeys() {\n return [this.memoryKey];\n }\n\n /**\n * Loads the memory variables. It takes an `InputValues` object as a\n * parameter and returns a `Promise` that resolves with a\n * `MemoryVariables` object.\n * @param _values `InputValues` object.\n * @returns A `Promise` that resolves with a `MemoryVariables` object.\n */\n async loadMemoryVariables(_values: InputValues): Promise<MemoryVariables> {\n const messages = await this.chatHistory.getMessages();\n if (this.returnMessages) {\n const result = {\n [this.memoryKey]: messages,\n };\n return result;\n }\n const result = {\n [this.memoryKey]: getBufferString(\n messages,\n this.humanPrefix,\n this.aiPrefix\n ),\n };\n return result;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,IAAa,eAAb,cAAkC,eAA4C;CAC5E,cAAc;CAEd,WAAW;CAEX,YAAY;CAEZ,YAAY,QAA4B;AACtC,QAAM;GACJ,aAAa,QAAQ;GACrB,gBAAgB,QAAQ,kBAAkB;GAC1C,UAAU,QAAQ;GAClB,WAAW,QAAQ;GACpB,CAAC;AACF,OAAK,cAAc,QAAQ,eAAe,KAAK;AAC/C,OAAK,WAAW,QAAQ,YAAY,KAAK;AACzC,OAAK,YAAY,QAAQ,aAAa,KAAK;;CAG7C,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,UAAU;;;;;;;;;CAUzB,MAAM,oBAAoB,SAAgD;EACxE,MAAM,WAAW,MAAM,KAAK,YAAY,aAAa;AACrD,MAAI,KAAK,eAIP,
|
|
1
|
+
{"version":3,"file":"buffer_memory.js","names":[],"sources":["../../src/memory/buffer_memory.ts"],"sourcesContent":["import { InputValues, MemoryVariables } from \"@langchain/core/memory\";\nimport { getBufferString } from \"@langchain/core/messages\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the input parameters of the `BufferMemory` class.\n */\nexport interface BufferMemoryInput extends BaseChatMemoryInput {\n humanPrefix?: string;\n aiPrefix?: string;\n memoryKey?: string;\n}\n\n/**\n * The `BufferMemory` class is a type of memory component used for storing\n * and managing previous chat messages. It is a wrapper around\n * `ChatMessageHistory` that extracts the messages into an input variable.\n * This class is particularly useful in applications like chatbots where\n * it is essential to remember previous interactions. Note: The memory\n * instance represents the history of a single conversation. Therefore, it\n * is not recommended to share the same history or memory instance between\n * two different chains. If you deploy your LangChain app on a serverless\n * environment, do not store memory instances in a variable, as your\n * hosting provider may reset it by the next time the function is called.\n * @example\n * ```typescript\n * // Initialize the memory to store chat history and set up the language model with a specific temperature.\n * const memory = new BufferMemory({ memoryKey: \"chat_history\" });\n * const model = new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0.9 });\n *\n * // Create a prompt template for a friendly conversation between a human and an AI.\n * const prompt =\n * PromptTemplate.fromTemplate(`The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n *\n * Current conversation:\n * {chat_history}\n * Human: {input}\n * AI:`);\n *\n * // Set up the chain with the language model, prompt, and memory.\n * const chain = new LLMChain({ llm: model, prompt, memory });\n *\n * // Example usage of the chain to continue the conversation.\n * // The `call` method sends the input to the model and returns the AI's response.\n * const res = await chain.call({ input: \"Hi! I'm Jim.\" });\n * console.log({ res });\n *\n * ```\n */\nexport class BufferMemory extends BaseChatMemory implements BufferMemoryInput {\n humanPrefix = \"Human\";\n\n aiPrefix = \"AI\";\n\n memoryKey = \"history\";\n\n constructor(fields?: BufferMemoryInput) {\n super({\n chatHistory: fields?.chatHistory,\n returnMessages: fields?.returnMessages ?? false,\n inputKey: fields?.inputKey,\n outputKey: fields?.outputKey,\n });\n this.humanPrefix = fields?.humanPrefix ?? this.humanPrefix;\n this.aiPrefix = fields?.aiPrefix ?? this.aiPrefix;\n this.memoryKey = fields?.memoryKey ?? this.memoryKey;\n }\n\n get memoryKeys() {\n return [this.memoryKey];\n }\n\n /**\n * Loads the memory variables. It takes an `InputValues` object as a\n * parameter and returns a `Promise` that resolves with a\n * `MemoryVariables` object.\n * @param _values `InputValues` object.\n * @returns A `Promise` that resolves with a `MemoryVariables` object.\n */\n async loadMemoryVariables(_values: InputValues): Promise<MemoryVariables> {\n const messages = await this.chatHistory.getMessages();\n if (this.returnMessages) {\n const result = {\n [this.memoryKey]: messages,\n };\n return result;\n }\n const result = {\n [this.memoryKey]: getBufferString(\n messages,\n this.humanPrefix,\n this.aiPrefix\n ),\n };\n return result;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,IAAa,eAAb,cAAkC,eAA4C;CAC5E,cAAc;CAEd,WAAW;CAEX,YAAY;CAEZ,YAAY,QAA4B;AACtC,QAAM;GACJ,aAAa,QAAQ;GACrB,gBAAgB,QAAQ,kBAAkB;GAC1C,UAAU,QAAQ;GAClB,WAAW,QAAQ;GACpB,CAAC;AACF,OAAK,cAAc,QAAQ,eAAe,KAAK;AAC/C,OAAK,WAAW,QAAQ,YAAY,KAAK;AACzC,OAAK,YAAY,QAAQ,aAAa,KAAK;;CAG7C,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,UAAU;;;;;;;;;CAUzB,MAAM,oBAAoB,SAAgD;EACxE,MAAM,WAAW,MAAM,KAAK,YAAY,aAAa;AACrD,MAAI,KAAK,eAIP,QAAO,GAFJ,KAAK,YAAY,UAEP;AASf,SAAO,GANJ,KAAK,YAAY,gBAChB,UACA,KAAK,aACL,KAAK,SACN,EAEU"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buffer_token_memory.cjs","names":["BaseChatMemory"],"sources":["../../src/memory/buffer_token_memory.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport {\n InputValues,\n MemoryVariables,\n OutputValues,\n} from \"@langchain/core/memory\";\nimport { getBufferString } from \"@langchain/core/messages\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the input parameters of the `BufferTokenMemory` class.\n */\n\nexport interface ConversationTokenBufferMemoryInput extends BaseChatMemoryInput {\n /* Prefix for human messages in the buffer. */\n humanPrefix?: string;\n\n /* Prefix for AI messages in the buffer. */\n aiPrefix?: string;\n\n /* The LLM for this instance. */\n llm: BaseLanguageModelInterface;\n\n /* Memory key for buffer instance. */\n memoryKey?: string;\n\n /* Maximmum number of tokens allowed in the buffer. */\n maxTokenLimit?: number;\n}\n\n/**\n * Class that represents a conversation chat memory with a token buffer.\n * It extends the `BaseChatMemory` class and implements the\n * `ConversationTokenBufferMemoryInput` interface.\n * @example\n * ```typescript\n * const memory = new ConversationTokenBufferMemory({\n * llm: new ChatOpenAI({ model: \"gpt-4o-mini\" }),\n * maxTokenLimit: 10,\n * });\n *\n * // Save conversation context\n * await memory.saveContext({ input: \"hi\" }, { output: \"whats up\" });\n * await memory.saveContext({ input: \"not much you\" }, { output: \"not much\" });\n *\n * // Load memory variables\n * const result = await memory.loadMemoryVariables({});\n * console.log(result);\n * ```\n */\n\nexport class ConversationTokenBufferMemory\n extends BaseChatMemory\n implements ConversationTokenBufferMemoryInput\n{\n humanPrefix = \"Human\";\n\n aiPrefix = \"AI\";\n\n memoryKey = \"history\";\n\n maxTokenLimit = 2000; // Default max token limit of 2000 which can be overridden\n\n llm: BaseLanguageModelInterface;\n\n constructor(fields: ConversationTokenBufferMemoryInput) {\n super(fields);\n this.llm = fields.llm;\n this.humanPrefix = fields?.humanPrefix ?? this.humanPrefix;\n this.aiPrefix = fields?.aiPrefix ?? this.aiPrefix;\n this.memoryKey = fields?.memoryKey ?? this.memoryKey;\n this.maxTokenLimit = fields?.maxTokenLimit ?? this.maxTokenLimit;\n }\n\n get memoryKeys() {\n return [this.memoryKey];\n }\n\n /**\n * Loads the memory variables. It takes an `InputValues` object as a\n * parameter and returns a `Promise` that resolves with a\n * `MemoryVariables` object.\n * @param _values `InputValues` object.\n * @returns A `Promise` that resolves with a `MemoryVariables` object.\n */\n async loadMemoryVariables(_values: InputValues): Promise<MemoryVariables> {\n const messages = await this.chatHistory.getMessages();\n if (this.returnMessages) {\n const result = {\n [this.memoryKey]: messages,\n };\n return result;\n }\n const result = {\n [this.memoryKey]: getBufferString(\n messages,\n this.humanPrefix,\n this.aiPrefix\n ),\n };\n return result;\n }\n\n /**\n * Saves the context from this conversation to buffer. If the amount\n * of tokens required to save the buffer exceeds MAX_TOKEN_LIMIT,\n * prune it.\n */\n async saveContext(inputValues: InputValues, outputValues: OutputValues) {\n await super.saveContext(inputValues, outputValues);\n\n // Prune buffer if it exceeds the max token limit set for this instance.\n const buffer = await this.chatHistory.getMessages();\n let currBufferLength = await this.llm.getNumTokens(\n getBufferString(buffer, this.humanPrefix, this.aiPrefix)\n );\n\n if (currBufferLength > this.maxTokenLimit) {\n const prunedMemory = [];\n while (currBufferLength > this.maxTokenLimit) {\n prunedMemory.push(buffer.shift());\n currBufferLength = await this.llm.getNumTokens(\n getBufferString(buffer, this.humanPrefix, this.aiPrefix)\n );\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAmDA,IAAa,gCAAb,cACUA,2BAAAA,eAEV;CACE,cAAc;CAEd,WAAW;CAEX,YAAY;CAEZ,gBAAgB;CAEhB;CAEA,YAAY,QAA4C;AACtD,QAAM,OAAO;AACb,OAAK,MAAM,OAAO;AAClB,OAAK,cAAc,QAAQ,eAAe,KAAK;AAC/C,OAAK,WAAW,QAAQ,YAAY,KAAK;AACzC,OAAK,YAAY,QAAQ,aAAa,KAAK;AAC3C,OAAK,gBAAgB,QAAQ,iBAAiB,KAAK;;CAGrD,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,UAAU;;;;;;;;;CAUzB,MAAM,oBAAoB,SAAgD;EACxE,MAAM,WAAW,MAAM,KAAK,YAAY,aAAa;AACrD,MAAI,KAAK,eAIP,
|
|
1
|
+
{"version":3,"file":"buffer_token_memory.cjs","names":["BaseChatMemory"],"sources":["../../src/memory/buffer_token_memory.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport {\n InputValues,\n MemoryVariables,\n OutputValues,\n} from \"@langchain/core/memory\";\nimport { getBufferString } from \"@langchain/core/messages\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the input parameters of the `BufferTokenMemory` class.\n */\n\nexport interface ConversationTokenBufferMemoryInput extends BaseChatMemoryInput {\n /* Prefix for human messages in the buffer. */\n humanPrefix?: string;\n\n /* Prefix for AI messages in the buffer. */\n aiPrefix?: string;\n\n /* The LLM for this instance. */\n llm: BaseLanguageModelInterface;\n\n /* Memory key for buffer instance. */\n memoryKey?: string;\n\n /* Maximmum number of tokens allowed in the buffer. */\n maxTokenLimit?: number;\n}\n\n/**\n * Class that represents a conversation chat memory with a token buffer.\n * It extends the `BaseChatMemory` class and implements the\n * `ConversationTokenBufferMemoryInput` interface.\n * @example\n * ```typescript\n * const memory = new ConversationTokenBufferMemory({\n * llm: new ChatOpenAI({ model: \"gpt-4o-mini\" }),\n * maxTokenLimit: 10,\n * });\n *\n * // Save conversation context\n * await memory.saveContext({ input: \"hi\" }, { output: \"whats up\" });\n * await memory.saveContext({ input: \"not much you\" }, { output: \"not much\" });\n *\n * // Load memory variables\n * const result = await memory.loadMemoryVariables({});\n * console.log(result);\n * ```\n */\n\nexport class ConversationTokenBufferMemory\n extends BaseChatMemory\n implements ConversationTokenBufferMemoryInput\n{\n humanPrefix = \"Human\";\n\n aiPrefix = \"AI\";\n\n memoryKey = \"history\";\n\n maxTokenLimit = 2000; // Default max token limit of 2000 which can be overridden\n\n llm: BaseLanguageModelInterface;\n\n constructor(fields: ConversationTokenBufferMemoryInput) {\n super(fields);\n this.llm = fields.llm;\n this.humanPrefix = fields?.humanPrefix ?? this.humanPrefix;\n this.aiPrefix = fields?.aiPrefix ?? this.aiPrefix;\n this.memoryKey = fields?.memoryKey ?? this.memoryKey;\n this.maxTokenLimit = fields?.maxTokenLimit ?? this.maxTokenLimit;\n }\n\n get memoryKeys() {\n return [this.memoryKey];\n }\n\n /**\n * Loads the memory variables. It takes an `InputValues` object as a\n * parameter and returns a `Promise` that resolves with a\n * `MemoryVariables` object.\n * @param _values `InputValues` object.\n * @returns A `Promise` that resolves with a `MemoryVariables` object.\n */\n async loadMemoryVariables(_values: InputValues): Promise<MemoryVariables> {\n const messages = await this.chatHistory.getMessages();\n if (this.returnMessages) {\n const result = {\n [this.memoryKey]: messages,\n };\n return result;\n }\n const result = {\n [this.memoryKey]: getBufferString(\n messages,\n this.humanPrefix,\n this.aiPrefix\n ),\n };\n return result;\n }\n\n /**\n * Saves the context from this conversation to buffer. If the amount\n * of tokens required to save the buffer exceeds MAX_TOKEN_LIMIT,\n * prune it.\n */\n async saveContext(inputValues: InputValues, outputValues: OutputValues) {\n await super.saveContext(inputValues, outputValues);\n\n // Prune buffer if it exceeds the max token limit set for this instance.\n const buffer = await this.chatHistory.getMessages();\n let currBufferLength = await this.llm.getNumTokens(\n getBufferString(buffer, this.humanPrefix, this.aiPrefix)\n );\n\n if (currBufferLength > this.maxTokenLimit) {\n const prunedMemory = [];\n while (currBufferLength > this.maxTokenLimit) {\n prunedMemory.push(buffer.shift());\n currBufferLength = await this.llm.getNumTokens(\n getBufferString(buffer, this.humanPrefix, this.aiPrefix)\n );\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAmDA,IAAa,gCAAb,cACUA,2BAAAA,eAEV;CACE,cAAc;CAEd,WAAW;CAEX,YAAY;CAEZ,gBAAgB;CAEhB;CAEA,YAAY,QAA4C;AACtD,QAAM,OAAO;AACb,OAAK,MAAM,OAAO;AAClB,OAAK,cAAc,QAAQ,eAAe,KAAK;AAC/C,OAAK,WAAW,QAAQ,YAAY,KAAK;AACzC,OAAK,YAAY,QAAQ,aAAa,KAAK;AAC3C,OAAK,gBAAgB,QAAQ,iBAAiB,KAAK;;CAGrD,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,UAAU;;;;;;;;;CAUzB,MAAM,oBAAoB,SAAgD;EACxE,MAAM,WAAW,MAAM,KAAK,YAAY,aAAa;AACrD,MAAI,KAAK,eAIP,QAAO,GAFJ,KAAK,YAAY,UAEP;AASf,SAAO,GANJ,KAAK,aAAA,GAAA,yBAAA,iBACJ,UACA,KAAK,aACL,KAAK,SACN,EAEU;;;;;;;CAQf,MAAM,YAAY,aAA0B,cAA4B;AACtE,QAAM,MAAM,YAAY,aAAa,aAAa;EAGlD,MAAM,SAAS,MAAM,KAAK,YAAY,aAAa;EACnD,IAAI,mBAAmB,MAAM,KAAK,IAAI,cAAA,GAAA,yBAAA,iBACpB,QAAQ,KAAK,aAAa,KAAK,SAAS,CACzD;AAED,MAAI,mBAAmB,KAAK,eAAe;GACzC,MAAM,eAAe,EAAE;AACvB,UAAO,mBAAmB,KAAK,eAAe;AAC5C,iBAAa,KAAK,OAAO,OAAO,CAAC;AACjC,uBAAmB,MAAM,KAAK,IAAI,cAAA,GAAA,yBAAA,iBAChB,QAAQ,KAAK,aAAa,KAAK,SAAS,CACzD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buffer_token_memory.js","names":[],"sources":["../../src/memory/buffer_token_memory.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport {\n InputValues,\n MemoryVariables,\n OutputValues,\n} from \"@langchain/core/memory\";\nimport { getBufferString } from \"@langchain/core/messages\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the input parameters of the `BufferTokenMemory` class.\n */\n\nexport interface ConversationTokenBufferMemoryInput extends BaseChatMemoryInput {\n /* Prefix for human messages in the buffer. */\n humanPrefix?: string;\n\n /* Prefix for AI messages in the buffer. */\n aiPrefix?: string;\n\n /* The LLM for this instance. */\n llm: BaseLanguageModelInterface;\n\n /* Memory key for buffer instance. */\n memoryKey?: string;\n\n /* Maximmum number of tokens allowed in the buffer. */\n maxTokenLimit?: number;\n}\n\n/**\n * Class that represents a conversation chat memory with a token buffer.\n * It extends the `BaseChatMemory` class and implements the\n * `ConversationTokenBufferMemoryInput` interface.\n * @example\n * ```typescript\n * const memory = new ConversationTokenBufferMemory({\n * llm: new ChatOpenAI({ model: \"gpt-4o-mini\" }),\n * maxTokenLimit: 10,\n * });\n *\n * // Save conversation context\n * await memory.saveContext({ input: \"hi\" }, { output: \"whats up\" });\n * await memory.saveContext({ input: \"not much you\" }, { output: \"not much\" });\n *\n * // Load memory variables\n * const result = await memory.loadMemoryVariables({});\n * console.log(result);\n * ```\n */\n\nexport class ConversationTokenBufferMemory\n extends BaseChatMemory\n implements ConversationTokenBufferMemoryInput\n{\n humanPrefix = \"Human\";\n\n aiPrefix = \"AI\";\n\n memoryKey = \"history\";\n\n maxTokenLimit = 2000; // Default max token limit of 2000 which can be overridden\n\n llm: BaseLanguageModelInterface;\n\n constructor(fields: ConversationTokenBufferMemoryInput) {\n super(fields);\n this.llm = fields.llm;\n this.humanPrefix = fields?.humanPrefix ?? this.humanPrefix;\n this.aiPrefix = fields?.aiPrefix ?? this.aiPrefix;\n this.memoryKey = fields?.memoryKey ?? this.memoryKey;\n this.maxTokenLimit = fields?.maxTokenLimit ?? this.maxTokenLimit;\n }\n\n get memoryKeys() {\n return [this.memoryKey];\n }\n\n /**\n * Loads the memory variables. It takes an `InputValues` object as a\n * parameter and returns a `Promise` that resolves with a\n * `MemoryVariables` object.\n * @param _values `InputValues` object.\n * @returns A `Promise` that resolves with a `MemoryVariables` object.\n */\n async loadMemoryVariables(_values: InputValues): Promise<MemoryVariables> {\n const messages = await this.chatHistory.getMessages();\n if (this.returnMessages) {\n const result = {\n [this.memoryKey]: messages,\n };\n return result;\n }\n const result = {\n [this.memoryKey]: getBufferString(\n messages,\n this.humanPrefix,\n this.aiPrefix\n ),\n };\n return result;\n }\n\n /**\n * Saves the context from this conversation to buffer. If the amount\n * of tokens required to save the buffer exceeds MAX_TOKEN_LIMIT,\n * prune it.\n */\n async saveContext(inputValues: InputValues, outputValues: OutputValues) {\n await super.saveContext(inputValues, outputValues);\n\n // Prune buffer if it exceeds the max token limit set for this instance.\n const buffer = await this.chatHistory.getMessages();\n let currBufferLength = await this.llm.getNumTokens(\n getBufferString(buffer, this.humanPrefix, this.aiPrefix)\n );\n\n if (currBufferLength > this.maxTokenLimit) {\n const prunedMemory = [];\n while (currBufferLength > this.maxTokenLimit) {\n prunedMemory.push(buffer.shift());\n currBufferLength = await this.llm.getNumTokens(\n getBufferString(buffer, this.humanPrefix, this.aiPrefix)\n );\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAmDA,IAAa,gCAAb,cACU,eAEV;CACE,cAAc;CAEd,WAAW;CAEX,YAAY;CAEZ,gBAAgB;CAEhB;CAEA,YAAY,QAA4C;AACtD,QAAM,OAAO;AACb,OAAK,MAAM,OAAO;AAClB,OAAK,cAAc,QAAQ,eAAe,KAAK;AAC/C,OAAK,WAAW,QAAQ,YAAY,KAAK;AACzC,OAAK,YAAY,QAAQ,aAAa,KAAK;AAC3C,OAAK,gBAAgB,QAAQ,iBAAiB,KAAK;;CAGrD,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,UAAU;;;;;;;;;CAUzB,MAAM,oBAAoB,SAAgD;EACxE,MAAM,WAAW,MAAM,KAAK,YAAY,aAAa;AACrD,MAAI,KAAK,eAIP,
|
|
1
|
+
{"version":3,"file":"buffer_token_memory.js","names":[],"sources":["../../src/memory/buffer_token_memory.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport {\n InputValues,\n MemoryVariables,\n OutputValues,\n} from \"@langchain/core/memory\";\nimport { getBufferString } from \"@langchain/core/messages\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the input parameters of the `BufferTokenMemory` class.\n */\n\nexport interface ConversationTokenBufferMemoryInput extends BaseChatMemoryInput {\n /* Prefix for human messages in the buffer. */\n humanPrefix?: string;\n\n /* Prefix for AI messages in the buffer. */\n aiPrefix?: string;\n\n /* The LLM for this instance. */\n llm: BaseLanguageModelInterface;\n\n /* Memory key for buffer instance. */\n memoryKey?: string;\n\n /* Maximmum number of tokens allowed in the buffer. */\n maxTokenLimit?: number;\n}\n\n/**\n * Class that represents a conversation chat memory with a token buffer.\n * It extends the `BaseChatMemory` class and implements the\n * `ConversationTokenBufferMemoryInput` interface.\n * @example\n * ```typescript\n * const memory = new ConversationTokenBufferMemory({\n * llm: new ChatOpenAI({ model: \"gpt-4o-mini\" }),\n * maxTokenLimit: 10,\n * });\n *\n * // Save conversation context\n * await memory.saveContext({ input: \"hi\" }, { output: \"whats up\" });\n * await memory.saveContext({ input: \"not much you\" }, { output: \"not much\" });\n *\n * // Load memory variables\n * const result = await memory.loadMemoryVariables({});\n * console.log(result);\n * ```\n */\n\nexport class ConversationTokenBufferMemory\n extends BaseChatMemory\n implements ConversationTokenBufferMemoryInput\n{\n humanPrefix = \"Human\";\n\n aiPrefix = \"AI\";\n\n memoryKey = \"history\";\n\n maxTokenLimit = 2000; // Default max token limit of 2000 which can be overridden\n\n llm: BaseLanguageModelInterface;\n\n constructor(fields: ConversationTokenBufferMemoryInput) {\n super(fields);\n this.llm = fields.llm;\n this.humanPrefix = fields?.humanPrefix ?? this.humanPrefix;\n this.aiPrefix = fields?.aiPrefix ?? this.aiPrefix;\n this.memoryKey = fields?.memoryKey ?? this.memoryKey;\n this.maxTokenLimit = fields?.maxTokenLimit ?? this.maxTokenLimit;\n }\n\n get memoryKeys() {\n return [this.memoryKey];\n }\n\n /**\n * Loads the memory variables. It takes an `InputValues` object as a\n * parameter and returns a `Promise` that resolves with a\n * `MemoryVariables` object.\n * @param _values `InputValues` object.\n * @returns A `Promise` that resolves with a `MemoryVariables` object.\n */\n async loadMemoryVariables(_values: InputValues): Promise<MemoryVariables> {\n const messages = await this.chatHistory.getMessages();\n if (this.returnMessages) {\n const result = {\n [this.memoryKey]: messages,\n };\n return result;\n }\n const result = {\n [this.memoryKey]: getBufferString(\n messages,\n this.humanPrefix,\n this.aiPrefix\n ),\n };\n return result;\n }\n\n /**\n * Saves the context from this conversation to buffer. If the amount\n * of tokens required to save the buffer exceeds MAX_TOKEN_LIMIT,\n * prune it.\n */\n async saveContext(inputValues: InputValues, outputValues: OutputValues) {\n await super.saveContext(inputValues, outputValues);\n\n // Prune buffer if it exceeds the max token limit set for this instance.\n const buffer = await this.chatHistory.getMessages();\n let currBufferLength = await this.llm.getNumTokens(\n getBufferString(buffer, this.humanPrefix, this.aiPrefix)\n );\n\n if (currBufferLength > this.maxTokenLimit) {\n const prunedMemory = [];\n while (currBufferLength > this.maxTokenLimit) {\n prunedMemory.push(buffer.shift());\n currBufferLength = await this.llm.getNumTokens(\n getBufferString(buffer, this.humanPrefix, this.aiPrefix)\n );\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAmDA,IAAa,gCAAb,cACU,eAEV;CACE,cAAc;CAEd,WAAW;CAEX,YAAY;CAEZ,gBAAgB;CAEhB;CAEA,YAAY,QAA4C;AACtD,QAAM,OAAO;AACb,OAAK,MAAM,OAAO;AAClB,OAAK,cAAc,QAAQ,eAAe,KAAK;AAC/C,OAAK,WAAW,QAAQ,YAAY,KAAK;AACzC,OAAK,YAAY,QAAQ,aAAa,KAAK;AAC3C,OAAK,gBAAgB,QAAQ,iBAAiB,KAAK;;CAGrD,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,UAAU;;;;;;;;;CAUzB,MAAM,oBAAoB,SAAgD;EACxE,MAAM,WAAW,MAAM,KAAK,YAAY,aAAa;AACrD,MAAI,KAAK,eAIP,QAAO,GAFJ,KAAK,YAAY,UAEP;AASf,SAAO,GANJ,KAAK,YAAY,gBAChB,UACA,KAAK,aACL,KAAK,SACN,EAEU;;;;;;;CAQf,MAAM,YAAY,aAA0B,cAA4B;AACtE,QAAM,MAAM,YAAY,aAAa,aAAa;EAGlD,MAAM,SAAS,MAAM,KAAK,YAAY,aAAa;EACnD,IAAI,mBAAmB,MAAM,KAAK,IAAI,aACpC,gBAAgB,QAAQ,KAAK,aAAa,KAAK,SAAS,CACzD;AAED,MAAI,mBAAmB,KAAK,eAAe;GACzC,MAAM,eAAe,EAAE;AACvB,UAAO,mBAAmB,KAAK,eAAe;AAC5C,iBAAa,KAAK,OAAO,OAAO,CAAC;AACjC,uBAAmB,MAAM,KAAK,IAAI,aAChC,gBAAgB,QAAQ,KAAK,aAAa,KAAK,SAAS,CACzD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buffer_window_memory.cjs","names":["BaseChatMemory"],"sources":["../../src/memory/buffer_window_memory.ts"],"sourcesContent":["import { InputValues, MemoryVariables } from \"@langchain/core/memory\";\nimport { getBufferString } from \"@langchain/core/messages\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the input parameters of the BufferWindowMemory class.\n */\nexport interface BufferWindowMemoryInput extends BaseChatMemoryInput {\n humanPrefix?: string;\n aiPrefix?: string;\n memoryKey?: string;\n k?: number;\n}\n\n/**\n * Class for managing and storing previous chat messages. It extends the\n * BaseChatMemory class and implements the BufferWindowMemoryInput\n * interface. This class is stateful and stores messages in a buffer. When\n * called in a chain, it returns all of the messages it has stored.\n * @example\n * ```typescript\n * const prompt =\n * PromptTemplate.fromTemplate(`The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n * Current conversation:\n * {chat_history}\n * Human: {input}\n * AI:`);\n *\n * const chain = new LLMChain({\n * llm: new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0.9 }),\n * prompt,\n * memory: new BufferWindowMemory({ memoryKey: \"chat_history\", k: 1 }),\n * });\n *\n * // Example of initiating a conversation with the AI\n * const res1 = await chain.call({ input: \"Hi! I'm Jim.\" });\n * console.log({ res1 });\n *\n * // Example of following up with another question\n * const res2 = await chain.call({ input: \"What's my name?\" });\n * console.log({ res2 });\n * ```\n */\nexport class BufferWindowMemory\n extends BaseChatMemory\n implements BufferWindowMemoryInput\n{\n humanPrefix = \"Human\";\n\n aiPrefix = \"AI\";\n\n memoryKey = \"history\";\n\n k = 5;\n\n constructor(fields?: BufferWindowMemoryInput) {\n super({\n returnMessages: fields?.returnMessages ?? false,\n chatHistory: fields?.chatHistory,\n inputKey: fields?.inputKey,\n outputKey: fields?.outputKey,\n });\n this.humanPrefix = fields?.humanPrefix ?? this.humanPrefix;\n this.aiPrefix = fields?.aiPrefix ?? this.aiPrefix;\n this.memoryKey = fields?.memoryKey ?? this.memoryKey;\n this.k = fields?.k ?? this.k;\n }\n\n get memoryKeys() {\n return [this.memoryKey];\n }\n\n /**\n * Method to load the memory variables. Retrieves the chat messages from\n * the history, slices the last 'k' messages, and stores them in the\n * memory under the memoryKey. If the returnMessages property is set to\n * true, the method returns the messages as they are. Otherwise, it\n * returns a string representation of the messages.\n * @param _values InputValues object.\n * @returns Promise that resolves to a MemoryVariables object.\n */\n async loadMemoryVariables(_values: InputValues): Promise<MemoryVariables> {\n const messages = await this.chatHistory.getMessages();\n if (this.returnMessages) {\n const result = {\n [this.memoryKey]: messages.slice(-this.k * 2),\n };\n return result;\n }\n const result = {\n [this.memoryKey]: getBufferString(\n messages.slice(-this.k * 2),\n this.humanPrefix,\n this.aiPrefix\n ),\n };\n return result;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,IAAa,qBAAb,cACUA,2BAAAA,eAEV;CACE,cAAc;CAEd,WAAW;CAEX,YAAY;CAEZ,IAAI;CAEJ,YAAY,QAAkC;AAC5C,QAAM;GACJ,gBAAgB,QAAQ,kBAAkB;GAC1C,aAAa,QAAQ;GACrB,UAAU,QAAQ;GAClB,WAAW,QAAQ;GACpB,CAAC;AACF,OAAK,cAAc,QAAQ,eAAe,KAAK;AAC/C,OAAK,WAAW,QAAQ,YAAY,KAAK;AACzC,OAAK,YAAY,QAAQ,aAAa,KAAK;AAC3C,OAAK,IAAI,QAAQ,KAAK,KAAK;;CAG7B,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,UAAU;;;;;;;;;;;CAYzB,MAAM,oBAAoB,SAAgD;EACxE,MAAM,WAAW,MAAM,KAAK,YAAY,aAAa;AACrD,MAAI,KAAK,eAIP,
|
|
1
|
+
{"version":3,"file":"buffer_window_memory.cjs","names":["BaseChatMemory"],"sources":["../../src/memory/buffer_window_memory.ts"],"sourcesContent":["import { InputValues, MemoryVariables } from \"@langchain/core/memory\";\nimport { getBufferString } from \"@langchain/core/messages\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the input parameters of the BufferWindowMemory class.\n */\nexport interface BufferWindowMemoryInput extends BaseChatMemoryInput {\n humanPrefix?: string;\n aiPrefix?: string;\n memoryKey?: string;\n k?: number;\n}\n\n/**\n * Class for managing and storing previous chat messages. It extends the\n * BaseChatMemory class and implements the BufferWindowMemoryInput\n * interface. This class is stateful and stores messages in a buffer. When\n * called in a chain, it returns all of the messages it has stored.\n * @example\n * ```typescript\n * const prompt =\n * PromptTemplate.fromTemplate(`The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n * Current conversation:\n * {chat_history}\n * Human: {input}\n * AI:`);\n *\n * const chain = new LLMChain({\n * llm: new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0.9 }),\n * prompt,\n * memory: new BufferWindowMemory({ memoryKey: \"chat_history\", k: 1 }),\n * });\n *\n * // Example of initiating a conversation with the AI\n * const res1 = await chain.call({ input: \"Hi! I'm Jim.\" });\n * console.log({ res1 });\n *\n * // Example of following up with another question\n * const res2 = await chain.call({ input: \"What's my name?\" });\n * console.log({ res2 });\n * ```\n */\nexport class BufferWindowMemory\n extends BaseChatMemory\n implements BufferWindowMemoryInput\n{\n humanPrefix = \"Human\";\n\n aiPrefix = \"AI\";\n\n memoryKey = \"history\";\n\n k = 5;\n\n constructor(fields?: BufferWindowMemoryInput) {\n super({\n returnMessages: fields?.returnMessages ?? false,\n chatHistory: fields?.chatHistory,\n inputKey: fields?.inputKey,\n outputKey: fields?.outputKey,\n });\n this.humanPrefix = fields?.humanPrefix ?? this.humanPrefix;\n this.aiPrefix = fields?.aiPrefix ?? this.aiPrefix;\n this.memoryKey = fields?.memoryKey ?? this.memoryKey;\n this.k = fields?.k ?? this.k;\n }\n\n get memoryKeys() {\n return [this.memoryKey];\n }\n\n /**\n * Method to load the memory variables. Retrieves the chat messages from\n * the history, slices the last 'k' messages, and stores them in the\n * memory under the memoryKey. If the returnMessages property is set to\n * true, the method returns the messages as they are. Otherwise, it\n * returns a string representation of the messages.\n * @param _values InputValues object.\n * @returns Promise that resolves to a MemoryVariables object.\n */\n async loadMemoryVariables(_values: InputValues): Promise<MemoryVariables> {\n const messages = await this.chatHistory.getMessages();\n if (this.returnMessages) {\n const result = {\n [this.memoryKey]: messages.slice(-this.k * 2),\n };\n return result;\n }\n const result = {\n [this.memoryKey]: getBufferString(\n messages.slice(-this.k * 2),\n this.humanPrefix,\n this.aiPrefix\n ),\n };\n return result;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,IAAa,qBAAb,cACUA,2BAAAA,eAEV;CACE,cAAc;CAEd,WAAW;CAEX,YAAY;CAEZ,IAAI;CAEJ,YAAY,QAAkC;AAC5C,QAAM;GACJ,gBAAgB,QAAQ,kBAAkB;GAC1C,aAAa,QAAQ;GACrB,UAAU,QAAQ;GAClB,WAAW,QAAQ;GACpB,CAAC;AACF,OAAK,cAAc,QAAQ,eAAe,KAAK;AAC/C,OAAK,WAAW,QAAQ,YAAY,KAAK;AACzC,OAAK,YAAY,QAAQ,aAAa,KAAK;AAC3C,OAAK,IAAI,QAAQ,KAAK,KAAK;;CAG7B,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,UAAU;;;;;;;;;;;CAYzB,MAAM,oBAAoB,SAAgD;EACxE,MAAM,WAAW,MAAM,KAAK,YAAY,aAAa;AACrD,MAAI,KAAK,eAIP,QAAO,GAFJ,KAAK,YAAY,SAAS,MAAM,CAAC,KAAK,IAAI,EAAE,EAElC;AASf,SAAO,GANJ,KAAK,aAAA,GAAA,yBAAA,iBACJ,SAAS,MAAM,CAAC,KAAK,IAAI,EAAE,EAC3B,KAAK,aACL,KAAK,SACN,EAEU"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buffer_window_memory.js","names":[],"sources":["../../src/memory/buffer_window_memory.ts"],"sourcesContent":["import { InputValues, MemoryVariables } from \"@langchain/core/memory\";\nimport { getBufferString } from \"@langchain/core/messages\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the input parameters of the BufferWindowMemory class.\n */\nexport interface BufferWindowMemoryInput extends BaseChatMemoryInput {\n humanPrefix?: string;\n aiPrefix?: string;\n memoryKey?: string;\n k?: number;\n}\n\n/**\n * Class for managing and storing previous chat messages. It extends the\n * BaseChatMemory class and implements the BufferWindowMemoryInput\n * interface. This class is stateful and stores messages in a buffer. When\n * called in a chain, it returns all of the messages it has stored.\n * @example\n * ```typescript\n * const prompt =\n * PromptTemplate.fromTemplate(`The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n * Current conversation:\n * {chat_history}\n * Human: {input}\n * AI:`);\n *\n * const chain = new LLMChain({\n * llm: new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0.9 }),\n * prompt,\n * memory: new BufferWindowMemory({ memoryKey: \"chat_history\", k: 1 }),\n * });\n *\n * // Example of initiating a conversation with the AI\n * const res1 = await chain.call({ input: \"Hi! I'm Jim.\" });\n * console.log({ res1 });\n *\n * // Example of following up with another question\n * const res2 = await chain.call({ input: \"What's my name?\" });\n * console.log({ res2 });\n * ```\n */\nexport class BufferWindowMemory\n extends BaseChatMemory\n implements BufferWindowMemoryInput\n{\n humanPrefix = \"Human\";\n\n aiPrefix = \"AI\";\n\n memoryKey = \"history\";\n\n k = 5;\n\n constructor(fields?: BufferWindowMemoryInput) {\n super({\n returnMessages: fields?.returnMessages ?? false,\n chatHistory: fields?.chatHistory,\n inputKey: fields?.inputKey,\n outputKey: fields?.outputKey,\n });\n this.humanPrefix = fields?.humanPrefix ?? this.humanPrefix;\n this.aiPrefix = fields?.aiPrefix ?? this.aiPrefix;\n this.memoryKey = fields?.memoryKey ?? this.memoryKey;\n this.k = fields?.k ?? this.k;\n }\n\n get memoryKeys() {\n return [this.memoryKey];\n }\n\n /**\n * Method to load the memory variables. Retrieves the chat messages from\n * the history, slices the last 'k' messages, and stores them in the\n * memory under the memoryKey. If the returnMessages property is set to\n * true, the method returns the messages as they are. Otherwise, it\n * returns a string representation of the messages.\n * @param _values InputValues object.\n * @returns Promise that resolves to a MemoryVariables object.\n */\n async loadMemoryVariables(_values: InputValues): Promise<MemoryVariables> {\n const messages = await this.chatHistory.getMessages();\n if (this.returnMessages) {\n const result = {\n [this.memoryKey]: messages.slice(-this.k * 2),\n };\n return result;\n }\n const result = {\n [this.memoryKey]: getBufferString(\n messages.slice(-this.k * 2),\n this.humanPrefix,\n this.aiPrefix\n ),\n };\n return result;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,IAAa,qBAAb,cACU,eAEV;CACE,cAAc;CAEd,WAAW;CAEX,YAAY;CAEZ,IAAI;CAEJ,YAAY,QAAkC;AAC5C,QAAM;GACJ,gBAAgB,QAAQ,kBAAkB;GAC1C,aAAa,QAAQ;GACrB,UAAU,QAAQ;GAClB,WAAW,QAAQ;GACpB,CAAC;AACF,OAAK,cAAc,QAAQ,eAAe,KAAK;AAC/C,OAAK,WAAW,QAAQ,YAAY,KAAK;AACzC,OAAK,YAAY,QAAQ,aAAa,KAAK;AAC3C,OAAK,IAAI,QAAQ,KAAK,KAAK;;CAG7B,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,UAAU;;;;;;;;;;;CAYzB,MAAM,oBAAoB,SAAgD;EACxE,MAAM,WAAW,MAAM,KAAK,YAAY,aAAa;AACrD,MAAI,KAAK,eAIP,
|
|
1
|
+
{"version":3,"file":"buffer_window_memory.js","names":[],"sources":["../../src/memory/buffer_window_memory.ts"],"sourcesContent":["import { InputValues, MemoryVariables } from \"@langchain/core/memory\";\nimport { getBufferString } from \"@langchain/core/messages\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the input parameters of the BufferWindowMemory class.\n */\nexport interface BufferWindowMemoryInput extends BaseChatMemoryInput {\n humanPrefix?: string;\n aiPrefix?: string;\n memoryKey?: string;\n k?: number;\n}\n\n/**\n * Class for managing and storing previous chat messages. It extends the\n * BaseChatMemory class and implements the BufferWindowMemoryInput\n * interface. This class is stateful and stores messages in a buffer. When\n * called in a chain, it returns all of the messages it has stored.\n * @example\n * ```typescript\n * const prompt =\n * PromptTemplate.fromTemplate(`The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n * Current conversation:\n * {chat_history}\n * Human: {input}\n * AI:`);\n *\n * const chain = new LLMChain({\n * llm: new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0.9 }),\n * prompt,\n * memory: new BufferWindowMemory({ memoryKey: \"chat_history\", k: 1 }),\n * });\n *\n * // Example of initiating a conversation with the AI\n * const res1 = await chain.call({ input: \"Hi! I'm Jim.\" });\n * console.log({ res1 });\n *\n * // Example of following up with another question\n * const res2 = await chain.call({ input: \"What's my name?\" });\n * console.log({ res2 });\n * ```\n */\nexport class BufferWindowMemory\n extends BaseChatMemory\n implements BufferWindowMemoryInput\n{\n humanPrefix = \"Human\";\n\n aiPrefix = \"AI\";\n\n memoryKey = \"history\";\n\n k = 5;\n\n constructor(fields?: BufferWindowMemoryInput) {\n super({\n returnMessages: fields?.returnMessages ?? false,\n chatHistory: fields?.chatHistory,\n inputKey: fields?.inputKey,\n outputKey: fields?.outputKey,\n });\n this.humanPrefix = fields?.humanPrefix ?? this.humanPrefix;\n this.aiPrefix = fields?.aiPrefix ?? this.aiPrefix;\n this.memoryKey = fields?.memoryKey ?? this.memoryKey;\n this.k = fields?.k ?? this.k;\n }\n\n get memoryKeys() {\n return [this.memoryKey];\n }\n\n /**\n * Method to load the memory variables. Retrieves the chat messages from\n * the history, slices the last 'k' messages, and stores them in the\n * memory under the memoryKey. If the returnMessages property is set to\n * true, the method returns the messages as they are. Otherwise, it\n * returns a string representation of the messages.\n * @param _values InputValues object.\n * @returns Promise that resolves to a MemoryVariables object.\n */\n async loadMemoryVariables(_values: InputValues): Promise<MemoryVariables> {\n const messages = await this.chatHistory.getMessages();\n if (this.returnMessages) {\n const result = {\n [this.memoryKey]: messages.slice(-this.k * 2),\n };\n return result;\n }\n const result = {\n [this.memoryKey]: getBufferString(\n messages.slice(-this.k * 2),\n this.humanPrefix,\n this.aiPrefix\n ),\n };\n return result;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,IAAa,qBAAb,cACU,eAEV;CACE,cAAc;CAEd,WAAW;CAEX,YAAY;CAEZ,IAAI;CAEJ,YAAY,QAAkC;AAC5C,QAAM;GACJ,gBAAgB,QAAQ,kBAAkB;GAC1C,aAAa,QAAQ;GACrB,UAAU,QAAQ;GAClB,WAAW,QAAQ;GACpB,CAAC;AACF,OAAK,cAAc,QAAQ,eAAe,KAAK;AAC/C,OAAK,WAAW,QAAQ,YAAY,KAAK;AACzC,OAAK,YAAY,QAAQ,aAAa,KAAK;AAC3C,OAAK,IAAI,QAAQ,KAAK,KAAK;;CAG7B,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,UAAU;;;;;;;;;;;CAYzB,MAAM,oBAAoB,SAAgD;EACxE,MAAM,WAAW,MAAM,KAAK,YAAY,aAAa;AACrD,MAAI,KAAK,eAIP,QAAO,GAFJ,KAAK,YAAY,SAAS,MAAM,CAAC,KAAK,IAAI,EAAE,EAElC;AASf,SAAO,GANJ,KAAK,YAAY,gBAChB,SAAS,MAAM,CAAC,KAAK,IAAI,EAAE,EAC3B,KAAK,aACL,KAAK,SACN,EAEU"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entity_memory.cjs","names":["BaseChatMemory","LLMChain","ENTITY_EXTRACTION_PROMPT","ENTITY_SUMMARIZATION_PROMPT","InMemoryEntityStore"],"sources":["../../src/memory/entity_memory.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { PromptTemplate } from \"@langchain/core/prompts\";\n\nimport {\n InputValues,\n MemoryVariables,\n OutputValues,\n getPromptInputKey,\n} from \"@langchain/core/memory\";\nimport { getBufferString } from \"@langchain/core/messages\";\nimport { InMemoryEntityStore } from \"./stores/entity/in_memory.js\";\nimport { LLMChain } from \"../chains/llm_chain.js\";\nimport {\n ENTITY_EXTRACTION_PROMPT,\n ENTITY_SUMMARIZATION_PROMPT,\n} from \"./prompt.js\";\nimport { BaseEntityStore } from \"./stores/entity/base.js\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the input parameters required by the EntityMemory class.\n */\nexport interface EntityMemoryInput extends BaseChatMemoryInput {\n llm: BaseLanguageModelInterface;\n humanPrefix?: string;\n aiPrefix?: string;\n entityExtractionPrompt?: PromptTemplate;\n entitySummarizationPrompt?: PromptTemplate;\n entityCache?: string[];\n k?: number;\n chatHistoryKey?: string;\n entitiesKey?: string;\n entityStore?: BaseEntityStore;\n}\n\n// Entity extractor & summarizer to memory.\n/**\n * Class for managing entity extraction and summarization to memory in\n * chatbot applications. Extends the BaseChatMemory class and implements\n * the EntityMemoryInput interface.\n * @example\n * ```typescript\n * const memory = new EntityMemory({\n * llm: new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0 }),\n * chatHistoryKey: \"history\",\n * entitiesKey: \"entities\",\n * });\n * const model = new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0.9 });\n * const chain = new LLMChain({\n * llm: model,\n * prompt: ENTITY_MEMORY_CONVERSATION_TEMPLATE,\n * memory,\n * });\n *\n * const res1 = await chain.call({ input: \"Hi! I'm Jim.\" });\n * console.log({\n * res1,\n * memory: await memory.loadMemoryVariables({ input: \"Who is Jim?\" }),\n * });\n *\n * const res2 = await chain.call({\n * input: \"I work in construction. What about you?\",\n * });\n * console.log({\n * res2,\n * memory: await memory.loadMemoryVariables({ input: \"Who is Jim?\" }),\n * });\n *\n * ```\n */\nexport class EntityMemory extends BaseChatMemory implements EntityMemoryInput {\n private entityExtractionChain: LLMChain;\n\n private entitySummarizationChain: LLMChain;\n\n entityStore: BaseEntityStore;\n\n entityCache: string[] = [];\n\n k = 3;\n\n chatHistoryKey = \"history\";\n\n llm: BaseLanguageModelInterface;\n\n entitiesKey = \"entities\";\n\n humanPrefix?: string;\n\n aiPrefix?: string;\n\n constructor(fields: EntityMemoryInput) {\n super({\n chatHistory: fields.chatHistory,\n returnMessages: fields.returnMessages ?? false,\n inputKey: fields.inputKey,\n outputKey: fields.outputKey,\n });\n this.llm = fields.llm;\n this.humanPrefix = fields.humanPrefix;\n this.aiPrefix = fields.aiPrefix;\n this.chatHistoryKey = fields.chatHistoryKey ?? this.chatHistoryKey;\n this.entitiesKey = fields.entitiesKey ?? this.entitiesKey;\n this.entityExtractionChain = new LLMChain({\n llm: this.llm,\n prompt: fields.entityExtractionPrompt ?? ENTITY_EXTRACTION_PROMPT,\n });\n this.entitySummarizationChain = new LLMChain({\n llm: this.llm,\n prompt: fields.entitySummarizationPrompt ?? ENTITY_SUMMARIZATION_PROMPT,\n });\n this.entityStore = fields.entityStore ?? new InMemoryEntityStore();\n this.entityCache = fields.entityCache ?? this.entityCache;\n this.k = fields.k ?? this.k;\n }\n\n get memoryKeys() {\n return [this.chatHistoryKey];\n }\n\n // Will always return list of memory variables.\n get memoryVariables(): string[] {\n return [this.entitiesKey, this.chatHistoryKey];\n }\n\n // Return history buffer.\n /**\n * Method to load memory variables and perform entity extraction.\n * @param inputs Input values for the method.\n * @returns Promise resolving to an object containing memory variables.\n */\n async loadMemoryVariables(inputs: InputValues): Promise<MemoryVariables> {\n const promptInputKey =\n this.inputKey ?? getPromptInputKey(inputs, this.memoryVariables);\n const messages = await this.chatHistory.getMessages();\n const serializedMessages = getBufferString(\n messages.slice(-this.k * 2),\n this.humanPrefix,\n this.aiPrefix\n );\n const output = await this.entityExtractionChain.predict({\n history: serializedMessages,\n input: inputs[promptInputKey],\n });\n const entities: string[] =\n output.trim() === \"NONE\" ? [] : output.split(\",\").map((w) => w.trim());\n const entitySummaries: { [key: string]: string | undefined } = {};\n\n for (const entity of entities) {\n entitySummaries[entity] = await this.entityStore.get(\n entity,\n \"No current information known.\"\n );\n }\n this.entityCache = [...entities];\n const buffer = this.returnMessages\n ? messages.slice(-this.k * 2)\n : serializedMessages;\n\n return {\n [this.chatHistoryKey]: buffer,\n [this.entitiesKey]: entitySummaries,\n };\n }\n\n // Save context from this conversation to buffer.\n /**\n * Method to save the context from a conversation to a buffer and perform\n * entity summarization.\n * @param inputs Input values for the method.\n * @param outputs Output values from the method.\n * @returns Promise resolving to void.\n */\n async saveContext(inputs: InputValues, outputs: OutputValues): Promise<void> {\n await super.saveContext(inputs, outputs);\n\n const promptInputKey =\n this.inputKey ?? getPromptInputKey(inputs, this.memoryVariables);\n const messages = await this.chatHistory.getMessages();\n const serializedMessages = getBufferString(\n messages.slice(-this.k * 2),\n this.humanPrefix,\n this.aiPrefix\n );\n const inputData = inputs[promptInputKey];\n\n for (const entity of this.entityCache) {\n const existingSummary = await this.entityStore.get(\n entity,\n \"No current information known.\"\n );\n const output = await this.entitySummarizationChain.predict({\n summary: existingSummary,\n entity,\n history: serializedMessages,\n input: inputData,\n });\n if (output.trim() !== \"UNCHANGED\") {\n await this.entityStore.set(entity, output.trim());\n }\n }\n }\n\n // Clear memory contents.\n /**\n * Method to clear the memory contents.\n * @returns Promise resolving to void.\n */\n async clear() {\n await super.clear();\n await this.entityStore.clear();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,IAAa,eAAb,cAAkCA,2BAAAA,eAA4C;CAC5E;CAEA;CAEA;CAEA,cAAwB,EAAE;CAE1B,IAAI;CAEJ,iBAAiB;CAEjB;CAEA,cAAc;CAEd;CAEA;CAEA,YAAY,QAA2B;AACrC,QAAM;GACJ,aAAa,OAAO;GACpB,gBAAgB,OAAO,kBAAkB;GACzC,UAAU,OAAO;GACjB,WAAW,OAAO;GACnB,CAAC;AACF,OAAK,MAAM,OAAO;AAClB,OAAK,cAAc,OAAO;AAC1B,OAAK,WAAW,OAAO;AACvB,OAAK,iBAAiB,OAAO,kBAAkB,KAAK;AACpD,OAAK,cAAc,OAAO,eAAe,KAAK;AAC9C,OAAK,wBAAwB,IAAIC,kBAAAA,SAAS;GACxC,KAAK,KAAK;GACV,QAAQ,OAAO,0BAA0BC,eAAAA;GAC1C,CAAC;AACF,OAAK,2BAA2B,IAAID,kBAAAA,SAAS;GAC3C,KAAK,KAAK;GACV,QAAQ,OAAO,6BAA6BE,eAAAA;GAC7C,CAAC;AACF,OAAK,cAAc,OAAO,eAAe,IAAIC,kBAAAA,qBAAqB;AAClE,OAAK,cAAc,OAAO,eAAe,KAAK;AAC9C,OAAK,IAAI,OAAO,KAAK,KAAK;;CAG5B,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,eAAe;;CAI9B,IAAI,kBAA4B;AAC9B,SAAO,CAAC,KAAK,aAAa,KAAK,eAAe;;;;;;;CAShD,MAAM,oBAAoB,QAA+C;EACvE,MAAM,iBACJ,KAAK,aAAA,GAAA,uBAAA,mBAA8B,QAAQ,KAAK,gBAAgB;EAClE,MAAM,WAAW,MAAM,KAAK,YAAY,aAAa;EACrD,MAAM,sBAAA,GAAA,yBAAA,iBACJ,SAAS,MAAM,CAAC,KAAK,IAAI,EAAE,EAC3B,KAAK,aACL,KAAK,SACN;EACD,MAAM,SAAS,MAAM,KAAK,sBAAsB,QAAQ;GACtD,SAAS;GACT,OAAO,OAAO;GACf,CAAC;EACF,MAAM,WACJ,OAAO,MAAM,KAAK,SAAS,EAAE,GAAG,OAAO,MAAM,IAAI,CAAC,KAAK,MAAM,EAAE,MAAM,CAAC;EACxE,MAAM,kBAAyD,EAAE;AAEjE,OAAK,MAAM,UAAU,SACnB,iBAAgB,UAAU,MAAM,KAAK,YAAY,IAC/C,QACA,gCACD;AAEH,OAAK,cAAc,CAAC,GAAG,SAAS;EAChC,MAAM,SAAS,KAAK,iBAChB,SAAS,MAAM,CAAC,KAAK,IAAI,EAAE,GAC3B;AAEJ,SAAO;IACJ,KAAK,iBAAiB;IACtB,KAAK,cAAc;GACrB;;;;;;;;;CAWH,MAAM,YAAY,QAAqB,SAAsC;AAC3E,QAAM,MAAM,YAAY,QAAQ,QAAQ;EAExC,MAAM,iBACJ,KAAK,aAAA,GAAA,uBAAA,mBAA8B,QAAQ,KAAK,gBAAgB;EAElE,MAAM,sBAAA,GAAA,yBAAA,
|
|
1
|
+
{"version":3,"file":"entity_memory.cjs","names":["BaseChatMemory","LLMChain","ENTITY_EXTRACTION_PROMPT","ENTITY_SUMMARIZATION_PROMPT","InMemoryEntityStore"],"sources":["../../src/memory/entity_memory.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { PromptTemplate } from \"@langchain/core/prompts\";\n\nimport {\n InputValues,\n MemoryVariables,\n OutputValues,\n getPromptInputKey,\n} from \"@langchain/core/memory\";\nimport { getBufferString } from \"@langchain/core/messages\";\nimport { InMemoryEntityStore } from \"./stores/entity/in_memory.js\";\nimport { LLMChain } from \"../chains/llm_chain.js\";\nimport {\n ENTITY_EXTRACTION_PROMPT,\n ENTITY_SUMMARIZATION_PROMPT,\n} from \"./prompt.js\";\nimport { BaseEntityStore } from \"./stores/entity/base.js\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the input parameters required by the EntityMemory class.\n */\nexport interface EntityMemoryInput extends BaseChatMemoryInput {\n llm: BaseLanguageModelInterface;\n humanPrefix?: string;\n aiPrefix?: string;\n entityExtractionPrompt?: PromptTemplate;\n entitySummarizationPrompt?: PromptTemplate;\n entityCache?: string[];\n k?: number;\n chatHistoryKey?: string;\n entitiesKey?: string;\n entityStore?: BaseEntityStore;\n}\n\n// Entity extractor & summarizer to memory.\n/**\n * Class for managing entity extraction and summarization to memory in\n * chatbot applications. Extends the BaseChatMemory class and implements\n * the EntityMemoryInput interface.\n * @example\n * ```typescript\n * const memory = new EntityMemory({\n * llm: new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0 }),\n * chatHistoryKey: \"history\",\n * entitiesKey: \"entities\",\n * });\n * const model = new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0.9 });\n * const chain = new LLMChain({\n * llm: model,\n * prompt: ENTITY_MEMORY_CONVERSATION_TEMPLATE,\n * memory,\n * });\n *\n * const res1 = await chain.call({ input: \"Hi! I'm Jim.\" });\n * console.log({\n * res1,\n * memory: await memory.loadMemoryVariables({ input: \"Who is Jim?\" }),\n * });\n *\n * const res2 = await chain.call({\n * input: \"I work in construction. What about you?\",\n * });\n * console.log({\n * res2,\n * memory: await memory.loadMemoryVariables({ input: \"Who is Jim?\" }),\n * });\n *\n * ```\n */\nexport class EntityMemory extends BaseChatMemory implements EntityMemoryInput {\n private entityExtractionChain: LLMChain;\n\n private entitySummarizationChain: LLMChain;\n\n entityStore: BaseEntityStore;\n\n entityCache: string[] = [];\n\n k = 3;\n\n chatHistoryKey = \"history\";\n\n llm: BaseLanguageModelInterface;\n\n entitiesKey = \"entities\";\n\n humanPrefix?: string;\n\n aiPrefix?: string;\n\n constructor(fields: EntityMemoryInput) {\n super({\n chatHistory: fields.chatHistory,\n returnMessages: fields.returnMessages ?? false,\n inputKey: fields.inputKey,\n outputKey: fields.outputKey,\n });\n this.llm = fields.llm;\n this.humanPrefix = fields.humanPrefix;\n this.aiPrefix = fields.aiPrefix;\n this.chatHistoryKey = fields.chatHistoryKey ?? this.chatHistoryKey;\n this.entitiesKey = fields.entitiesKey ?? this.entitiesKey;\n this.entityExtractionChain = new LLMChain({\n llm: this.llm,\n prompt: fields.entityExtractionPrompt ?? ENTITY_EXTRACTION_PROMPT,\n });\n this.entitySummarizationChain = new LLMChain({\n llm: this.llm,\n prompt: fields.entitySummarizationPrompt ?? ENTITY_SUMMARIZATION_PROMPT,\n });\n this.entityStore = fields.entityStore ?? new InMemoryEntityStore();\n this.entityCache = fields.entityCache ?? this.entityCache;\n this.k = fields.k ?? this.k;\n }\n\n get memoryKeys() {\n return [this.chatHistoryKey];\n }\n\n // Will always return list of memory variables.\n get memoryVariables(): string[] {\n return [this.entitiesKey, this.chatHistoryKey];\n }\n\n // Return history buffer.\n /**\n * Method to load memory variables and perform entity extraction.\n * @param inputs Input values for the method.\n * @returns Promise resolving to an object containing memory variables.\n */\n async loadMemoryVariables(inputs: InputValues): Promise<MemoryVariables> {\n const promptInputKey =\n this.inputKey ?? getPromptInputKey(inputs, this.memoryVariables);\n const messages = await this.chatHistory.getMessages();\n const serializedMessages = getBufferString(\n messages.slice(-this.k * 2),\n this.humanPrefix,\n this.aiPrefix\n );\n const output = await this.entityExtractionChain.predict({\n history: serializedMessages,\n input: inputs[promptInputKey],\n });\n const entities: string[] =\n output.trim() === \"NONE\" ? [] : output.split(\",\").map((w) => w.trim());\n const entitySummaries: { [key: string]: string | undefined } = {};\n\n for (const entity of entities) {\n entitySummaries[entity] = await this.entityStore.get(\n entity,\n \"No current information known.\"\n );\n }\n this.entityCache = [...entities];\n const buffer = this.returnMessages\n ? messages.slice(-this.k * 2)\n : serializedMessages;\n\n return {\n [this.chatHistoryKey]: buffer,\n [this.entitiesKey]: entitySummaries,\n };\n }\n\n // Save context from this conversation to buffer.\n /**\n * Method to save the context from a conversation to a buffer and perform\n * entity summarization.\n * @param inputs Input values for the method.\n * @param outputs Output values from the method.\n * @returns Promise resolving to void.\n */\n async saveContext(inputs: InputValues, outputs: OutputValues): Promise<void> {\n await super.saveContext(inputs, outputs);\n\n const promptInputKey =\n this.inputKey ?? getPromptInputKey(inputs, this.memoryVariables);\n const messages = await this.chatHistory.getMessages();\n const serializedMessages = getBufferString(\n messages.slice(-this.k * 2),\n this.humanPrefix,\n this.aiPrefix\n );\n const inputData = inputs[promptInputKey];\n\n for (const entity of this.entityCache) {\n const existingSummary = await this.entityStore.get(\n entity,\n \"No current information known.\"\n );\n const output = await this.entitySummarizationChain.predict({\n summary: existingSummary,\n entity,\n history: serializedMessages,\n input: inputData,\n });\n if (output.trim() !== \"UNCHANGED\") {\n await this.entityStore.set(entity, output.trim());\n }\n }\n }\n\n // Clear memory contents.\n /**\n * Method to clear the memory contents.\n * @returns Promise resolving to void.\n */\n async clear() {\n await super.clear();\n await this.entityStore.clear();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,IAAa,eAAb,cAAkCA,2BAAAA,eAA4C;CAC5E;CAEA;CAEA;CAEA,cAAwB,EAAE;CAE1B,IAAI;CAEJ,iBAAiB;CAEjB;CAEA,cAAc;CAEd;CAEA;CAEA,YAAY,QAA2B;AACrC,QAAM;GACJ,aAAa,OAAO;GACpB,gBAAgB,OAAO,kBAAkB;GACzC,UAAU,OAAO;GACjB,WAAW,OAAO;GACnB,CAAC;AACF,OAAK,MAAM,OAAO;AAClB,OAAK,cAAc,OAAO;AAC1B,OAAK,WAAW,OAAO;AACvB,OAAK,iBAAiB,OAAO,kBAAkB,KAAK;AACpD,OAAK,cAAc,OAAO,eAAe,KAAK;AAC9C,OAAK,wBAAwB,IAAIC,kBAAAA,SAAS;GACxC,KAAK,KAAK;GACV,QAAQ,OAAO,0BAA0BC,eAAAA;GAC1C,CAAC;AACF,OAAK,2BAA2B,IAAID,kBAAAA,SAAS;GAC3C,KAAK,KAAK;GACV,QAAQ,OAAO,6BAA6BE,eAAAA;GAC7C,CAAC;AACF,OAAK,cAAc,OAAO,eAAe,IAAIC,kBAAAA,qBAAqB;AAClE,OAAK,cAAc,OAAO,eAAe,KAAK;AAC9C,OAAK,IAAI,OAAO,KAAK,KAAK;;CAG5B,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,eAAe;;CAI9B,IAAI,kBAA4B;AAC9B,SAAO,CAAC,KAAK,aAAa,KAAK,eAAe;;;;;;;CAShD,MAAM,oBAAoB,QAA+C;EACvE,MAAM,iBACJ,KAAK,aAAA,GAAA,uBAAA,mBAA8B,QAAQ,KAAK,gBAAgB;EAClE,MAAM,WAAW,MAAM,KAAK,YAAY,aAAa;EACrD,MAAM,sBAAA,GAAA,yBAAA,iBACJ,SAAS,MAAM,CAAC,KAAK,IAAI,EAAE,EAC3B,KAAK,aACL,KAAK,SACN;EACD,MAAM,SAAS,MAAM,KAAK,sBAAsB,QAAQ;GACtD,SAAS;GACT,OAAO,OAAO;GACf,CAAC;EACF,MAAM,WACJ,OAAO,MAAM,KAAK,SAAS,EAAE,GAAG,OAAO,MAAM,IAAI,CAAC,KAAK,MAAM,EAAE,MAAM,CAAC;EACxE,MAAM,kBAAyD,EAAE;AAEjE,OAAK,MAAM,UAAU,SACnB,iBAAgB,UAAU,MAAM,KAAK,YAAY,IAC/C,QACA,gCACD;AAEH,OAAK,cAAc,CAAC,GAAG,SAAS;EAChC,MAAM,SAAS,KAAK,iBAChB,SAAS,MAAM,CAAC,KAAK,IAAI,EAAE,GAC3B;AAEJ,SAAO;IACJ,KAAK,iBAAiB;IACtB,KAAK,cAAc;GACrB;;;;;;;;;CAWH,MAAM,YAAY,QAAqB,SAAsC;AAC3E,QAAM,MAAM,YAAY,QAAQ,QAAQ;EAExC,MAAM,iBACJ,KAAK,aAAA,GAAA,uBAAA,mBAA8B,QAAQ,KAAK,gBAAgB;EAElE,MAAM,sBAAA,GAAA,yBAAA,kBACJ,MAFqB,KAAK,YAAY,aAAa,EAE1C,MAAM,CAAC,KAAK,IAAI,EAAE,EAC3B,KAAK,aACL,KAAK,SACN;EACD,MAAM,YAAY,OAAO;AAEzB,OAAK,MAAM,UAAU,KAAK,aAAa;GACrC,MAAM,kBAAkB,MAAM,KAAK,YAAY,IAC7C,QACA,gCACD;GACD,MAAM,SAAS,MAAM,KAAK,yBAAyB,QAAQ;IACzD,SAAS;IACT;IACA,SAAS;IACT,OAAO;IACR,CAAC;AACF,OAAI,OAAO,MAAM,KAAK,YACpB,OAAM,KAAK,YAAY,IAAI,QAAQ,OAAO,MAAM,CAAC;;;;;;;CAUvD,MAAM,QAAQ;AACZ,QAAM,MAAM,OAAO;AACnB,QAAM,KAAK,YAAY,OAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entity_memory.js","names":[],"sources":["../../src/memory/entity_memory.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { PromptTemplate } from \"@langchain/core/prompts\";\n\nimport {\n InputValues,\n MemoryVariables,\n OutputValues,\n getPromptInputKey,\n} from \"@langchain/core/memory\";\nimport { getBufferString } from \"@langchain/core/messages\";\nimport { InMemoryEntityStore } from \"./stores/entity/in_memory.js\";\nimport { LLMChain } from \"../chains/llm_chain.js\";\nimport {\n ENTITY_EXTRACTION_PROMPT,\n ENTITY_SUMMARIZATION_PROMPT,\n} from \"./prompt.js\";\nimport { BaseEntityStore } from \"./stores/entity/base.js\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the input parameters required by the EntityMemory class.\n */\nexport interface EntityMemoryInput extends BaseChatMemoryInput {\n llm: BaseLanguageModelInterface;\n humanPrefix?: string;\n aiPrefix?: string;\n entityExtractionPrompt?: PromptTemplate;\n entitySummarizationPrompt?: PromptTemplate;\n entityCache?: string[];\n k?: number;\n chatHistoryKey?: string;\n entitiesKey?: string;\n entityStore?: BaseEntityStore;\n}\n\n// Entity extractor & summarizer to memory.\n/**\n * Class for managing entity extraction and summarization to memory in\n * chatbot applications. Extends the BaseChatMemory class and implements\n * the EntityMemoryInput interface.\n * @example\n * ```typescript\n * const memory = new EntityMemory({\n * llm: new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0 }),\n * chatHistoryKey: \"history\",\n * entitiesKey: \"entities\",\n * });\n * const model = new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0.9 });\n * const chain = new LLMChain({\n * llm: model,\n * prompt: ENTITY_MEMORY_CONVERSATION_TEMPLATE,\n * memory,\n * });\n *\n * const res1 = await chain.call({ input: \"Hi! I'm Jim.\" });\n * console.log({\n * res1,\n * memory: await memory.loadMemoryVariables({ input: \"Who is Jim?\" }),\n * });\n *\n * const res2 = await chain.call({\n * input: \"I work in construction. What about you?\",\n * });\n * console.log({\n * res2,\n * memory: await memory.loadMemoryVariables({ input: \"Who is Jim?\" }),\n * });\n *\n * ```\n */\nexport class EntityMemory extends BaseChatMemory implements EntityMemoryInput {\n private entityExtractionChain: LLMChain;\n\n private entitySummarizationChain: LLMChain;\n\n entityStore: BaseEntityStore;\n\n entityCache: string[] = [];\n\n k = 3;\n\n chatHistoryKey = \"history\";\n\n llm: BaseLanguageModelInterface;\n\n entitiesKey = \"entities\";\n\n humanPrefix?: string;\n\n aiPrefix?: string;\n\n constructor(fields: EntityMemoryInput) {\n super({\n chatHistory: fields.chatHistory,\n returnMessages: fields.returnMessages ?? false,\n inputKey: fields.inputKey,\n outputKey: fields.outputKey,\n });\n this.llm = fields.llm;\n this.humanPrefix = fields.humanPrefix;\n this.aiPrefix = fields.aiPrefix;\n this.chatHistoryKey = fields.chatHistoryKey ?? this.chatHistoryKey;\n this.entitiesKey = fields.entitiesKey ?? this.entitiesKey;\n this.entityExtractionChain = new LLMChain({\n llm: this.llm,\n prompt: fields.entityExtractionPrompt ?? ENTITY_EXTRACTION_PROMPT,\n });\n this.entitySummarizationChain = new LLMChain({\n llm: this.llm,\n prompt: fields.entitySummarizationPrompt ?? ENTITY_SUMMARIZATION_PROMPT,\n });\n this.entityStore = fields.entityStore ?? new InMemoryEntityStore();\n this.entityCache = fields.entityCache ?? this.entityCache;\n this.k = fields.k ?? this.k;\n }\n\n get memoryKeys() {\n return [this.chatHistoryKey];\n }\n\n // Will always return list of memory variables.\n get memoryVariables(): string[] {\n return [this.entitiesKey, this.chatHistoryKey];\n }\n\n // Return history buffer.\n /**\n * Method to load memory variables and perform entity extraction.\n * @param inputs Input values for the method.\n * @returns Promise resolving to an object containing memory variables.\n */\n async loadMemoryVariables(inputs: InputValues): Promise<MemoryVariables> {\n const promptInputKey =\n this.inputKey ?? getPromptInputKey(inputs, this.memoryVariables);\n const messages = await this.chatHistory.getMessages();\n const serializedMessages = getBufferString(\n messages.slice(-this.k * 2),\n this.humanPrefix,\n this.aiPrefix\n );\n const output = await this.entityExtractionChain.predict({\n history: serializedMessages,\n input: inputs[promptInputKey],\n });\n const entities: string[] =\n output.trim() === \"NONE\" ? [] : output.split(\",\").map((w) => w.trim());\n const entitySummaries: { [key: string]: string | undefined } = {};\n\n for (const entity of entities) {\n entitySummaries[entity] = await this.entityStore.get(\n entity,\n \"No current information known.\"\n );\n }\n this.entityCache = [...entities];\n const buffer = this.returnMessages\n ? messages.slice(-this.k * 2)\n : serializedMessages;\n\n return {\n [this.chatHistoryKey]: buffer,\n [this.entitiesKey]: entitySummaries,\n };\n }\n\n // Save context from this conversation to buffer.\n /**\n * Method to save the context from a conversation to a buffer and perform\n * entity summarization.\n * @param inputs Input values for the method.\n * @param outputs Output values from the method.\n * @returns Promise resolving to void.\n */\n async saveContext(inputs: InputValues, outputs: OutputValues): Promise<void> {\n await super.saveContext(inputs, outputs);\n\n const promptInputKey =\n this.inputKey ?? getPromptInputKey(inputs, this.memoryVariables);\n const messages = await this.chatHistory.getMessages();\n const serializedMessages = getBufferString(\n messages.slice(-this.k * 2),\n this.humanPrefix,\n this.aiPrefix\n );\n const inputData = inputs[promptInputKey];\n\n for (const entity of this.entityCache) {\n const existingSummary = await this.entityStore.get(\n entity,\n \"No current information known.\"\n );\n const output = await this.entitySummarizationChain.predict({\n summary: existingSummary,\n entity,\n history: serializedMessages,\n input: inputData,\n });\n if (output.trim() !== \"UNCHANGED\") {\n await this.entityStore.set(entity, output.trim());\n }\n }\n }\n\n // Clear memory contents.\n /**\n * Method to clear the memory contents.\n * @returns Promise resolving to void.\n */\n async clear() {\n await super.clear();\n await this.entityStore.clear();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,IAAa,eAAb,cAAkC,eAA4C;CAC5E;CAEA;CAEA;CAEA,cAAwB,EAAE;CAE1B,IAAI;CAEJ,iBAAiB;CAEjB;CAEA,cAAc;CAEd;CAEA;CAEA,YAAY,QAA2B;AACrC,QAAM;GACJ,aAAa,OAAO;GACpB,gBAAgB,OAAO,kBAAkB;GACzC,UAAU,OAAO;GACjB,WAAW,OAAO;GACnB,CAAC;AACF,OAAK,MAAM,OAAO;AAClB,OAAK,cAAc,OAAO;AAC1B,OAAK,WAAW,OAAO;AACvB,OAAK,iBAAiB,OAAO,kBAAkB,KAAK;AACpD,OAAK,cAAc,OAAO,eAAe,KAAK;AAC9C,OAAK,wBAAwB,IAAI,SAAS;GACxC,KAAK,KAAK;GACV,QAAQ,OAAO,0BAA0B;GAC1C,CAAC;AACF,OAAK,2BAA2B,IAAI,SAAS;GAC3C,KAAK,KAAK;GACV,QAAQ,OAAO,6BAA6B;GAC7C,CAAC;AACF,OAAK,cAAc,OAAO,eAAe,IAAI,qBAAqB;AAClE,OAAK,cAAc,OAAO,eAAe,KAAK;AAC9C,OAAK,IAAI,OAAO,KAAK,KAAK;;CAG5B,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,eAAe;;CAI9B,IAAI,kBAA4B;AAC9B,SAAO,CAAC,KAAK,aAAa,KAAK,eAAe;;;;;;;CAShD,MAAM,oBAAoB,QAA+C;EACvE,MAAM,iBACJ,KAAK,YAAY,kBAAkB,QAAQ,KAAK,gBAAgB;EAClE,MAAM,WAAW,MAAM,KAAK,YAAY,aAAa;EACrD,MAAM,qBAAqB,gBACzB,SAAS,MAAM,CAAC,KAAK,IAAI,EAAE,EAC3B,KAAK,aACL,KAAK,SACN;EACD,MAAM,SAAS,MAAM,KAAK,sBAAsB,QAAQ;GACtD,SAAS;GACT,OAAO,OAAO;GACf,CAAC;EACF,MAAM,WACJ,OAAO,MAAM,KAAK,SAAS,EAAE,GAAG,OAAO,MAAM,IAAI,CAAC,KAAK,MAAM,EAAE,MAAM,CAAC;EACxE,MAAM,kBAAyD,EAAE;AAEjE,OAAK,MAAM,UAAU,SACnB,iBAAgB,UAAU,MAAM,KAAK,YAAY,IAC/C,QACA,gCACD;AAEH,OAAK,cAAc,CAAC,GAAG,SAAS;EAChC,MAAM,SAAS,KAAK,iBAChB,SAAS,MAAM,CAAC,KAAK,IAAI,EAAE,GAC3B;AAEJ,SAAO;IACJ,KAAK,iBAAiB;IACtB,KAAK,cAAc;GACrB;;;;;;;;;CAWH,MAAM,YAAY,QAAqB,SAAsC;AAC3E,QAAM,MAAM,YAAY,QAAQ,QAAQ;EAExC,MAAM,iBACJ,KAAK,YAAY,kBAAkB,QAAQ,KAAK,gBAAgB;EAElE,MAAM,qBAAqB,
|
|
1
|
+
{"version":3,"file":"entity_memory.js","names":[],"sources":["../../src/memory/entity_memory.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { PromptTemplate } from \"@langchain/core/prompts\";\n\nimport {\n InputValues,\n MemoryVariables,\n OutputValues,\n getPromptInputKey,\n} from \"@langchain/core/memory\";\nimport { getBufferString } from \"@langchain/core/messages\";\nimport { InMemoryEntityStore } from \"./stores/entity/in_memory.js\";\nimport { LLMChain } from \"../chains/llm_chain.js\";\nimport {\n ENTITY_EXTRACTION_PROMPT,\n ENTITY_SUMMARIZATION_PROMPT,\n} from \"./prompt.js\";\nimport { BaseEntityStore } from \"./stores/entity/base.js\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the input parameters required by the EntityMemory class.\n */\nexport interface EntityMemoryInput extends BaseChatMemoryInput {\n llm: BaseLanguageModelInterface;\n humanPrefix?: string;\n aiPrefix?: string;\n entityExtractionPrompt?: PromptTemplate;\n entitySummarizationPrompt?: PromptTemplate;\n entityCache?: string[];\n k?: number;\n chatHistoryKey?: string;\n entitiesKey?: string;\n entityStore?: BaseEntityStore;\n}\n\n// Entity extractor & summarizer to memory.\n/**\n * Class for managing entity extraction and summarization to memory in\n * chatbot applications. Extends the BaseChatMemory class and implements\n * the EntityMemoryInput interface.\n * @example\n * ```typescript\n * const memory = new EntityMemory({\n * llm: new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0 }),\n * chatHistoryKey: \"history\",\n * entitiesKey: \"entities\",\n * });\n * const model = new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0.9 });\n * const chain = new LLMChain({\n * llm: model,\n * prompt: ENTITY_MEMORY_CONVERSATION_TEMPLATE,\n * memory,\n * });\n *\n * const res1 = await chain.call({ input: \"Hi! I'm Jim.\" });\n * console.log({\n * res1,\n * memory: await memory.loadMemoryVariables({ input: \"Who is Jim?\" }),\n * });\n *\n * const res2 = await chain.call({\n * input: \"I work in construction. What about you?\",\n * });\n * console.log({\n * res2,\n * memory: await memory.loadMemoryVariables({ input: \"Who is Jim?\" }),\n * });\n *\n * ```\n */\nexport class EntityMemory extends BaseChatMemory implements EntityMemoryInput {\n private entityExtractionChain: LLMChain;\n\n private entitySummarizationChain: LLMChain;\n\n entityStore: BaseEntityStore;\n\n entityCache: string[] = [];\n\n k = 3;\n\n chatHistoryKey = \"history\";\n\n llm: BaseLanguageModelInterface;\n\n entitiesKey = \"entities\";\n\n humanPrefix?: string;\n\n aiPrefix?: string;\n\n constructor(fields: EntityMemoryInput) {\n super({\n chatHistory: fields.chatHistory,\n returnMessages: fields.returnMessages ?? false,\n inputKey: fields.inputKey,\n outputKey: fields.outputKey,\n });\n this.llm = fields.llm;\n this.humanPrefix = fields.humanPrefix;\n this.aiPrefix = fields.aiPrefix;\n this.chatHistoryKey = fields.chatHistoryKey ?? this.chatHistoryKey;\n this.entitiesKey = fields.entitiesKey ?? this.entitiesKey;\n this.entityExtractionChain = new LLMChain({\n llm: this.llm,\n prompt: fields.entityExtractionPrompt ?? ENTITY_EXTRACTION_PROMPT,\n });\n this.entitySummarizationChain = new LLMChain({\n llm: this.llm,\n prompt: fields.entitySummarizationPrompt ?? ENTITY_SUMMARIZATION_PROMPT,\n });\n this.entityStore = fields.entityStore ?? new InMemoryEntityStore();\n this.entityCache = fields.entityCache ?? this.entityCache;\n this.k = fields.k ?? this.k;\n }\n\n get memoryKeys() {\n return [this.chatHistoryKey];\n }\n\n // Will always return list of memory variables.\n get memoryVariables(): string[] {\n return [this.entitiesKey, this.chatHistoryKey];\n }\n\n // Return history buffer.\n /**\n * Method to load memory variables and perform entity extraction.\n * @param inputs Input values for the method.\n * @returns Promise resolving to an object containing memory variables.\n */\n async loadMemoryVariables(inputs: InputValues): Promise<MemoryVariables> {\n const promptInputKey =\n this.inputKey ?? getPromptInputKey(inputs, this.memoryVariables);\n const messages = await this.chatHistory.getMessages();\n const serializedMessages = getBufferString(\n messages.slice(-this.k * 2),\n this.humanPrefix,\n this.aiPrefix\n );\n const output = await this.entityExtractionChain.predict({\n history: serializedMessages,\n input: inputs[promptInputKey],\n });\n const entities: string[] =\n output.trim() === \"NONE\" ? [] : output.split(\",\").map((w) => w.trim());\n const entitySummaries: { [key: string]: string | undefined } = {};\n\n for (const entity of entities) {\n entitySummaries[entity] = await this.entityStore.get(\n entity,\n \"No current information known.\"\n );\n }\n this.entityCache = [...entities];\n const buffer = this.returnMessages\n ? messages.slice(-this.k * 2)\n : serializedMessages;\n\n return {\n [this.chatHistoryKey]: buffer,\n [this.entitiesKey]: entitySummaries,\n };\n }\n\n // Save context from this conversation to buffer.\n /**\n * Method to save the context from a conversation to a buffer and perform\n * entity summarization.\n * @param inputs Input values for the method.\n * @param outputs Output values from the method.\n * @returns Promise resolving to void.\n */\n async saveContext(inputs: InputValues, outputs: OutputValues): Promise<void> {\n await super.saveContext(inputs, outputs);\n\n const promptInputKey =\n this.inputKey ?? getPromptInputKey(inputs, this.memoryVariables);\n const messages = await this.chatHistory.getMessages();\n const serializedMessages = getBufferString(\n messages.slice(-this.k * 2),\n this.humanPrefix,\n this.aiPrefix\n );\n const inputData = inputs[promptInputKey];\n\n for (const entity of this.entityCache) {\n const existingSummary = await this.entityStore.get(\n entity,\n \"No current information known.\"\n );\n const output = await this.entitySummarizationChain.predict({\n summary: existingSummary,\n entity,\n history: serializedMessages,\n input: inputData,\n });\n if (output.trim() !== \"UNCHANGED\") {\n await this.entityStore.set(entity, output.trim());\n }\n }\n }\n\n // Clear memory contents.\n /**\n * Method to clear the memory contents.\n * @returns Promise resolving to void.\n */\n async clear() {\n await super.clear();\n await this.entityStore.clear();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,IAAa,eAAb,cAAkC,eAA4C;CAC5E;CAEA;CAEA;CAEA,cAAwB,EAAE;CAE1B,IAAI;CAEJ,iBAAiB;CAEjB;CAEA,cAAc;CAEd;CAEA;CAEA,YAAY,QAA2B;AACrC,QAAM;GACJ,aAAa,OAAO;GACpB,gBAAgB,OAAO,kBAAkB;GACzC,UAAU,OAAO;GACjB,WAAW,OAAO;GACnB,CAAC;AACF,OAAK,MAAM,OAAO;AAClB,OAAK,cAAc,OAAO;AAC1B,OAAK,WAAW,OAAO;AACvB,OAAK,iBAAiB,OAAO,kBAAkB,KAAK;AACpD,OAAK,cAAc,OAAO,eAAe,KAAK;AAC9C,OAAK,wBAAwB,IAAI,SAAS;GACxC,KAAK,KAAK;GACV,QAAQ,OAAO,0BAA0B;GAC1C,CAAC;AACF,OAAK,2BAA2B,IAAI,SAAS;GAC3C,KAAK,KAAK;GACV,QAAQ,OAAO,6BAA6B;GAC7C,CAAC;AACF,OAAK,cAAc,OAAO,eAAe,IAAI,qBAAqB;AAClE,OAAK,cAAc,OAAO,eAAe,KAAK;AAC9C,OAAK,IAAI,OAAO,KAAK,KAAK;;CAG5B,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,eAAe;;CAI9B,IAAI,kBAA4B;AAC9B,SAAO,CAAC,KAAK,aAAa,KAAK,eAAe;;;;;;;CAShD,MAAM,oBAAoB,QAA+C;EACvE,MAAM,iBACJ,KAAK,YAAY,kBAAkB,QAAQ,KAAK,gBAAgB;EAClE,MAAM,WAAW,MAAM,KAAK,YAAY,aAAa;EACrD,MAAM,qBAAqB,gBACzB,SAAS,MAAM,CAAC,KAAK,IAAI,EAAE,EAC3B,KAAK,aACL,KAAK,SACN;EACD,MAAM,SAAS,MAAM,KAAK,sBAAsB,QAAQ;GACtD,SAAS;GACT,OAAO,OAAO;GACf,CAAC;EACF,MAAM,WACJ,OAAO,MAAM,KAAK,SAAS,EAAE,GAAG,OAAO,MAAM,IAAI,CAAC,KAAK,MAAM,EAAE,MAAM,CAAC;EACxE,MAAM,kBAAyD,EAAE;AAEjE,OAAK,MAAM,UAAU,SACnB,iBAAgB,UAAU,MAAM,KAAK,YAAY,IAC/C,QACA,gCACD;AAEH,OAAK,cAAc,CAAC,GAAG,SAAS;EAChC,MAAM,SAAS,KAAK,iBAChB,SAAS,MAAM,CAAC,KAAK,IAAI,EAAE,GAC3B;AAEJ,SAAO;IACJ,KAAK,iBAAiB;IACtB,KAAK,cAAc;GACrB;;;;;;;;;CAWH,MAAM,YAAY,QAAqB,SAAsC;AAC3E,QAAM,MAAM,YAAY,QAAQ,QAAQ;EAExC,MAAM,iBACJ,KAAK,YAAY,kBAAkB,QAAQ,KAAK,gBAAgB;EAElE,MAAM,qBAAqB,iBACzB,MAFqB,KAAK,YAAY,aAAa,EAE1C,MAAM,CAAC,KAAK,IAAI,EAAE,EAC3B,KAAK,aACL,KAAK,SACN;EACD,MAAM,YAAY,OAAO;AAEzB,OAAK,MAAM,UAAU,KAAK,aAAa;GACrC,MAAM,kBAAkB,MAAM,KAAK,YAAY,IAC7C,QACA,gCACD;GACD,MAAM,SAAS,MAAM,KAAK,yBAAyB,QAAQ;IACzD,SAAS;IACT;IACA,SAAS;IACT,OAAO;IACR,CAAC;AACF,OAAI,OAAO,MAAM,KAAK,YACpB,OAAM,KAAK,YAAY,IAAI,QAAQ,OAAO,MAAM,CAAC;;;;;;;CAUvD,MAAM,QAAQ;AACZ,QAAM,MAAM,OAAO;AACnB,QAAM,KAAK,YAAY,OAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt.cjs","names":["PromptTemplate"],"sources":["../../src/memory/prompt.ts"],"sourcesContent":["import { PromptTemplate } from \"@langchain/core/prompts\";\n\nconst _DEFAULT_SUMMARIZER_TEMPLATE = `Progressively summarize the lines of conversation provided, adding onto the previous summary returning a new summary.\n\nEXAMPLE\nCurrent summary:\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good.\n\nNew lines of conversation:\nHuman: Why do you think artificial intelligence is a force for good?\nAI: Because artificial intelligence will help humans reach their full potential.\n\nNew summary:\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential.\nEND OF EXAMPLE\n\nCurrent summary:\n{summary}\n\nNew lines of conversation:\n{new_lines}\n\nNew summary:`;\n\nexport const SUMMARY_PROMPT = /*#__PURE__*/ new PromptTemplate({\n inputVariables: [\"summary\", \"new_lines\"],\n template: _DEFAULT_SUMMARIZER_TEMPLATE,\n});\n\nexport const _DEFAULT_ENTITY_MEMORY_CONVERSATION_TEMPLATE = `You are an assistant to a human, powered by a large language model trained by OpenAI.\n\nYou are designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, you are able to generate human-like text based on the input you receive, allowing you to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.\n\nYou are constantly learning and improving, and your capabilities are constantly evolving. You are able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. You have access to some personalized information provided by the human in the Context section below. Additionally, you are able to generate your own text based on the input you receive, allowing you to engage in discussions and provide explanations and descriptions on a wide range of topics.\n\nOverall, you are a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether the human needs help with a specific question or just wants to have a conversation about a particular topic, you are here to assist.\n\nContext:\n{entities}\n\nCurrent conversation:\n{history}\nLast line:\nHuman: {input}\nYou:`;\n\nexport const ENTITY_MEMORY_CONVERSATION_TEMPLATE =\n /*#__PURE__*/ new PromptTemplate({\n inputVariables: [\"entities\", \"history\", \"input\"],\n template: _DEFAULT_ENTITY_MEMORY_CONVERSATION_TEMPLATE,\n });\n\nexport const _DEFAULT_ENTITY_EXTRACTION_TEMPLATE = `You are an AI assistant reading the transcript of a conversation between an AI and a human. Extract all of the proper nouns from the last line of conversation. As a guideline, a proper noun is generally capitalized. You should definitely extract all names and places.\n\nThe conversation history is provided just in case of a coreference (e.g. \"What do you know about him\" where \"him\" is defined in a previous line) -- ignore items mentioned there that are not in the last line.\n\nReturn the output as a single comma-separated list, or NONE if there is nothing of note to return (e.g. the user is just issuing a greeting or having a simple conversation).\n\nEXAMPLE\nConversation history:\nPerson #1: my name is Jacob. how's it going today?\nAI: \"It's going great! How about you?\"\nPerson #1: good! busy working on Langchain. lots to do.\nAI: \"That sounds like a lot of work! What kind of things are you doing to make Langchain better?\"\nLast line:\nPerson #1: i'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff.\nOutput: Jacob,Langchain\nEND OF EXAMPLE\n\nEXAMPLE\nConversation history:\nPerson #1: how's it going today?\nAI: \"It's going great! How about you?\"\nPerson #1: good! busy working on Langchain. lots to do.\nAI: \"That sounds like a lot of work! What kind of things are you doing to make Langchain better?\"\nLast line:\nPerson #1: i'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I'm working with Person #2.\nOutput: Langchain, Person #2\nEND OF EXAMPLE\n\nConversation history (for reference only):\n{history}\nLast line of conversation (for extraction):\nHuman: {input}\n\nOutput:`;\n\nexport const ENTITY_EXTRACTION_PROMPT = /*#__PURE__*/ new PromptTemplate({\n inputVariables: [\"history\", \"input\"],\n template: _DEFAULT_ENTITY_EXTRACTION_TEMPLATE,\n});\n\nexport const _DEFAULT_ENTITY_SUMMARIZATION_TEMPLATE = `You are an AI assistant helping a human keep track of facts about relevant people, places, and concepts in their life. Update and add to the summary of the provided entity in the \"Entity\" section based on the last line of your conversation with the human. If you are writing the summary for the first time, return a single sentence.\nThe update should only include facts that are relayed in the last line of conversation about the provided entity, and should only contain facts about the provided entity.\n\nIf there is no new information about the provided entity or the information is not worth noting (not an important or relevant fact to remember long-term), output the exact string \"UNCHANGED\" below.\n\nFull conversation history (for context):\n{history}\n\nEntity to summarize:\n{entity}\n\nExisting summary of {entity}:\n{summary}\n\nLast line of conversation:\nHuman: {input}\nUpdated summary (or the exact string \"UNCHANGED\" if there is no new information about {entity} above):`;\n\nexport const ENTITY_SUMMARIZATION_PROMPT = /*#__PURE__*/ new PromptTemplate({\n inputVariables: [\"entity\", \"summary\", \"history\", \"input\"],\n template: _DEFAULT_ENTITY_SUMMARIZATION_TEMPLATE,\n});\n"],"mappings":";;AAwBA,MAAa,iCAA+B,IAAIA,wBAAAA,eAAe;CAC7D,gBAAgB,CAAC,WAAW,YAAY;CACxC,
|
|
1
|
+
{"version":3,"file":"prompt.cjs","names":["PromptTemplate"],"sources":["../../src/memory/prompt.ts"],"sourcesContent":["import { PromptTemplate } from \"@langchain/core/prompts\";\n\nconst _DEFAULT_SUMMARIZER_TEMPLATE = `Progressively summarize the lines of conversation provided, adding onto the previous summary returning a new summary.\n\nEXAMPLE\nCurrent summary:\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good.\n\nNew lines of conversation:\nHuman: Why do you think artificial intelligence is a force for good?\nAI: Because artificial intelligence will help humans reach their full potential.\n\nNew summary:\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential.\nEND OF EXAMPLE\n\nCurrent summary:\n{summary}\n\nNew lines of conversation:\n{new_lines}\n\nNew summary:`;\n\nexport const SUMMARY_PROMPT = /*#__PURE__*/ new PromptTemplate({\n inputVariables: [\"summary\", \"new_lines\"],\n template: _DEFAULT_SUMMARIZER_TEMPLATE,\n});\n\nexport const _DEFAULT_ENTITY_MEMORY_CONVERSATION_TEMPLATE = `You are an assistant to a human, powered by a large language model trained by OpenAI.\n\nYou are designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, you are able to generate human-like text based on the input you receive, allowing you to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.\n\nYou are constantly learning and improving, and your capabilities are constantly evolving. You are able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. You have access to some personalized information provided by the human in the Context section below. Additionally, you are able to generate your own text based on the input you receive, allowing you to engage in discussions and provide explanations and descriptions on a wide range of topics.\n\nOverall, you are a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether the human needs help with a specific question or just wants to have a conversation about a particular topic, you are here to assist.\n\nContext:\n{entities}\n\nCurrent conversation:\n{history}\nLast line:\nHuman: {input}\nYou:`;\n\nexport const ENTITY_MEMORY_CONVERSATION_TEMPLATE =\n /*#__PURE__*/ new PromptTemplate({\n inputVariables: [\"entities\", \"history\", \"input\"],\n template: _DEFAULT_ENTITY_MEMORY_CONVERSATION_TEMPLATE,\n });\n\nexport const _DEFAULT_ENTITY_EXTRACTION_TEMPLATE = `You are an AI assistant reading the transcript of a conversation between an AI and a human. Extract all of the proper nouns from the last line of conversation. As a guideline, a proper noun is generally capitalized. You should definitely extract all names and places.\n\nThe conversation history is provided just in case of a coreference (e.g. \"What do you know about him\" where \"him\" is defined in a previous line) -- ignore items mentioned there that are not in the last line.\n\nReturn the output as a single comma-separated list, or NONE if there is nothing of note to return (e.g. the user is just issuing a greeting or having a simple conversation).\n\nEXAMPLE\nConversation history:\nPerson #1: my name is Jacob. how's it going today?\nAI: \"It's going great! How about you?\"\nPerson #1: good! busy working on Langchain. lots to do.\nAI: \"That sounds like a lot of work! What kind of things are you doing to make Langchain better?\"\nLast line:\nPerson #1: i'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff.\nOutput: Jacob,Langchain\nEND OF EXAMPLE\n\nEXAMPLE\nConversation history:\nPerson #1: how's it going today?\nAI: \"It's going great! How about you?\"\nPerson #1: good! busy working on Langchain. lots to do.\nAI: \"That sounds like a lot of work! What kind of things are you doing to make Langchain better?\"\nLast line:\nPerson #1: i'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I'm working with Person #2.\nOutput: Langchain, Person #2\nEND OF EXAMPLE\n\nConversation history (for reference only):\n{history}\nLast line of conversation (for extraction):\nHuman: {input}\n\nOutput:`;\n\nexport const ENTITY_EXTRACTION_PROMPT = /*#__PURE__*/ new PromptTemplate({\n inputVariables: [\"history\", \"input\"],\n template: _DEFAULT_ENTITY_EXTRACTION_TEMPLATE,\n});\n\nexport const _DEFAULT_ENTITY_SUMMARIZATION_TEMPLATE = `You are an AI assistant helping a human keep track of facts about relevant people, places, and concepts in their life. Update and add to the summary of the provided entity in the \"Entity\" section based on the last line of your conversation with the human. If you are writing the summary for the first time, return a single sentence.\nThe update should only include facts that are relayed in the last line of conversation about the provided entity, and should only contain facts about the provided entity.\n\nIf there is no new information about the provided entity or the information is not worth noting (not an important or relevant fact to remember long-term), output the exact string \"UNCHANGED\" below.\n\nFull conversation history (for context):\n{history}\n\nEntity to summarize:\n{entity}\n\nExisting summary of {entity}:\n{summary}\n\nLast line of conversation:\nHuman: {input}\nUpdated summary (or the exact string \"UNCHANGED\" if there is no new information about {entity} above):`;\n\nexport const ENTITY_SUMMARIZATION_PROMPT = /*#__PURE__*/ new PromptTemplate({\n inputVariables: [\"entity\", \"summary\", \"history\", \"input\"],\n template: _DEFAULT_ENTITY_SUMMARIZATION_TEMPLATE,\n});\n"],"mappings":";;AAwBA,MAAa,iCAA+B,IAAIA,wBAAAA,eAAe;CAC7D,gBAAgB,CAAC,WAAW,YAAY;CACxC,UAAU;;;;;;;;;;;;;;;;;;;;;CACX,CAAC;AAmBF,MAAa,sDACG,IAAIA,wBAAAA,eAAe;CAC/B,gBAAgB;EAAC;EAAY;EAAW;EAAQ;CAChD,UAAU;;;;;;;;;;;;;;;;CACX,CAAC;AAqCJ,MAAa,2CAAyC,IAAIA,wBAAAA,eAAe;CACvE,gBAAgB,CAAC,WAAW,QAAQ;CACpC,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CACX,CAAC;AAoBF,MAAa,8CAA4C,IAAIA,wBAAAA,eAAe;CAC1E,gBAAgB;EAAC;EAAU;EAAW;EAAW;EAAQ;CACzD,UAAU;;;;;;;;;;;;;;;;;CACX,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt.js","names":[],"sources":["../../src/memory/prompt.ts"],"sourcesContent":["import { PromptTemplate } from \"@langchain/core/prompts\";\n\nconst _DEFAULT_SUMMARIZER_TEMPLATE = `Progressively summarize the lines of conversation provided, adding onto the previous summary returning a new summary.\n\nEXAMPLE\nCurrent summary:\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good.\n\nNew lines of conversation:\nHuman: Why do you think artificial intelligence is a force for good?\nAI: Because artificial intelligence will help humans reach their full potential.\n\nNew summary:\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential.\nEND OF EXAMPLE\n\nCurrent summary:\n{summary}\n\nNew lines of conversation:\n{new_lines}\n\nNew summary:`;\n\nexport const SUMMARY_PROMPT = /*#__PURE__*/ new PromptTemplate({\n inputVariables: [\"summary\", \"new_lines\"],\n template: _DEFAULT_SUMMARIZER_TEMPLATE,\n});\n\nexport const _DEFAULT_ENTITY_MEMORY_CONVERSATION_TEMPLATE = `You are an assistant to a human, powered by a large language model trained by OpenAI.\n\nYou are designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, you are able to generate human-like text based on the input you receive, allowing you to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.\n\nYou are constantly learning and improving, and your capabilities are constantly evolving. You are able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. You have access to some personalized information provided by the human in the Context section below. Additionally, you are able to generate your own text based on the input you receive, allowing you to engage in discussions and provide explanations and descriptions on a wide range of topics.\n\nOverall, you are a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether the human needs help with a specific question or just wants to have a conversation about a particular topic, you are here to assist.\n\nContext:\n{entities}\n\nCurrent conversation:\n{history}\nLast line:\nHuman: {input}\nYou:`;\n\nexport const ENTITY_MEMORY_CONVERSATION_TEMPLATE =\n /*#__PURE__*/ new PromptTemplate({\n inputVariables: [\"entities\", \"history\", \"input\"],\n template: _DEFAULT_ENTITY_MEMORY_CONVERSATION_TEMPLATE,\n });\n\nexport const _DEFAULT_ENTITY_EXTRACTION_TEMPLATE = `You are an AI assistant reading the transcript of a conversation between an AI and a human. Extract all of the proper nouns from the last line of conversation. As a guideline, a proper noun is generally capitalized. You should definitely extract all names and places.\n\nThe conversation history is provided just in case of a coreference (e.g. \"What do you know about him\" where \"him\" is defined in a previous line) -- ignore items mentioned there that are not in the last line.\n\nReturn the output as a single comma-separated list, or NONE if there is nothing of note to return (e.g. the user is just issuing a greeting or having a simple conversation).\n\nEXAMPLE\nConversation history:\nPerson #1: my name is Jacob. how's it going today?\nAI: \"It's going great! How about you?\"\nPerson #1: good! busy working on Langchain. lots to do.\nAI: \"That sounds like a lot of work! What kind of things are you doing to make Langchain better?\"\nLast line:\nPerson #1: i'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff.\nOutput: Jacob,Langchain\nEND OF EXAMPLE\n\nEXAMPLE\nConversation history:\nPerson #1: how's it going today?\nAI: \"It's going great! How about you?\"\nPerson #1: good! busy working on Langchain. lots to do.\nAI: \"That sounds like a lot of work! What kind of things are you doing to make Langchain better?\"\nLast line:\nPerson #1: i'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I'm working with Person #2.\nOutput: Langchain, Person #2\nEND OF EXAMPLE\n\nConversation history (for reference only):\n{history}\nLast line of conversation (for extraction):\nHuman: {input}\n\nOutput:`;\n\nexport const ENTITY_EXTRACTION_PROMPT = /*#__PURE__*/ new PromptTemplate({\n inputVariables: [\"history\", \"input\"],\n template: _DEFAULT_ENTITY_EXTRACTION_TEMPLATE,\n});\n\nexport const _DEFAULT_ENTITY_SUMMARIZATION_TEMPLATE = `You are an AI assistant helping a human keep track of facts about relevant people, places, and concepts in their life. Update and add to the summary of the provided entity in the \"Entity\" section based on the last line of your conversation with the human. If you are writing the summary for the first time, return a single sentence.\nThe update should only include facts that are relayed in the last line of conversation about the provided entity, and should only contain facts about the provided entity.\n\nIf there is no new information about the provided entity or the information is not worth noting (not an important or relevant fact to remember long-term), output the exact string \"UNCHANGED\" below.\n\nFull conversation history (for context):\n{history}\n\nEntity to summarize:\n{entity}\n\nExisting summary of {entity}:\n{summary}\n\nLast line of conversation:\nHuman: {input}\nUpdated summary (or the exact string \"UNCHANGED\" if there is no new information about {entity} above):`;\n\nexport const ENTITY_SUMMARIZATION_PROMPT = /*#__PURE__*/ new PromptTemplate({\n inputVariables: [\"entity\", \"summary\", \"history\", \"input\"],\n template: _DEFAULT_ENTITY_SUMMARIZATION_TEMPLATE,\n});\n"],"mappings":";AAwBA,MAAa,iCAA+B,IAAI,eAAe;CAC7D,gBAAgB,CAAC,WAAW,YAAY;CACxC,
|
|
1
|
+
{"version":3,"file":"prompt.js","names":[],"sources":["../../src/memory/prompt.ts"],"sourcesContent":["import { PromptTemplate } from \"@langchain/core/prompts\";\n\nconst _DEFAULT_SUMMARIZER_TEMPLATE = `Progressively summarize the lines of conversation provided, adding onto the previous summary returning a new summary.\n\nEXAMPLE\nCurrent summary:\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good.\n\nNew lines of conversation:\nHuman: Why do you think artificial intelligence is a force for good?\nAI: Because artificial intelligence will help humans reach their full potential.\n\nNew summary:\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential.\nEND OF EXAMPLE\n\nCurrent summary:\n{summary}\n\nNew lines of conversation:\n{new_lines}\n\nNew summary:`;\n\nexport const SUMMARY_PROMPT = /*#__PURE__*/ new PromptTemplate({\n inputVariables: [\"summary\", \"new_lines\"],\n template: _DEFAULT_SUMMARIZER_TEMPLATE,\n});\n\nexport const _DEFAULT_ENTITY_MEMORY_CONVERSATION_TEMPLATE = `You are an assistant to a human, powered by a large language model trained by OpenAI.\n\nYou are designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, you are able to generate human-like text based on the input you receive, allowing you to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.\n\nYou are constantly learning and improving, and your capabilities are constantly evolving. You are able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. You have access to some personalized information provided by the human in the Context section below. Additionally, you are able to generate your own text based on the input you receive, allowing you to engage in discussions and provide explanations and descriptions on a wide range of topics.\n\nOverall, you are a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether the human needs help with a specific question or just wants to have a conversation about a particular topic, you are here to assist.\n\nContext:\n{entities}\n\nCurrent conversation:\n{history}\nLast line:\nHuman: {input}\nYou:`;\n\nexport const ENTITY_MEMORY_CONVERSATION_TEMPLATE =\n /*#__PURE__*/ new PromptTemplate({\n inputVariables: [\"entities\", \"history\", \"input\"],\n template: _DEFAULT_ENTITY_MEMORY_CONVERSATION_TEMPLATE,\n });\n\nexport const _DEFAULT_ENTITY_EXTRACTION_TEMPLATE = `You are an AI assistant reading the transcript of a conversation between an AI and a human. Extract all of the proper nouns from the last line of conversation. As a guideline, a proper noun is generally capitalized. You should definitely extract all names and places.\n\nThe conversation history is provided just in case of a coreference (e.g. \"What do you know about him\" where \"him\" is defined in a previous line) -- ignore items mentioned there that are not in the last line.\n\nReturn the output as a single comma-separated list, or NONE if there is nothing of note to return (e.g. the user is just issuing a greeting or having a simple conversation).\n\nEXAMPLE\nConversation history:\nPerson #1: my name is Jacob. how's it going today?\nAI: \"It's going great! How about you?\"\nPerson #1: good! busy working on Langchain. lots to do.\nAI: \"That sounds like a lot of work! What kind of things are you doing to make Langchain better?\"\nLast line:\nPerson #1: i'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff.\nOutput: Jacob,Langchain\nEND OF EXAMPLE\n\nEXAMPLE\nConversation history:\nPerson #1: how's it going today?\nAI: \"It's going great! How about you?\"\nPerson #1: good! busy working on Langchain. lots to do.\nAI: \"That sounds like a lot of work! What kind of things are you doing to make Langchain better?\"\nLast line:\nPerson #1: i'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I'm working with Person #2.\nOutput: Langchain, Person #2\nEND OF EXAMPLE\n\nConversation history (for reference only):\n{history}\nLast line of conversation (for extraction):\nHuman: {input}\n\nOutput:`;\n\nexport const ENTITY_EXTRACTION_PROMPT = /*#__PURE__*/ new PromptTemplate({\n inputVariables: [\"history\", \"input\"],\n template: _DEFAULT_ENTITY_EXTRACTION_TEMPLATE,\n});\n\nexport const _DEFAULT_ENTITY_SUMMARIZATION_TEMPLATE = `You are an AI assistant helping a human keep track of facts about relevant people, places, and concepts in their life. Update and add to the summary of the provided entity in the \"Entity\" section based on the last line of your conversation with the human. If you are writing the summary for the first time, return a single sentence.\nThe update should only include facts that are relayed in the last line of conversation about the provided entity, and should only contain facts about the provided entity.\n\nIf there is no new information about the provided entity or the information is not worth noting (not an important or relevant fact to remember long-term), output the exact string \"UNCHANGED\" below.\n\nFull conversation history (for context):\n{history}\n\nEntity to summarize:\n{entity}\n\nExisting summary of {entity}:\n{summary}\n\nLast line of conversation:\nHuman: {input}\nUpdated summary (or the exact string \"UNCHANGED\" if there is no new information about {entity} above):`;\n\nexport const ENTITY_SUMMARIZATION_PROMPT = /*#__PURE__*/ new PromptTemplate({\n inputVariables: [\"entity\", \"summary\", \"history\", \"input\"],\n template: _DEFAULT_ENTITY_SUMMARIZATION_TEMPLATE,\n});\n"],"mappings":";AAwBA,MAAa,iCAA+B,IAAI,eAAe;CAC7D,gBAAgB,CAAC,WAAW,YAAY;CACxC,UAAU;;;;;;;;;;;;;;;;;;;;;CACX,CAAC;AAmBF,MAAa,sDACG,IAAI,eAAe;CAC/B,gBAAgB;EAAC;EAAY;EAAW;EAAQ;CAChD,UAAU;;;;;;;;;;;;;;;;CACX,CAAC;AAqCJ,MAAa,2CAAyC,IAAI,eAAe;CACvE,gBAAgB,CAAC,WAAW,QAAQ;CACpC,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CACX,CAAC;AAoBF,MAAa,8CAA4C,IAAI,eAAe;CAC1E,gBAAgB;EAAC;EAAU;EAAW;EAAW;EAAQ;CACzD,UAAU;;;;;;;;;;;;;;;;;CACX,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"summary.cjs","names":["BaseChatMemory","SUMMARY_PROMPT","SystemMessage","LLMChain"],"sources":["../../src/memory/summary.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport {\n BaseMessage,\n SystemMessage,\n getBufferString,\n} from \"@langchain/core/messages\";\nimport { BasePromptTemplate } from \"@langchain/core/prompts\";\nimport {\n InputValues,\n MemoryVariables,\n OutputValues,\n} from \"@langchain/core/memory\";\nimport { LLMChain } from \"../chains/llm_chain.js\";\nimport { SUMMARY_PROMPT } from \"./prompt.js\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the input parameters of the ConversationSummaryMemory\n * class.\n */\nexport interface ConversationSummaryMemoryInput extends BaseConversationSummaryMemoryInput {}\n\n/**\n * Interface for the input parameters of the BaseConversationSummaryMemory\n * class.\n */\nexport interface BaseConversationSummaryMemoryInput extends BaseChatMemoryInput {\n llm: BaseLanguageModelInterface;\n memoryKey?: string;\n humanPrefix?: string;\n aiPrefix?: string;\n prompt?: BasePromptTemplate;\n summaryChatMessageClass?: new (content: string) => BaseMessage;\n}\n\n/**\n * Abstract class that provides a structure for storing and managing the\n * memory of a conversation. It includes methods for predicting a new\n * summary for the conversation given the existing messages and summary.\n */\nexport abstract class BaseConversationSummaryMemory extends BaseChatMemory {\n memoryKey = \"history\";\n\n humanPrefix = \"Human\";\n\n aiPrefix = \"AI\";\n\n llm: BaseLanguageModelInterface;\n\n prompt: BasePromptTemplate = SUMMARY_PROMPT;\n\n summaryChatMessageClass: new (content: string) => BaseMessage = SystemMessage;\n\n constructor(fields: BaseConversationSummaryMemoryInput) {\n const {\n returnMessages,\n inputKey,\n outputKey,\n chatHistory,\n humanPrefix,\n aiPrefix,\n llm,\n prompt,\n summaryChatMessageClass,\n } = fields;\n\n super({ returnMessages, inputKey, outputKey, chatHistory });\n\n this.memoryKey = fields?.memoryKey ?? this.memoryKey;\n this.humanPrefix = humanPrefix ?? this.humanPrefix;\n this.aiPrefix = aiPrefix ?? this.aiPrefix;\n this.llm = llm;\n this.prompt = prompt ?? this.prompt;\n this.summaryChatMessageClass =\n summaryChatMessageClass ?? this.summaryChatMessageClass;\n }\n\n /**\n * Predicts a new summary for the conversation given the existing messages\n * and summary.\n * @param messages Existing messages in the conversation.\n * @param existingSummary Current summary of the conversation.\n * @returns A promise that resolves to a new summary string.\n */\n async predictNewSummary(\n messages: BaseMessage[],\n existingSummary: string\n ): Promise<string> {\n const newLines = getBufferString(messages, this.humanPrefix, this.aiPrefix);\n const chain = new LLMChain({ llm: this.llm, prompt: this.prompt });\n return await chain.predict({\n summary: existingSummary,\n new_lines: newLines,\n });\n }\n}\n\n/**\n * Class that provides a concrete implementation of the conversation\n * memory. It includes methods for loading memory variables, saving\n * context, and clearing the memory.\n * @example\n * ```typescript\n * const memory = new ConversationSummaryMemory({\n * memoryKey: \"chat_history\",\n * llm: new ChatOpenAI({ model: \"gpt-3.5-turbo\", temperature: 0 }),\n * });\n *\n * const model = new ChatOpenAI({ model: \"gpt-4o-mini\" });\n * const prompt =\n * PromptTemplate.fromTemplate(`The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n *\n * Current conversation:\n * {chat_history}\n * Human: {input}\n * AI:`);\n * const chain = new LLMChain({ llm: model, prompt, memory });\n *\n * const res1 = await chain.call({ input: \"Hi! I'm Jim.\" });\n * console.log({ res1, memory: await memory.loadMemoryVariables({}) });\n *\n * const res2 = await chain.call({ input: \"What's my name?\" });\n * console.log({ res2, memory: await memory.loadMemoryVariables({}) });\n *\n * ```\n */\nexport class ConversationSummaryMemory extends BaseConversationSummaryMemory {\n buffer = \"\";\n\n constructor(fields: ConversationSummaryMemoryInput) {\n super(fields);\n }\n\n get memoryKeys() {\n return [this.memoryKey];\n }\n\n /**\n * Loads the memory variables for the conversation memory.\n * @returns A promise that resolves to an object containing the memory variables.\n */\n async loadMemoryVariables(_: InputValues): Promise<MemoryVariables> {\n if (this.returnMessages) {\n const result = {\n [this.memoryKey]: [new this.summaryChatMessageClass(this.buffer)],\n };\n return result;\n }\n const result = { [this.memoryKey]: this.buffer };\n return result;\n }\n\n /**\n * Saves the context of the conversation memory.\n * @param inputValues Input values for the conversation.\n * @param outputValues Output values from the conversation.\n * @returns A promise that resolves when the context has been saved.\n */\n async saveContext(\n inputValues: InputValues,\n outputValues: OutputValues\n ): Promise<void> {\n await super.saveContext(inputValues, outputValues);\n const messages = await this.chatHistory.getMessages();\n this.buffer = await this.predictNewSummary(messages.slice(-2), this.buffer);\n }\n\n /**\n * Clears the conversation memory.\n * @returns A promise that resolves when the memory has been cleared.\n */\n async clear() {\n await super.clear();\n this.buffer = \"\";\n }\n}\n"],"mappings":";;;;;;;;;;;AAwCA,IAAsB,gCAAtB,cAA4DA,2BAAAA,eAAe;CACzE,YAAY;CAEZ,cAAc;CAEd,WAAW;CAEX;CAEA,SAA6BC,eAAAA;CAE7B,0BAAgEC,yBAAAA;CAEhE,YAAY,QAA4C;EACtD,MAAM,EACJ,gBACA,UACA,WACA,aACA,aACA,UACA,KACA,QACA,4BACE;AAEJ,QAAM;GAAE;GAAgB;GAAU;GAAW;GAAa,CAAC;AAE3D,OAAK,YAAY,QAAQ,aAAa,KAAK;AAC3C,OAAK,cAAc,eAAe,KAAK;AACvC,OAAK,WAAW,YAAY,KAAK;AACjC,OAAK,MAAM;AACX,OAAK,SAAS,UAAU,KAAK;AAC7B,OAAK,0BACH,2BAA2B,KAAK;;;;;;;;;CAUpC,MAAM,kBACJ,UACA,iBACiB;EACjB,MAAM,YAAA,GAAA,yBAAA,iBAA2B,UAAU,KAAK,aAAa,KAAK,SAAS;AAE3E,SAAO,
|
|
1
|
+
{"version":3,"file":"summary.cjs","names":["BaseChatMemory","SUMMARY_PROMPT","SystemMessage","LLMChain"],"sources":["../../src/memory/summary.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport {\n BaseMessage,\n SystemMessage,\n getBufferString,\n} from \"@langchain/core/messages\";\nimport { BasePromptTemplate } from \"@langchain/core/prompts\";\nimport {\n InputValues,\n MemoryVariables,\n OutputValues,\n} from \"@langchain/core/memory\";\nimport { LLMChain } from \"../chains/llm_chain.js\";\nimport { SUMMARY_PROMPT } from \"./prompt.js\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the input parameters of the ConversationSummaryMemory\n * class.\n */\nexport interface ConversationSummaryMemoryInput extends BaseConversationSummaryMemoryInput {}\n\n/**\n * Interface for the input parameters of the BaseConversationSummaryMemory\n * class.\n */\nexport interface BaseConversationSummaryMemoryInput extends BaseChatMemoryInput {\n llm: BaseLanguageModelInterface;\n memoryKey?: string;\n humanPrefix?: string;\n aiPrefix?: string;\n prompt?: BasePromptTemplate;\n summaryChatMessageClass?: new (content: string) => BaseMessage;\n}\n\n/**\n * Abstract class that provides a structure for storing and managing the\n * memory of a conversation. It includes methods for predicting a new\n * summary for the conversation given the existing messages and summary.\n */\nexport abstract class BaseConversationSummaryMemory extends BaseChatMemory {\n memoryKey = \"history\";\n\n humanPrefix = \"Human\";\n\n aiPrefix = \"AI\";\n\n llm: BaseLanguageModelInterface;\n\n prompt: BasePromptTemplate = SUMMARY_PROMPT;\n\n summaryChatMessageClass: new (content: string) => BaseMessage = SystemMessage;\n\n constructor(fields: BaseConversationSummaryMemoryInput) {\n const {\n returnMessages,\n inputKey,\n outputKey,\n chatHistory,\n humanPrefix,\n aiPrefix,\n llm,\n prompt,\n summaryChatMessageClass,\n } = fields;\n\n super({ returnMessages, inputKey, outputKey, chatHistory });\n\n this.memoryKey = fields?.memoryKey ?? this.memoryKey;\n this.humanPrefix = humanPrefix ?? this.humanPrefix;\n this.aiPrefix = aiPrefix ?? this.aiPrefix;\n this.llm = llm;\n this.prompt = prompt ?? this.prompt;\n this.summaryChatMessageClass =\n summaryChatMessageClass ?? this.summaryChatMessageClass;\n }\n\n /**\n * Predicts a new summary for the conversation given the existing messages\n * and summary.\n * @param messages Existing messages in the conversation.\n * @param existingSummary Current summary of the conversation.\n * @returns A promise that resolves to a new summary string.\n */\n async predictNewSummary(\n messages: BaseMessage[],\n existingSummary: string\n ): Promise<string> {\n const newLines = getBufferString(messages, this.humanPrefix, this.aiPrefix);\n const chain = new LLMChain({ llm: this.llm, prompt: this.prompt });\n return await chain.predict({\n summary: existingSummary,\n new_lines: newLines,\n });\n }\n}\n\n/**\n * Class that provides a concrete implementation of the conversation\n * memory. It includes methods for loading memory variables, saving\n * context, and clearing the memory.\n * @example\n * ```typescript\n * const memory = new ConversationSummaryMemory({\n * memoryKey: \"chat_history\",\n * llm: new ChatOpenAI({ model: \"gpt-3.5-turbo\", temperature: 0 }),\n * });\n *\n * const model = new ChatOpenAI({ model: \"gpt-4o-mini\" });\n * const prompt =\n * PromptTemplate.fromTemplate(`The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n *\n * Current conversation:\n * {chat_history}\n * Human: {input}\n * AI:`);\n * const chain = new LLMChain({ llm: model, prompt, memory });\n *\n * const res1 = await chain.call({ input: \"Hi! I'm Jim.\" });\n * console.log({ res1, memory: await memory.loadMemoryVariables({}) });\n *\n * const res2 = await chain.call({ input: \"What's my name?\" });\n * console.log({ res2, memory: await memory.loadMemoryVariables({}) });\n *\n * ```\n */\nexport class ConversationSummaryMemory extends BaseConversationSummaryMemory {\n buffer = \"\";\n\n constructor(fields: ConversationSummaryMemoryInput) {\n super(fields);\n }\n\n get memoryKeys() {\n return [this.memoryKey];\n }\n\n /**\n * Loads the memory variables for the conversation memory.\n * @returns A promise that resolves to an object containing the memory variables.\n */\n async loadMemoryVariables(_: InputValues): Promise<MemoryVariables> {\n if (this.returnMessages) {\n const result = {\n [this.memoryKey]: [new this.summaryChatMessageClass(this.buffer)],\n };\n return result;\n }\n const result = { [this.memoryKey]: this.buffer };\n return result;\n }\n\n /**\n * Saves the context of the conversation memory.\n * @param inputValues Input values for the conversation.\n * @param outputValues Output values from the conversation.\n * @returns A promise that resolves when the context has been saved.\n */\n async saveContext(\n inputValues: InputValues,\n outputValues: OutputValues\n ): Promise<void> {\n await super.saveContext(inputValues, outputValues);\n const messages = await this.chatHistory.getMessages();\n this.buffer = await this.predictNewSummary(messages.slice(-2), this.buffer);\n }\n\n /**\n * Clears the conversation memory.\n * @returns A promise that resolves when the memory has been cleared.\n */\n async clear() {\n await super.clear();\n this.buffer = \"\";\n }\n}\n"],"mappings":";;;;;;;;;;;AAwCA,IAAsB,gCAAtB,cAA4DA,2BAAAA,eAAe;CACzE,YAAY;CAEZ,cAAc;CAEd,WAAW;CAEX;CAEA,SAA6BC,eAAAA;CAE7B,0BAAgEC,yBAAAA;CAEhE,YAAY,QAA4C;EACtD,MAAM,EACJ,gBACA,UACA,WACA,aACA,aACA,UACA,KACA,QACA,4BACE;AAEJ,QAAM;GAAE;GAAgB;GAAU;GAAW;GAAa,CAAC;AAE3D,OAAK,YAAY,QAAQ,aAAa,KAAK;AAC3C,OAAK,cAAc,eAAe,KAAK;AACvC,OAAK,WAAW,YAAY,KAAK;AACjC,OAAK,MAAM;AACX,OAAK,SAAS,UAAU,KAAK;AAC7B,OAAK,0BACH,2BAA2B,KAAK;;;;;;;;;CAUpC,MAAM,kBACJ,UACA,iBACiB;EACjB,MAAM,YAAA,GAAA,yBAAA,iBAA2B,UAAU,KAAK,aAAa,KAAK,SAAS;AAE3E,SAAO,MAAM,IADKC,kBAAAA,SAAS;GAAE,KAAK,KAAK;GAAK,QAAQ,KAAK;GAAQ,CAC/C,CAAC,QAAQ;GACzB,SAAS;GACT,WAAW;GACZ,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCN,IAAa,4BAAb,cAA+C,8BAA8B;CAC3E,SAAS;CAET,YAAY,QAAwC;AAClD,QAAM,OAAO;;CAGf,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,UAAU;;;;;;CAOzB,MAAM,oBAAoB,GAA0C;AAClE,MAAI,KAAK,eAIP,QAAO,GAFJ,KAAK,YAAY,CAAC,IAAI,KAAK,wBAAwB,KAAK,OAAO,CAAC,EAEtD;AAGf,SAAO,GADW,KAAK,YAAY,KAAK,QAC3B;;;;;;;;CASf,MAAM,YACJ,aACA,cACe;AACf,QAAM,MAAM,YAAY,aAAa,aAAa;EAClD,MAAM,WAAW,MAAM,KAAK,YAAY,aAAa;AACrD,OAAK,SAAS,MAAM,KAAK,kBAAkB,SAAS,MAAM,GAAG,EAAE,KAAK,OAAO;;;;;;CAO7E,MAAM,QAAQ;AACZ,QAAM,MAAM,OAAO;AACnB,OAAK,SAAS"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"summary.js","names":[],"sources":["../../src/memory/summary.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport {\n BaseMessage,\n SystemMessage,\n getBufferString,\n} from \"@langchain/core/messages\";\nimport { BasePromptTemplate } from \"@langchain/core/prompts\";\nimport {\n InputValues,\n MemoryVariables,\n OutputValues,\n} from \"@langchain/core/memory\";\nimport { LLMChain } from \"../chains/llm_chain.js\";\nimport { SUMMARY_PROMPT } from \"./prompt.js\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the input parameters of the ConversationSummaryMemory\n * class.\n */\nexport interface ConversationSummaryMemoryInput extends BaseConversationSummaryMemoryInput {}\n\n/**\n * Interface for the input parameters of the BaseConversationSummaryMemory\n * class.\n */\nexport interface BaseConversationSummaryMemoryInput extends BaseChatMemoryInput {\n llm: BaseLanguageModelInterface;\n memoryKey?: string;\n humanPrefix?: string;\n aiPrefix?: string;\n prompt?: BasePromptTemplate;\n summaryChatMessageClass?: new (content: string) => BaseMessage;\n}\n\n/**\n * Abstract class that provides a structure for storing and managing the\n * memory of a conversation. It includes methods for predicting a new\n * summary for the conversation given the existing messages and summary.\n */\nexport abstract class BaseConversationSummaryMemory extends BaseChatMemory {\n memoryKey = \"history\";\n\n humanPrefix = \"Human\";\n\n aiPrefix = \"AI\";\n\n llm: BaseLanguageModelInterface;\n\n prompt: BasePromptTemplate = SUMMARY_PROMPT;\n\n summaryChatMessageClass: new (content: string) => BaseMessage = SystemMessage;\n\n constructor(fields: BaseConversationSummaryMemoryInput) {\n const {\n returnMessages,\n inputKey,\n outputKey,\n chatHistory,\n humanPrefix,\n aiPrefix,\n llm,\n prompt,\n summaryChatMessageClass,\n } = fields;\n\n super({ returnMessages, inputKey, outputKey, chatHistory });\n\n this.memoryKey = fields?.memoryKey ?? this.memoryKey;\n this.humanPrefix = humanPrefix ?? this.humanPrefix;\n this.aiPrefix = aiPrefix ?? this.aiPrefix;\n this.llm = llm;\n this.prompt = prompt ?? this.prompt;\n this.summaryChatMessageClass =\n summaryChatMessageClass ?? this.summaryChatMessageClass;\n }\n\n /**\n * Predicts a new summary for the conversation given the existing messages\n * and summary.\n * @param messages Existing messages in the conversation.\n * @param existingSummary Current summary of the conversation.\n * @returns A promise that resolves to a new summary string.\n */\n async predictNewSummary(\n messages: BaseMessage[],\n existingSummary: string\n ): Promise<string> {\n const newLines = getBufferString(messages, this.humanPrefix, this.aiPrefix);\n const chain = new LLMChain({ llm: this.llm, prompt: this.prompt });\n return await chain.predict({\n summary: existingSummary,\n new_lines: newLines,\n });\n }\n}\n\n/**\n * Class that provides a concrete implementation of the conversation\n * memory. It includes methods for loading memory variables, saving\n * context, and clearing the memory.\n * @example\n * ```typescript\n * const memory = new ConversationSummaryMemory({\n * memoryKey: \"chat_history\",\n * llm: new ChatOpenAI({ model: \"gpt-3.5-turbo\", temperature: 0 }),\n * });\n *\n * const model = new ChatOpenAI({ model: \"gpt-4o-mini\" });\n * const prompt =\n * PromptTemplate.fromTemplate(`The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n *\n * Current conversation:\n * {chat_history}\n * Human: {input}\n * AI:`);\n * const chain = new LLMChain({ llm: model, prompt, memory });\n *\n * const res1 = await chain.call({ input: \"Hi! I'm Jim.\" });\n * console.log({ res1, memory: await memory.loadMemoryVariables({}) });\n *\n * const res2 = await chain.call({ input: \"What's my name?\" });\n * console.log({ res2, memory: await memory.loadMemoryVariables({}) });\n *\n * ```\n */\nexport class ConversationSummaryMemory extends BaseConversationSummaryMemory {\n buffer = \"\";\n\n constructor(fields: ConversationSummaryMemoryInput) {\n super(fields);\n }\n\n get memoryKeys() {\n return [this.memoryKey];\n }\n\n /**\n * Loads the memory variables for the conversation memory.\n * @returns A promise that resolves to an object containing the memory variables.\n */\n async loadMemoryVariables(_: InputValues): Promise<MemoryVariables> {\n if (this.returnMessages) {\n const result = {\n [this.memoryKey]: [new this.summaryChatMessageClass(this.buffer)],\n };\n return result;\n }\n const result = { [this.memoryKey]: this.buffer };\n return result;\n }\n\n /**\n * Saves the context of the conversation memory.\n * @param inputValues Input values for the conversation.\n * @param outputValues Output values from the conversation.\n * @returns A promise that resolves when the context has been saved.\n */\n async saveContext(\n inputValues: InputValues,\n outputValues: OutputValues\n ): Promise<void> {\n await super.saveContext(inputValues, outputValues);\n const messages = await this.chatHistory.getMessages();\n this.buffer = await this.predictNewSummary(messages.slice(-2), this.buffer);\n }\n\n /**\n * Clears the conversation memory.\n * @returns A promise that resolves when the memory has been cleared.\n */\n async clear() {\n await super.clear();\n this.buffer = \"\";\n }\n}\n"],"mappings":";;;;;;;;;;AAwCA,IAAsB,gCAAtB,cAA4D,eAAe;CACzE,YAAY;CAEZ,cAAc;CAEd,WAAW;CAEX;CAEA,SAA6B;CAE7B,0BAAgE;CAEhE,YAAY,QAA4C;EACtD,MAAM,EACJ,gBACA,UACA,WACA,aACA,aACA,UACA,KACA,QACA,4BACE;AAEJ,QAAM;GAAE;GAAgB;GAAU;GAAW;GAAa,CAAC;AAE3D,OAAK,YAAY,QAAQ,aAAa,KAAK;AAC3C,OAAK,cAAc,eAAe,KAAK;AACvC,OAAK,WAAW,YAAY,KAAK;AACjC,OAAK,MAAM;AACX,OAAK,SAAS,UAAU,KAAK;AAC7B,OAAK,0BACH,2BAA2B,KAAK;;;;;;;;;CAUpC,MAAM,kBACJ,UACA,iBACiB;EACjB,MAAM,WAAW,gBAAgB,UAAU,KAAK,aAAa,KAAK,SAAS;AAE3E,SAAO,
|
|
1
|
+
{"version":3,"file":"summary.js","names":[],"sources":["../../src/memory/summary.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport {\n BaseMessage,\n SystemMessage,\n getBufferString,\n} from \"@langchain/core/messages\";\nimport { BasePromptTemplate } from \"@langchain/core/prompts\";\nimport {\n InputValues,\n MemoryVariables,\n OutputValues,\n} from \"@langchain/core/memory\";\nimport { LLMChain } from \"../chains/llm_chain.js\";\nimport { SUMMARY_PROMPT } from \"./prompt.js\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the input parameters of the ConversationSummaryMemory\n * class.\n */\nexport interface ConversationSummaryMemoryInput extends BaseConversationSummaryMemoryInput {}\n\n/**\n * Interface for the input parameters of the BaseConversationSummaryMemory\n * class.\n */\nexport interface BaseConversationSummaryMemoryInput extends BaseChatMemoryInput {\n llm: BaseLanguageModelInterface;\n memoryKey?: string;\n humanPrefix?: string;\n aiPrefix?: string;\n prompt?: BasePromptTemplate;\n summaryChatMessageClass?: new (content: string) => BaseMessage;\n}\n\n/**\n * Abstract class that provides a structure for storing and managing the\n * memory of a conversation. It includes methods for predicting a new\n * summary for the conversation given the existing messages and summary.\n */\nexport abstract class BaseConversationSummaryMemory extends BaseChatMemory {\n memoryKey = \"history\";\n\n humanPrefix = \"Human\";\n\n aiPrefix = \"AI\";\n\n llm: BaseLanguageModelInterface;\n\n prompt: BasePromptTemplate = SUMMARY_PROMPT;\n\n summaryChatMessageClass: new (content: string) => BaseMessage = SystemMessage;\n\n constructor(fields: BaseConversationSummaryMemoryInput) {\n const {\n returnMessages,\n inputKey,\n outputKey,\n chatHistory,\n humanPrefix,\n aiPrefix,\n llm,\n prompt,\n summaryChatMessageClass,\n } = fields;\n\n super({ returnMessages, inputKey, outputKey, chatHistory });\n\n this.memoryKey = fields?.memoryKey ?? this.memoryKey;\n this.humanPrefix = humanPrefix ?? this.humanPrefix;\n this.aiPrefix = aiPrefix ?? this.aiPrefix;\n this.llm = llm;\n this.prompt = prompt ?? this.prompt;\n this.summaryChatMessageClass =\n summaryChatMessageClass ?? this.summaryChatMessageClass;\n }\n\n /**\n * Predicts a new summary for the conversation given the existing messages\n * and summary.\n * @param messages Existing messages in the conversation.\n * @param existingSummary Current summary of the conversation.\n * @returns A promise that resolves to a new summary string.\n */\n async predictNewSummary(\n messages: BaseMessage[],\n existingSummary: string\n ): Promise<string> {\n const newLines = getBufferString(messages, this.humanPrefix, this.aiPrefix);\n const chain = new LLMChain({ llm: this.llm, prompt: this.prompt });\n return await chain.predict({\n summary: existingSummary,\n new_lines: newLines,\n });\n }\n}\n\n/**\n * Class that provides a concrete implementation of the conversation\n * memory. It includes methods for loading memory variables, saving\n * context, and clearing the memory.\n * @example\n * ```typescript\n * const memory = new ConversationSummaryMemory({\n * memoryKey: \"chat_history\",\n * llm: new ChatOpenAI({ model: \"gpt-3.5-turbo\", temperature: 0 }),\n * });\n *\n * const model = new ChatOpenAI({ model: \"gpt-4o-mini\" });\n * const prompt =\n * PromptTemplate.fromTemplate(`The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n *\n * Current conversation:\n * {chat_history}\n * Human: {input}\n * AI:`);\n * const chain = new LLMChain({ llm: model, prompt, memory });\n *\n * const res1 = await chain.call({ input: \"Hi! I'm Jim.\" });\n * console.log({ res1, memory: await memory.loadMemoryVariables({}) });\n *\n * const res2 = await chain.call({ input: \"What's my name?\" });\n * console.log({ res2, memory: await memory.loadMemoryVariables({}) });\n *\n * ```\n */\nexport class ConversationSummaryMemory extends BaseConversationSummaryMemory {\n buffer = \"\";\n\n constructor(fields: ConversationSummaryMemoryInput) {\n super(fields);\n }\n\n get memoryKeys() {\n return [this.memoryKey];\n }\n\n /**\n * Loads the memory variables for the conversation memory.\n * @returns A promise that resolves to an object containing the memory variables.\n */\n async loadMemoryVariables(_: InputValues): Promise<MemoryVariables> {\n if (this.returnMessages) {\n const result = {\n [this.memoryKey]: [new this.summaryChatMessageClass(this.buffer)],\n };\n return result;\n }\n const result = { [this.memoryKey]: this.buffer };\n return result;\n }\n\n /**\n * Saves the context of the conversation memory.\n * @param inputValues Input values for the conversation.\n * @param outputValues Output values from the conversation.\n * @returns A promise that resolves when the context has been saved.\n */\n async saveContext(\n inputValues: InputValues,\n outputValues: OutputValues\n ): Promise<void> {\n await super.saveContext(inputValues, outputValues);\n const messages = await this.chatHistory.getMessages();\n this.buffer = await this.predictNewSummary(messages.slice(-2), this.buffer);\n }\n\n /**\n * Clears the conversation memory.\n * @returns A promise that resolves when the memory has been cleared.\n */\n async clear() {\n await super.clear();\n this.buffer = \"\";\n }\n}\n"],"mappings":";;;;;;;;;;AAwCA,IAAsB,gCAAtB,cAA4D,eAAe;CACzE,YAAY;CAEZ,cAAc;CAEd,WAAW;CAEX;CAEA,SAA6B;CAE7B,0BAAgE;CAEhE,YAAY,QAA4C;EACtD,MAAM,EACJ,gBACA,UACA,WACA,aACA,aACA,UACA,KACA,QACA,4BACE;AAEJ,QAAM;GAAE;GAAgB;GAAU;GAAW;GAAa,CAAC;AAE3D,OAAK,YAAY,QAAQ,aAAa,KAAK;AAC3C,OAAK,cAAc,eAAe,KAAK;AACvC,OAAK,WAAW,YAAY,KAAK;AACjC,OAAK,MAAM;AACX,OAAK,SAAS,UAAU,KAAK;AAC7B,OAAK,0BACH,2BAA2B,KAAK;;;;;;;;;CAUpC,MAAM,kBACJ,UACA,iBACiB;EACjB,MAAM,WAAW,gBAAgB,UAAU,KAAK,aAAa,KAAK,SAAS;AAE3E,SAAO,MAAM,IADK,SAAS;GAAE,KAAK,KAAK;GAAK,QAAQ,KAAK;GAAQ,CAC/C,CAAC,QAAQ;GACzB,SAAS;GACT,WAAW;GACZ,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCN,IAAa,4BAAb,cAA+C,8BAA8B;CAC3E,SAAS;CAET,YAAY,QAAwC;AAClD,QAAM,OAAO;;CAGf,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,UAAU;;;;;;CAOzB,MAAM,oBAAoB,GAA0C;AAClE,MAAI,KAAK,eAIP,QAAO,GAFJ,KAAK,YAAY,CAAC,IAAI,KAAK,wBAAwB,KAAK,OAAO,CAAC,EAEtD;AAGf,SAAO,GADW,KAAK,YAAY,KAAK,QAC3B;;;;;;;;CASf,MAAM,YACJ,aACA,cACe;AACf,QAAM,MAAM,YAAY,aAAa,aAAa;EAClD,MAAM,WAAW,MAAM,KAAK,YAAY,aAAa;AACrD,OAAK,SAAS,MAAM,KAAK,kBAAkB,SAAS,MAAM,GAAG,EAAE,KAAK,OAAO;;;;;;CAO7E,MAAM,QAAQ;AACZ,QAAM,MAAM,OAAO;AACnB,OAAK,SAAS"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"expression.cjs","names":["BaseOutputParser","ASTParser","MasterHandler"],"sources":["../../src/output_parsers/expression.ts"],"sourcesContent":["import { BaseOutputParser } from \"@langchain/core/output_parsers\";\nimport { MasterHandler } from \"./expression_type_handlers/factory.js\";\nimport { ParsedType } from \"./expression_type_handlers/types.js\";\nimport { ASTParser } from \"./expression_type_handlers/base.js\";\nimport type { ExpressionNode } from \"../types/expression-parser.js\";\n\nexport type ParseFunction = Awaited<\n ReturnType<typeof ASTParser.importASTParser>\n>;\n\n/**\n * We need to be able to handle the following cases:\n * ExpressionStatement\n * CallExpression\n * Identifier | MemberExpression\n * ExpressionLiterals: [\n * CallExpression\n * StringLiteral\n * NumericLiteral\n * ArrayLiteralExpression\n * ExpressionLiterals\n * ObjectLiteralExpression\n * PropertyAssignment\n * Identifier\n * ExpressionLiterals\n * ]\n */\n\nexport class ExpressionParser extends BaseOutputParser<ParsedType> {\n lc_namespace = [\"langchain\", \"output_parsers\", \"expression\"];\n\n parser: ParseFunction;\n\n /**\n * We should separate loading the parser into its own function\n * because loading the grammar takes some time. If there are\n * multiple concurrent parse calls, it's faster to just wait\n * for building the parser once and then use it for all\n * subsequent calls. See expression.test.ts for an example.\n */\n async ensureParser() {\n if (!this.parser) {\n this.parser = await ASTParser.importASTParser();\n }\n }\n\n /**\n * Parses the given text. It first ensures the parser is loaded, then\n * tries to parse the text. If the parsing fails, it throws an error. If\n * the parsing is successful, it returns the parsed expression.\n * @param text The text to be parsed.\n * @returns The parsed expression\n */\n async parse(text: string) {\n await this.ensureParser();\n\n try {\n const program = this.parser(text);\n\n const node = program.body;\n if (!ASTParser.isExpressionStatement(node)) {\n throw new Error(\n `Expected ExpressionStatement, got ${(node as ExpressionNode).type}`\n );\n }\n\n const { expression: expressionStatement } = node;\n if (!ASTParser.isCallExpression(expressionStatement)) {\n throw new Error(\"Expected CallExpression\");\n }\n const masterHandler = MasterHandler.createMasterHandler();\n return await masterHandler.handle(expressionStatement);\n } catch (err) {\n throw new Error(`Error parsing ${err}: ${text}`);\n }\n }\n\n /**\n * This method is currently empty, but it could be used to provide\n * instructions on the format of the input text.\n * @returns string\n */\n getFormatInstructions(): string {\n return \"\";\n }\n}\n\nexport * from \"./expression_type_handlers/types.js\";\n\nexport { MasterHandler } from \"./expression_type_handlers/factory.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,IAAa,mBAAb,cAAsCA,+BAAAA,iBAA6B;CACjE,eAAe;EAAC;EAAa;EAAkB;EAAa;CAE5D;;;;;;;;CASA,MAAM,eAAe;AACnB,MAAI,CAAC,KAAK,OACR,MAAK,SAAS,MAAMC,aAAAA,UAAU,iBAAiB;;;;;;;;;CAWnD,MAAM,MAAM,MAAc;AACxB,QAAM,KAAK,cAAc;AAEzB,MAAI;GAGF,MAAM,OAFU,KAAK,OAAO,
|
|
1
|
+
{"version":3,"file":"expression.cjs","names":["BaseOutputParser","ASTParser","MasterHandler"],"sources":["../../src/output_parsers/expression.ts"],"sourcesContent":["import { BaseOutputParser } from \"@langchain/core/output_parsers\";\nimport { MasterHandler } from \"./expression_type_handlers/factory.js\";\nimport { ParsedType } from \"./expression_type_handlers/types.js\";\nimport { ASTParser } from \"./expression_type_handlers/base.js\";\nimport type { ExpressionNode } from \"../types/expression-parser.js\";\n\nexport type ParseFunction = Awaited<\n ReturnType<typeof ASTParser.importASTParser>\n>;\n\n/**\n * We need to be able to handle the following cases:\n * ExpressionStatement\n * CallExpression\n * Identifier | MemberExpression\n * ExpressionLiterals: [\n * CallExpression\n * StringLiteral\n * NumericLiteral\n * ArrayLiteralExpression\n * ExpressionLiterals\n * ObjectLiteralExpression\n * PropertyAssignment\n * Identifier\n * ExpressionLiterals\n * ]\n */\n\nexport class ExpressionParser extends BaseOutputParser<ParsedType> {\n lc_namespace = [\"langchain\", \"output_parsers\", \"expression\"];\n\n parser: ParseFunction;\n\n /**\n * We should separate loading the parser into its own function\n * because loading the grammar takes some time. If there are\n * multiple concurrent parse calls, it's faster to just wait\n * for building the parser once and then use it for all\n * subsequent calls. See expression.test.ts for an example.\n */\n async ensureParser() {\n if (!this.parser) {\n this.parser = await ASTParser.importASTParser();\n }\n }\n\n /**\n * Parses the given text. It first ensures the parser is loaded, then\n * tries to parse the text. If the parsing fails, it throws an error. If\n * the parsing is successful, it returns the parsed expression.\n * @param text The text to be parsed.\n * @returns The parsed expression\n */\n async parse(text: string) {\n await this.ensureParser();\n\n try {\n const program = this.parser(text);\n\n const node = program.body;\n if (!ASTParser.isExpressionStatement(node)) {\n throw new Error(\n `Expected ExpressionStatement, got ${(node as ExpressionNode).type}`\n );\n }\n\n const { expression: expressionStatement } = node;\n if (!ASTParser.isCallExpression(expressionStatement)) {\n throw new Error(\"Expected CallExpression\");\n }\n const masterHandler = MasterHandler.createMasterHandler();\n return await masterHandler.handle(expressionStatement);\n } catch (err) {\n throw new Error(`Error parsing ${err}: ${text}`);\n }\n }\n\n /**\n * This method is currently empty, but it could be used to provide\n * instructions on the format of the input text.\n * @returns string\n */\n getFormatInstructions(): string {\n return \"\";\n }\n}\n\nexport * from \"./expression_type_handlers/types.js\";\n\nexport { MasterHandler } from \"./expression_type_handlers/factory.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,IAAa,mBAAb,cAAsCA,+BAAAA,iBAA6B;CACjE,eAAe;EAAC;EAAa;EAAkB;EAAa;CAE5D;;;;;;;;CASA,MAAM,eAAe;AACnB,MAAI,CAAC,KAAK,OACR,MAAK,SAAS,MAAMC,aAAAA,UAAU,iBAAiB;;;;;;;;;CAWnD,MAAM,MAAM,MAAc;AACxB,QAAM,KAAK,cAAc;AAEzB,MAAI;GAGF,MAAM,OAFU,KAAK,OAAO,KAER,CAAC;AACrB,OAAI,CAACA,aAAAA,UAAU,sBAAsB,KAAK,CACxC,OAAM,IAAI,MACR,qCAAsC,KAAwB,OAC/D;GAGH,MAAM,EAAE,YAAY,wBAAwB;AAC5C,OAAI,CAACA,aAAAA,UAAU,iBAAiB,oBAAoB,CAClD,OAAM,IAAI,MAAM,0BAA0B;AAG5C,UAAO,MADeC,gBAAAA,cAAc,qBACV,CAAC,OAAO,oBAAoB;WAC/C,KAAK;AACZ,SAAM,IAAI,MAAM,iBAAiB,IAAI,IAAI,OAAO;;;;;;;;CASpD,wBAAgC;AAC9B,SAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"expression.js","names":[],"sources":["../../src/output_parsers/expression.ts"],"sourcesContent":["import { BaseOutputParser } from \"@langchain/core/output_parsers\";\nimport { MasterHandler } from \"./expression_type_handlers/factory.js\";\nimport { ParsedType } from \"./expression_type_handlers/types.js\";\nimport { ASTParser } from \"./expression_type_handlers/base.js\";\nimport type { ExpressionNode } from \"../types/expression-parser.js\";\n\nexport type ParseFunction = Awaited<\n ReturnType<typeof ASTParser.importASTParser>\n>;\n\n/**\n * We need to be able to handle the following cases:\n * ExpressionStatement\n * CallExpression\n * Identifier | MemberExpression\n * ExpressionLiterals: [\n * CallExpression\n * StringLiteral\n * NumericLiteral\n * ArrayLiteralExpression\n * ExpressionLiterals\n * ObjectLiteralExpression\n * PropertyAssignment\n * Identifier\n * ExpressionLiterals\n * ]\n */\n\nexport class ExpressionParser extends BaseOutputParser<ParsedType> {\n lc_namespace = [\"langchain\", \"output_parsers\", \"expression\"];\n\n parser: ParseFunction;\n\n /**\n * We should separate loading the parser into its own function\n * because loading the grammar takes some time. If there are\n * multiple concurrent parse calls, it's faster to just wait\n * for building the parser once and then use it for all\n * subsequent calls. See expression.test.ts for an example.\n */\n async ensureParser() {\n if (!this.parser) {\n this.parser = await ASTParser.importASTParser();\n }\n }\n\n /**\n * Parses the given text. It first ensures the parser is loaded, then\n * tries to parse the text. If the parsing fails, it throws an error. If\n * the parsing is successful, it returns the parsed expression.\n * @param text The text to be parsed.\n * @returns The parsed expression\n */\n async parse(text: string) {\n await this.ensureParser();\n\n try {\n const program = this.parser(text);\n\n const node = program.body;\n if (!ASTParser.isExpressionStatement(node)) {\n throw new Error(\n `Expected ExpressionStatement, got ${(node as ExpressionNode).type}`\n );\n }\n\n const { expression: expressionStatement } = node;\n if (!ASTParser.isCallExpression(expressionStatement)) {\n throw new Error(\"Expected CallExpression\");\n }\n const masterHandler = MasterHandler.createMasterHandler();\n return await masterHandler.handle(expressionStatement);\n } catch (err) {\n throw new Error(`Error parsing ${err}: ${text}`);\n }\n }\n\n /**\n * This method is currently empty, but it could be used to provide\n * instructions on the format of the input text.\n * @returns string\n */\n getFormatInstructions(): string {\n return \"\";\n }\n}\n\nexport * from \"./expression_type_handlers/types.js\";\n\nexport { MasterHandler } from \"./expression_type_handlers/factory.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,IAAa,mBAAb,cAAsC,iBAA6B;CACjE,eAAe;EAAC;EAAa;EAAkB;EAAa;CAE5D;;;;;;;;CASA,MAAM,eAAe;AACnB,MAAI,CAAC,KAAK,OACR,MAAK,SAAS,MAAM,UAAU,iBAAiB;;;;;;;;;CAWnD,MAAM,MAAM,MAAc;AACxB,QAAM,KAAK,cAAc;AAEzB,MAAI;GAGF,MAAM,OAFU,KAAK,OAAO,
|
|
1
|
+
{"version":3,"file":"expression.js","names":[],"sources":["../../src/output_parsers/expression.ts"],"sourcesContent":["import { BaseOutputParser } from \"@langchain/core/output_parsers\";\nimport { MasterHandler } from \"./expression_type_handlers/factory.js\";\nimport { ParsedType } from \"./expression_type_handlers/types.js\";\nimport { ASTParser } from \"./expression_type_handlers/base.js\";\nimport type { ExpressionNode } from \"../types/expression-parser.js\";\n\nexport type ParseFunction = Awaited<\n ReturnType<typeof ASTParser.importASTParser>\n>;\n\n/**\n * We need to be able to handle the following cases:\n * ExpressionStatement\n * CallExpression\n * Identifier | MemberExpression\n * ExpressionLiterals: [\n * CallExpression\n * StringLiteral\n * NumericLiteral\n * ArrayLiteralExpression\n * ExpressionLiterals\n * ObjectLiteralExpression\n * PropertyAssignment\n * Identifier\n * ExpressionLiterals\n * ]\n */\n\nexport class ExpressionParser extends BaseOutputParser<ParsedType> {\n lc_namespace = [\"langchain\", \"output_parsers\", \"expression\"];\n\n parser: ParseFunction;\n\n /**\n * We should separate loading the parser into its own function\n * because loading the grammar takes some time. If there are\n * multiple concurrent parse calls, it's faster to just wait\n * for building the parser once and then use it for all\n * subsequent calls. See expression.test.ts for an example.\n */\n async ensureParser() {\n if (!this.parser) {\n this.parser = await ASTParser.importASTParser();\n }\n }\n\n /**\n * Parses the given text. It first ensures the parser is loaded, then\n * tries to parse the text. If the parsing fails, it throws an error. If\n * the parsing is successful, it returns the parsed expression.\n * @param text The text to be parsed.\n * @returns The parsed expression\n */\n async parse(text: string) {\n await this.ensureParser();\n\n try {\n const program = this.parser(text);\n\n const node = program.body;\n if (!ASTParser.isExpressionStatement(node)) {\n throw new Error(\n `Expected ExpressionStatement, got ${(node as ExpressionNode).type}`\n );\n }\n\n const { expression: expressionStatement } = node;\n if (!ASTParser.isCallExpression(expressionStatement)) {\n throw new Error(\"Expected CallExpression\");\n }\n const masterHandler = MasterHandler.createMasterHandler();\n return await masterHandler.handle(expressionStatement);\n } catch (err) {\n throw new Error(`Error parsing ${err}: ${text}`);\n }\n }\n\n /**\n * This method is currently empty, but it could be used to provide\n * instructions on the format of the input text.\n * @returns string\n */\n getFormatInstructions(): string {\n return \"\";\n }\n}\n\nexport * from \"./expression_type_handlers/types.js\";\n\nexport { MasterHandler } from \"./expression_type_handlers/factory.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,IAAa,mBAAb,cAAsC,iBAA6B;CACjE,eAAe;EAAC;EAAa;EAAkB;EAAa;CAE5D;;;;;;;;CASA,MAAM,eAAe;AACnB,MAAI,CAAC,KAAK,OACR,MAAK,SAAS,MAAM,UAAU,iBAAiB;;;;;;;;;CAWnD,MAAM,MAAM,MAAc;AACxB,QAAM,KAAK,cAAc;AAEzB,MAAI;GAGF,MAAM,OAFU,KAAK,OAAO,KAER,CAAC;AACrB,OAAI,CAAC,UAAU,sBAAsB,KAAK,CACxC,OAAM,IAAI,MACR,qCAAsC,KAAwB,OAC/D;GAGH,MAAM,EAAE,YAAY,wBAAwB;AAC5C,OAAI,CAAC,UAAU,iBAAiB,oBAAoB,CAClD,OAAM,IAAI,MAAM,0BAA0B;AAG5C,UAAO,MADe,cAAc,qBACV,CAAC,OAAO,oBAAoB;WAC/C,KAAK;AACZ,SAAM,IAAI,MAAM,iBAAiB,IAAI,IAAI,OAAO;;;;;;;;CASpD,wBAAgC;AAC9B,SAAO"}
|