@langchain/classic 1.0.34 → 1.0.36
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 +14 -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.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.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
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["AgentRunnableSequence","RunnablePassthrough","formatToOpenAIToolMessages","OpenAIToolsAgentOutputParser"],"sources":["../../../src/agents/openai_tools/index.ts"],"sourcesContent":["import type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport type {\n BaseChatModel,\n BaseChatModelCallOptions,\n} from \"@langchain/core/language_models/chat_models\";\nimport { ChatPromptTemplate } from \"@langchain/core/prompts\";\nimport { RunnablePassthrough } from \"@langchain/core/runnables\";\nimport { OpenAIClient } from \"@langchain/openai\";\nimport { convertToOpenAITool } from \"@langchain/core/utils/function_calling\";\nimport { ToolDefinition } from \"@langchain/core/language_models/base\";\nimport { formatToOpenAIToolMessages } from \"../format_scratchpad/openai_tools.js\";\nimport {\n OpenAIToolsAgentOutputParser,\n type ToolsAgentStep,\n} from \"./output_parser.js\";\nimport { AgentRunnableSequence } from \"../agent.js\";\n\nexport { OpenAIToolsAgentOutputParser, type ToolsAgentStep };\n\n/**\n * Params used by the createOpenAIToolsAgent function.\n */\nexport type CreateOpenAIToolsAgentParams = {\n /**\n * LLM to use as the agent. Should work with OpenAI tool calling,\n * so must either be an OpenAI model that supports that or a wrapper of\n * a different model that adds in equivalent support.\n */\n llm: BaseChatModel<\n BaseChatModelCallOptions & {\n tools?:\n | StructuredToolInterface[]\n | OpenAIClient.ChatCompletionTool[]\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | any[];\n }\n >;\n /** Tools this agent has access to. */\n tools: StructuredToolInterface[] | ToolDefinition[];\n /** The prompt to use, must have an input key of `agent_scratchpad`. */\n prompt: ChatPromptTemplate;\n /**\n * Whether to invoke the underlying model in streaming mode,\n * allowing streaming of intermediate steps. Defaults to true.\n */\n streamRunnable?: boolean;\n};\n\n/**\n * Create an agent that uses OpenAI-style tool calling.\n * @param params Params required to create the agent. Includes an LLM, tools, and prompt.\n * @returns A runnable sequence representing an agent. It takes as input all the same input\n * variables as the prompt passed in does. It returns as output either an\n * AgentAction or AgentFinish.\n *\n * @example\n * ```typescript\n * import { AgentExecutor, createOpenAIToolsAgent } from \"langchain/agents\";\n * import { pull } from \"langchain/hub\";\n * import type { ChatPromptTemplate } from \"@langchain/core/prompts\";\n * import { AIMessage, HumanMessage } from \"@langchain/core/messages\";\n *\n * import { ChatOpenAI } from \"@langchain/openai\";\n *\n * // Define the tools the agent will have access to.\n * const tools = [...];\n *\n * // Get the prompt to use - you can modify this!\n * // If you want to see the prompt in full, you can at:\n * // https://smith.langchain.com/hub/hwchase17/openai-tools-agent\n * const prompt = await pull<ChatPromptTemplate>(\n * \"hwchase17/openai-tools-agent\"\n * );\n *\n * const llm = new ChatOpenAI({\n * temperature: 0,\n * model: \"gpt-3.5-turbo-1106\",\n * });\n *\n * const agent = await createOpenAIToolsAgent({\n * llm,\n * tools,\n * prompt,\n * });\n *\n * const agentExecutor = new AgentExecutor({\n * agent,\n * tools,\n * });\n *\n * const result = await agentExecutor.invoke({\n * input: \"what is LangChain?\",\n * });\n *\n * // With chat history\n * const result2 = await agentExecutor.invoke({\n * input: \"what's my name?\",\n * chat_history: [\n * new HumanMessage(\"hi! my name is cob\"),\n * new AIMessage(\"Hello Cob! How can I assist you today?\"),\n * ],\n * });\n * ```\n */\nexport async function createOpenAIToolsAgent({\n llm,\n tools,\n prompt,\n streamRunnable,\n}: CreateOpenAIToolsAgentParams) {\n if (!prompt.inputVariables.includes(\"agent_scratchpad\")) {\n throw new Error(\n [\n `Prompt must have an input variable named \"agent_scratchpad\".`,\n `Found ${JSON.stringify(prompt.inputVariables)} instead.`,\n ].join(\"\\n\")\n );\n }\n const modelWithTools = llm.bindTools\n ? llm.bindTools(tools)\n : llm.withConfig({\n tools: tools.map((tool) => convertToOpenAITool(tool)),\n });\n const agent = AgentRunnableSequence.fromRunnables(\n [\n RunnablePassthrough.assign({\n agent_scratchpad: (input: { steps: ToolsAgentStep[] }) =>\n formatToOpenAIToolMessages(input.steps),\n }),\n prompt,\n modelWithTools,\n new OpenAIToolsAgentOutputParser(),\n ],\n {\n name: \"OpenAIToolsAgent\",\n streamRunnable,\n singleAction: false,\n }\n );\n return agent;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwGA,eAAsB,uBAAuB,EAC3C,KACA,OACA,QACA,kBAC+B;AAC/B,KAAI,CAAC,OAAO,eAAe,SAAS,mBAAmB,CACrD,OAAM,IAAI,MACR,CACE,gEACA,SAAS,KAAK,UAAU,OAAO,eAAe,CAAC,WAChD,CAAC,KAAK,KAAK,CACb;CAEH,MAAM,iBAAiB,IAAI,YACvB,IAAI,UAAU,MAAM,GACpB,IAAI,WAAW,EACb,OAAO,MAAM,KAAK,UAAA,GAAA,uCAAA,qBAA6B,KAAK,CAAC,EACtD,CAAC;AAiBN,QAhBcA,cAAAA,sBAAsB,cAClC;EACEC,0BAAAA,oBAAoB,OAAO,EACzB,mBAAmB,UACjBC,qBAAAA,qBAA2B,MAAM,MAAM,EAC1C,CAAC;EACF;EACA;EACA,IAAIC,sBAAAA,8BAA8B;EACnC,EACD;EACE,MAAM;EACN;EACA,cAAc;EACf,
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["AgentRunnableSequence","RunnablePassthrough","formatToOpenAIToolMessages","OpenAIToolsAgentOutputParser"],"sources":["../../../src/agents/openai_tools/index.ts"],"sourcesContent":["import type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport type {\n BaseChatModel,\n BaseChatModelCallOptions,\n} from \"@langchain/core/language_models/chat_models\";\nimport { ChatPromptTemplate } from \"@langchain/core/prompts\";\nimport { RunnablePassthrough } from \"@langchain/core/runnables\";\nimport { OpenAIClient } from \"@langchain/openai\";\nimport { convertToOpenAITool } from \"@langchain/core/utils/function_calling\";\nimport { ToolDefinition } from \"@langchain/core/language_models/base\";\nimport { formatToOpenAIToolMessages } from \"../format_scratchpad/openai_tools.js\";\nimport {\n OpenAIToolsAgentOutputParser,\n type ToolsAgentStep,\n} from \"./output_parser.js\";\nimport { AgentRunnableSequence } from \"../agent.js\";\n\nexport { OpenAIToolsAgentOutputParser, type ToolsAgentStep };\n\n/**\n * Params used by the createOpenAIToolsAgent function.\n */\nexport type CreateOpenAIToolsAgentParams = {\n /**\n * LLM to use as the agent. Should work with OpenAI tool calling,\n * so must either be an OpenAI model that supports that or a wrapper of\n * a different model that adds in equivalent support.\n */\n llm: BaseChatModel<\n BaseChatModelCallOptions & {\n tools?:\n | StructuredToolInterface[]\n | OpenAIClient.ChatCompletionTool[]\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | any[];\n }\n >;\n /** Tools this agent has access to. */\n tools: StructuredToolInterface[] | ToolDefinition[];\n /** The prompt to use, must have an input key of `agent_scratchpad`. */\n prompt: ChatPromptTemplate;\n /**\n * Whether to invoke the underlying model in streaming mode,\n * allowing streaming of intermediate steps. Defaults to true.\n */\n streamRunnable?: boolean;\n};\n\n/**\n * Create an agent that uses OpenAI-style tool calling.\n * @param params Params required to create the agent. Includes an LLM, tools, and prompt.\n * @returns A runnable sequence representing an agent. It takes as input all the same input\n * variables as the prompt passed in does. It returns as output either an\n * AgentAction or AgentFinish.\n *\n * @example\n * ```typescript\n * import { AgentExecutor, createOpenAIToolsAgent } from \"langchain/agents\";\n * import { pull } from \"langchain/hub\";\n * import type { ChatPromptTemplate } from \"@langchain/core/prompts\";\n * import { AIMessage, HumanMessage } from \"@langchain/core/messages\";\n *\n * import { ChatOpenAI } from \"@langchain/openai\";\n *\n * // Define the tools the agent will have access to.\n * const tools = [...];\n *\n * // Get the prompt to use - you can modify this!\n * // If you want to see the prompt in full, you can at:\n * // https://smith.langchain.com/hub/hwchase17/openai-tools-agent\n * const prompt = await pull<ChatPromptTemplate>(\n * \"hwchase17/openai-tools-agent\"\n * );\n *\n * const llm = new ChatOpenAI({\n * temperature: 0,\n * model: \"gpt-3.5-turbo-1106\",\n * });\n *\n * const agent = await createOpenAIToolsAgent({\n * llm,\n * tools,\n * prompt,\n * });\n *\n * const agentExecutor = new AgentExecutor({\n * agent,\n * tools,\n * });\n *\n * const result = await agentExecutor.invoke({\n * input: \"what is LangChain?\",\n * });\n *\n * // With chat history\n * const result2 = await agentExecutor.invoke({\n * input: \"what's my name?\",\n * chat_history: [\n * new HumanMessage(\"hi! my name is cob\"),\n * new AIMessage(\"Hello Cob! How can I assist you today?\"),\n * ],\n * });\n * ```\n */\nexport async function createOpenAIToolsAgent({\n llm,\n tools,\n prompt,\n streamRunnable,\n}: CreateOpenAIToolsAgentParams) {\n if (!prompt.inputVariables.includes(\"agent_scratchpad\")) {\n throw new Error(\n [\n `Prompt must have an input variable named \"agent_scratchpad\".`,\n `Found ${JSON.stringify(prompt.inputVariables)} instead.`,\n ].join(\"\\n\")\n );\n }\n const modelWithTools = llm.bindTools\n ? llm.bindTools(tools)\n : llm.withConfig({\n tools: tools.map((tool) => convertToOpenAITool(tool)),\n });\n const agent = AgentRunnableSequence.fromRunnables(\n [\n RunnablePassthrough.assign({\n agent_scratchpad: (input: { steps: ToolsAgentStep[] }) =>\n formatToOpenAIToolMessages(input.steps),\n }),\n prompt,\n modelWithTools,\n new OpenAIToolsAgentOutputParser(),\n ],\n {\n name: \"OpenAIToolsAgent\",\n streamRunnable,\n singleAction: false,\n }\n );\n return agent;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwGA,eAAsB,uBAAuB,EAC3C,KACA,OACA,QACA,kBAC+B;AAC/B,KAAI,CAAC,OAAO,eAAe,SAAS,mBAAmB,CACrD,OAAM,IAAI,MACR,CACE,gEACA,SAAS,KAAK,UAAU,OAAO,eAAe,CAAC,WAChD,CAAC,KAAK,KAAK,CACb;CAEH,MAAM,iBAAiB,IAAI,YACvB,IAAI,UAAU,MAAM,GACpB,IAAI,WAAW,EACb,OAAO,MAAM,KAAK,UAAA,GAAA,uCAAA,qBAA6B,KAAK,CAAC,EACtD,CAAC;AAiBN,QAhBcA,cAAAA,sBAAsB,cAClC;EACEC,0BAAAA,oBAAoB,OAAO,EACzB,mBAAmB,UACjBC,qBAAAA,qBAA2B,MAAM,MAAM,EAC1C,CAAC;EACF;EACA;EACA,IAAIC,sBAAAA,8BAA8B;EACnC,EACD;EACE,MAAM;EACN;EACA,cAAc;EACf,CAES"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["formatToOpenAIToolMessages"],"sources":["../../../src/agents/openai_tools/index.ts"],"sourcesContent":["import type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport type {\n BaseChatModel,\n BaseChatModelCallOptions,\n} from \"@langchain/core/language_models/chat_models\";\nimport { ChatPromptTemplate } from \"@langchain/core/prompts\";\nimport { RunnablePassthrough } from \"@langchain/core/runnables\";\nimport { OpenAIClient } from \"@langchain/openai\";\nimport { convertToOpenAITool } from \"@langchain/core/utils/function_calling\";\nimport { ToolDefinition } from \"@langchain/core/language_models/base\";\nimport { formatToOpenAIToolMessages } from \"../format_scratchpad/openai_tools.js\";\nimport {\n OpenAIToolsAgentOutputParser,\n type ToolsAgentStep,\n} from \"./output_parser.js\";\nimport { AgentRunnableSequence } from \"../agent.js\";\n\nexport { OpenAIToolsAgentOutputParser, type ToolsAgentStep };\n\n/**\n * Params used by the createOpenAIToolsAgent function.\n */\nexport type CreateOpenAIToolsAgentParams = {\n /**\n * LLM to use as the agent. Should work with OpenAI tool calling,\n * so must either be an OpenAI model that supports that or a wrapper of\n * a different model that adds in equivalent support.\n */\n llm: BaseChatModel<\n BaseChatModelCallOptions & {\n tools?:\n | StructuredToolInterface[]\n | OpenAIClient.ChatCompletionTool[]\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | any[];\n }\n >;\n /** Tools this agent has access to. */\n tools: StructuredToolInterface[] | ToolDefinition[];\n /** The prompt to use, must have an input key of `agent_scratchpad`. */\n prompt: ChatPromptTemplate;\n /**\n * Whether to invoke the underlying model in streaming mode,\n * allowing streaming of intermediate steps. Defaults to true.\n */\n streamRunnable?: boolean;\n};\n\n/**\n * Create an agent that uses OpenAI-style tool calling.\n * @param params Params required to create the agent. Includes an LLM, tools, and prompt.\n * @returns A runnable sequence representing an agent. It takes as input all the same input\n * variables as the prompt passed in does. It returns as output either an\n * AgentAction or AgentFinish.\n *\n * @example\n * ```typescript\n * import { AgentExecutor, createOpenAIToolsAgent } from \"langchain/agents\";\n * import { pull } from \"langchain/hub\";\n * import type { ChatPromptTemplate } from \"@langchain/core/prompts\";\n * import { AIMessage, HumanMessage } from \"@langchain/core/messages\";\n *\n * import { ChatOpenAI } from \"@langchain/openai\";\n *\n * // Define the tools the agent will have access to.\n * const tools = [...];\n *\n * // Get the prompt to use - you can modify this!\n * // If you want to see the prompt in full, you can at:\n * // https://smith.langchain.com/hub/hwchase17/openai-tools-agent\n * const prompt = await pull<ChatPromptTemplate>(\n * \"hwchase17/openai-tools-agent\"\n * );\n *\n * const llm = new ChatOpenAI({\n * temperature: 0,\n * model: \"gpt-3.5-turbo-1106\",\n * });\n *\n * const agent = await createOpenAIToolsAgent({\n * llm,\n * tools,\n * prompt,\n * });\n *\n * const agentExecutor = new AgentExecutor({\n * agent,\n * tools,\n * });\n *\n * const result = await agentExecutor.invoke({\n * input: \"what is LangChain?\",\n * });\n *\n * // With chat history\n * const result2 = await agentExecutor.invoke({\n * input: \"what's my name?\",\n * chat_history: [\n * new HumanMessage(\"hi! my name is cob\"),\n * new AIMessage(\"Hello Cob! How can I assist you today?\"),\n * ],\n * });\n * ```\n */\nexport async function createOpenAIToolsAgent({\n llm,\n tools,\n prompt,\n streamRunnable,\n}: CreateOpenAIToolsAgentParams) {\n if (!prompt.inputVariables.includes(\"agent_scratchpad\")) {\n throw new Error(\n [\n `Prompt must have an input variable named \"agent_scratchpad\".`,\n `Found ${JSON.stringify(prompt.inputVariables)} instead.`,\n ].join(\"\\n\")\n );\n }\n const modelWithTools = llm.bindTools\n ? llm.bindTools(tools)\n : llm.withConfig({\n tools: tools.map((tool) => convertToOpenAITool(tool)),\n });\n const agent = AgentRunnableSequence.fromRunnables(\n [\n RunnablePassthrough.assign({\n agent_scratchpad: (input: { steps: ToolsAgentStep[] }) =>\n formatToOpenAIToolMessages(input.steps),\n }),\n prompt,\n modelWithTools,\n new OpenAIToolsAgentOutputParser(),\n ],\n {\n name: \"OpenAIToolsAgent\",\n streamRunnable,\n singleAction: false,\n }\n );\n return agent;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwGA,eAAsB,uBAAuB,EAC3C,KACA,OACA,QACA,kBAC+B;AAC/B,KAAI,CAAC,OAAO,eAAe,SAAS,mBAAmB,CACrD,OAAM,IAAI,MACR,CACE,gEACA,SAAS,KAAK,UAAU,OAAO,eAAe,CAAC,WAChD,CAAC,KAAK,KAAK,CACb;CAEH,MAAM,iBAAiB,IAAI,YACvB,IAAI,UAAU,MAAM,GACpB,IAAI,WAAW,EACb,OAAO,MAAM,KAAK,SAAS,oBAAoB,KAAK,CAAC,EACtD,CAAC;AAiBN,QAhBc,sBAAsB,cAClC;EACE,oBAAoB,OAAO,EACzB,mBAAmB,UACjBA,qBAA2B,MAAM,MAAM,EAC1C,CAAC;EACF;EACA;EACA,IAAI,8BAA8B;EACnC,EACD;EACE,MAAM;EACN;EACA,cAAc;EACf,
|
|
1
|
+
{"version":3,"file":"index.js","names":["formatToOpenAIToolMessages"],"sources":["../../../src/agents/openai_tools/index.ts"],"sourcesContent":["import type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport type {\n BaseChatModel,\n BaseChatModelCallOptions,\n} from \"@langchain/core/language_models/chat_models\";\nimport { ChatPromptTemplate } from \"@langchain/core/prompts\";\nimport { RunnablePassthrough } from \"@langchain/core/runnables\";\nimport { OpenAIClient } from \"@langchain/openai\";\nimport { convertToOpenAITool } from \"@langchain/core/utils/function_calling\";\nimport { ToolDefinition } from \"@langchain/core/language_models/base\";\nimport { formatToOpenAIToolMessages } from \"../format_scratchpad/openai_tools.js\";\nimport {\n OpenAIToolsAgentOutputParser,\n type ToolsAgentStep,\n} from \"./output_parser.js\";\nimport { AgentRunnableSequence } from \"../agent.js\";\n\nexport { OpenAIToolsAgentOutputParser, type ToolsAgentStep };\n\n/**\n * Params used by the createOpenAIToolsAgent function.\n */\nexport type CreateOpenAIToolsAgentParams = {\n /**\n * LLM to use as the agent. Should work with OpenAI tool calling,\n * so must either be an OpenAI model that supports that or a wrapper of\n * a different model that adds in equivalent support.\n */\n llm: BaseChatModel<\n BaseChatModelCallOptions & {\n tools?:\n | StructuredToolInterface[]\n | OpenAIClient.ChatCompletionTool[]\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | any[];\n }\n >;\n /** Tools this agent has access to. */\n tools: StructuredToolInterface[] | ToolDefinition[];\n /** The prompt to use, must have an input key of `agent_scratchpad`. */\n prompt: ChatPromptTemplate;\n /**\n * Whether to invoke the underlying model in streaming mode,\n * allowing streaming of intermediate steps. Defaults to true.\n */\n streamRunnable?: boolean;\n};\n\n/**\n * Create an agent that uses OpenAI-style tool calling.\n * @param params Params required to create the agent. Includes an LLM, tools, and prompt.\n * @returns A runnable sequence representing an agent. It takes as input all the same input\n * variables as the prompt passed in does. It returns as output either an\n * AgentAction or AgentFinish.\n *\n * @example\n * ```typescript\n * import { AgentExecutor, createOpenAIToolsAgent } from \"langchain/agents\";\n * import { pull } from \"langchain/hub\";\n * import type { ChatPromptTemplate } from \"@langchain/core/prompts\";\n * import { AIMessage, HumanMessage } from \"@langchain/core/messages\";\n *\n * import { ChatOpenAI } from \"@langchain/openai\";\n *\n * // Define the tools the agent will have access to.\n * const tools = [...];\n *\n * // Get the prompt to use - you can modify this!\n * // If you want to see the prompt in full, you can at:\n * // https://smith.langchain.com/hub/hwchase17/openai-tools-agent\n * const prompt = await pull<ChatPromptTemplate>(\n * \"hwchase17/openai-tools-agent\"\n * );\n *\n * const llm = new ChatOpenAI({\n * temperature: 0,\n * model: \"gpt-3.5-turbo-1106\",\n * });\n *\n * const agent = await createOpenAIToolsAgent({\n * llm,\n * tools,\n * prompt,\n * });\n *\n * const agentExecutor = new AgentExecutor({\n * agent,\n * tools,\n * });\n *\n * const result = await agentExecutor.invoke({\n * input: \"what is LangChain?\",\n * });\n *\n * // With chat history\n * const result2 = await agentExecutor.invoke({\n * input: \"what's my name?\",\n * chat_history: [\n * new HumanMessage(\"hi! my name is cob\"),\n * new AIMessage(\"Hello Cob! How can I assist you today?\"),\n * ],\n * });\n * ```\n */\nexport async function createOpenAIToolsAgent({\n llm,\n tools,\n prompt,\n streamRunnable,\n}: CreateOpenAIToolsAgentParams) {\n if (!prompt.inputVariables.includes(\"agent_scratchpad\")) {\n throw new Error(\n [\n `Prompt must have an input variable named \"agent_scratchpad\".`,\n `Found ${JSON.stringify(prompt.inputVariables)} instead.`,\n ].join(\"\\n\")\n );\n }\n const modelWithTools = llm.bindTools\n ? llm.bindTools(tools)\n : llm.withConfig({\n tools: tools.map((tool) => convertToOpenAITool(tool)),\n });\n const agent = AgentRunnableSequence.fromRunnables(\n [\n RunnablePassthrough.assign({\n agent_scratchpad: (input: { steps: ToolsAgentStep[] }) =>\n formatToOpenAIToolMessages(input.steps),\n }),\n prompt,\n modelWithTools,\n new OpenAIToolsAgentOutputParser(),\n ],\n {\n name: \"OpenAIToolsAgent\",\n streamRunnable,\n singleAction: false,\n }\n );\n return agent;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwGA,eAAsB,uBAAuB,EAC3C,KACA,OACA,QACA,kBAC+B;AAC/B,KAAI,CAAC,OAAO,eAAe,SAAS,mBAAmB,CACrD,OAAM,IAAI,MACR,CACE,gEACA,SAAS,KAAK,UAAU,OAAO,eAAe,CAAC,WAChD,CAAC,KAAK,KAAK,CACb;CAEH,MAAM,iBAAiB,IAAI,YACvB,IAAI,UAAU,MAAM,GACpB,IAAI,WAAW,EACb,OAAO,MAAM,KAAK,SAAS,oBAAoB,KAAK,CAAC,EACtD,CAAC;AAiBN,QAhBc,sBAAsB,cAClC;EACE,oBAAoB,OAAO,EACzB,mBAAmB,UACjBA,qBAA2B,MAAM,MAAM,EAC1C,CAAC;EACF;EACA;EACA,IAAI,8BAA8B;EACnC,EACD;EACE,MAAM;EACN;EACA,cAAc;EACf,CAES"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["renderTextDescription","AgentRunnableSequence","RunnablePassthrough","formatLogToString","ReActSingleInputOutputParser"],"sources":["../../../src/agents/react/index.ts"],"sourcesContent":["import type { ToolInterface } from \"@langchain/core/tools\";\nimport { BasePromptTemplate } from \"@langchain/core/prompts\";\nimport type {\n BaseLanguageModel,\n BaseLanguageModelInterface,\n} from \"@langchain/core/language_models/base\";\nimport { RunnablePassthrough } from \"@langchain/core/runnables\";\nimport { AgentStep } from \"@langchain/core/agents\";\nimport { renderTextDescription } from \"../../tools/render.js\";\nimport { formatLogToString } from \"../format_scratchpad/log.js\";\nimport { ReActSingleInputOutputParser } from \"./output_parser.js\";\nimport { AgentRunnableSequence } from \"../agent.js\";\n\n/**\n * Params used by the createXmlAgent function.\n */\nexport type CreateReactAgentParams = {\n /** LLM to use for the agent. */\n llm: BaseLanguageModelInterface;\n /** Tools this agent has access to. */\n tools: ToolInterface[];\n /**\n * The prompt to use. Must have input keys for\n * `tools`, `tool_names`, and `agent_scratchpad`.\n */\n prompt: BasePromptTemplate;\n /**\n * Whether to invoke the underlying model in streaming mode,\n * allowing streaming of intermediate steps. Defaults to true.\n */\n streamRunnable?: boolean;\n};\n\n/**\n * Create an agent that uses ReAct prompting.\n * @param params Params required to create the agent. Includes an LLM, tools, and prompt.\n * @returns A runnable sequence representing an agent. It takes as input all the same input\n * variables as the prompt passed in does. It returns as output either an\n * AgentAction or AgentFinish.\n *\n * @example\n * ```typescript\n * import { AgentExecutor, createReactAgent } from \"langchain/agents\";\n * import { pull } from \"langchain/hub\";\n * import type { PromptTemplate } from \"@langchain/core/prompts\";\n *\n * import { OpenAI } from \"@langchain/openai\";\n *\n * // Define the tools the agent will have access to.\n * const tools = [...];\n *\n * // Get the prompt to use - you can modify this!\n * // If you want to see the prompt in full, you can at:\n * // https://smith.langchain.com/hub/hwchase17/react\n * const prompt = await pull<PromptTemplate>(\"hwchase17/react\");\n *\n * const llm = new OpenAI({\n * temperature: 0,\n * });\n *\n * const agent = await createReactAgent({\n * llm,\n * tools,\n * prompt,\n * });\n *\n * const agentExecutor = new AgentExecutor({\n * agent,\n * tools,\n * });\n *\n * const result = await agentExecutor.invoke({\n * input: \"what is LangChain?\",\n * });\n * ```\n */\nexport async function createReactAgent({\n llm,\n tools,\n prompt,\n streamRunnable,\n}: CreateReactAgentParams) {\n const missingVariables = [\"tools\", \"tool_names\", \"agent_scratchpad\"].filter(\n (v) => !prompt.inputVariables.includes(v)\n );\n if (missingVariables.length > 0) {\n throw new Error(\n `Provided prompt is missing required input variables: ${JSON.stringify(\n missingVariables\n )}`\n );\n }\n const toolNames = tools.map((tool) => tool.name);\n const partialedPrompt = await prompt.partial({\n tools: renderTextDescription(tools),\n tool_names: toolNames.join(\", \"),\n });\n const llmWithStop = (llm as BaseLanguageModel).withConfig({\n stop: [\"\\nObservation:\"],\n });\n const agent = AgentRunnableSequence.fromRunnables(\n [\n RunnablePassthrough.assign({\n agent_scratchpad: (input: { steps: AgentStep[] }) =>\n formatLogToString(input.steps),\n }),\n partialedPrompt,\n llmWithStop,\n new ReActSingleInputOutputParser({\n toolNames,\n }),\n ],\n {\n name: \"ReactAgent\",\n streamRunnable,\n singleAction: true,\n }\n );\n return agent;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4EA,eAAsB,iBAAiB,EACrC,KACA,OACA,QACA,kBACyB;CACzB,MAAM,mBAAmB;EAAC;EAAS;EAAc;EAAmB,CAAC,QAClE,MAAM,CAAC,OAAO,eAAe,SAAS,EAAE,CAC1C;AACD,KAAI,iBAAiB,SAAS,EAC5B,OAAM,IAAI,MACR,wDAAwD,KAAK,UAC3D,iBACD,GACF;CAEH,MAAM,YAAY,MAAM,KAAK,SAAS,KAAK,KAAK;CAChD,MAAM,kBAAkB,MAAM,OAAO,QAAQ;EAC3C,OAAOA,qBAAAA,sBAAsB,MAAM;EACnC,YAAY,UAAU,KAAK,KAAK;EACjC,CAAC;CACF,MAAM,cAAe,IAA0B,WAAW,EACxD,MAAM,CAAC,iBAAiB,EACzB,CAAC;AAmBF,QAlBcC,cAAAA,sBAAsB,cAClC;EACEC,0BAAAA,oBAAoB,OAAO,EACzB,mBAAmB,UACjBC,qCAAAA,kBAAkB,MAAM,MAAM,EACjC,CAAC;EACF;EACA;EACA,IAAIC,mCAAAA,6BAA6B,EAC/B,WACD,CAAC;EACH,EACD;EACE,MAAM;EACN;EACA,cAAc;EACf,
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["renderTextDescription","AgentRunnableSequence","RunnablePassthrough","formatLogToString","ReActSingleInputOutputParser"],"sources":["../../../src/agents/react/index.ts"],"sourcesContent":["import type { ToolInterface } from \"@langchain/core/tools\";\nimport { BasePromptTemplate } from \"@langchain/core/prompts\";\nimport type {\n BaseLanguageModel,\n BaseLanguageModelInterface,\n} from \"@langchain/core/language_models/base\";\nimport { RunnablePassthrough } from \"@langchain/core/runnables\";\nimport { AgentStep } from \"@langchain/core/agents\";\nimport { renderTextDescription } from \"../../tools/render.js\";\nimport { formatLogToString } from \"../format_scratchpad/log.js\";\nimport { ReActSingleInputOutputParser } from \"./output_parser.js\";\nimport { AgentRunnableSequence } from \"../agent.js\";\n\n/**\n * Params used by the createXmlAgent function.\n */\nexport type CreateReactAgentParams = {\n /** LLM to use for the agent. */\n llm: BaseLanguageModelInterface;\n /** Tools this agent has access to. */\n tools: ToolInterface[];\n /**\n * The prompt to use. Must have input keys for\n * `tools`, `tool_names`, and `agent_scratchpad`.\n */\n prompt: BasePromptTemplate;\n /**\n * Whether to invoke the underlying model in streaming mode,\n * allowing streaming of intermediate steps. Defaults to true.\n */\n streamRunnable?: boolean;\n};\n\n/**\n * Create an agent that uses ReAct prompting.\n * @param params Params required to create the agent. Includes an LLM, tools, and prompt.\n * @returns A runnable sequence representing an agent. It takes as input all the same input\n * variables as the prompt passed in does. It returns as output either an\n * AgentAction or AgentFinish.\n *\n * @example\n * ```typescript\n * import { AgentExecutor, createReactAgent } from \"langchain/agents\";\n * import { pull } from \"langchain/hub\";\n * import type { PromptTemplate } from \"@langchain/core/prompts\";\n *\n * import { OpenAI } from \"@langchain/openai\";\n *\n * // Define the tools the agent will have access to.\n * const tools = [...];\n *\n * // Get the prompt to use - you can modify this!\n * // If you want to see the prompt in full, you can at:\n * // https://smith.langchain.com/hub/hwchase17/react\n * const prompt = await pull<PromptTemplate>(\"hwchase17/react\");\n *\n * const llm = new OpenAI({\n * temperature: 0,\n * });\n *\n * const agent = await createReactAgent({\n * llm,\n * tools,\n * prompt,\n * });\n *\n * const agentExecutor = new AgentExecutor({\n * agent,\n * tools,\n * });\n *\n * const result = await agentExecutor.invoke({\n * input: \"what is LangChain?\",\n * });\n * ```\n */\nexport async function createReactAgent({\n llm,\n tools,\n prompt,\n streamRunnable,\n}: CreateReactAgentParams) {\n const missingVariables = [\"tools\", \"tool_names\", \"agent_scratchpad\"].filter(\n (v) => !prompt.inputVariables.includes(v)\n );\n if (missingVariables.length > 0) {\n throw new Error(\n `Provided prompt is missing required input variables: ${JSON.stringify(\n missingVariables\n )}`\n );\n }\n const toolNames = tools.map((tool) => tool.name);\n const partialedPrompt = await prompt.partial({\n tools: renderTextDescription(tools),\n tool_names: toolNames.join(\", \"),\n });\n const llmWithStop = (llm as BaseLanguageModel).withConfig({\n stop: [\"\\nObservation:\"],\n });\n const agent = AgentRunnableSequence.fromRunnables(\n [\n RunnablePassthrough.assign({\n agent_scratchpad: (input: { steps: AgentStep[] }) =>\n formatLogToString(input.steps),\n }),\n partialedPrompt,\n llmWithStop,\n new ReActSingleInputOutputParser({\n toolNames,\n }),\n ],\n {\n name: \"ReactAgent\",\n streamRunnable,\n singleAction: true,\n }\n );\n return agent;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4EA,eAAsB,iBAAiB,EACrC,KACA,OACA,QACA,kBACyB;CACzB,MAAM,mBAAmB;EAAC;EAAS;EAAc;EAAmB,CAAC,QAClE,MAAM,CAAC,OAAO,eAAe,SAAS,EAAE,CAC1C;AACD,KAAI,iBAAiB,SAAS,EAC5B,OAAM,IAAI,MACR,wDAAwD,KAAK,UAC3D,iBACD,GACF;CAEH,MAAM,YAAY,MAAM,KAAK,SAAS,KAAK,KAAK;CAChD,MAAM,kBAAkB,MAAM,OAAO,QAAQ;EAC3C,OAAOA,qBAAAA,sBAAsB,MAAM;EACnC,YAAY,UAAU,KAAK,KAAK;EACjC,CAAC;CACF,MAAM,cAAe,IAA0B,WAAW,EACxD,MAAM,CAAC,iBAAiB,EACzB,CAAC;AAmBF,QAlBcC,cAAAA,sBAAsB,cAClC;EACEC,0BAAAA,oBAAoB,OAAO,EACzB,mBAAmB,UACjBC,qCAAAA,kBAAkB,MAAM,MAAM,EACjC,CAAC;EACF;EACA;EACA,IAAIC,mCAAAA,6BAA6B,EAC/B,WACD,CAAC;EACH,EACD;EACE,MAAM;EACN;EACA,cAAc;EACf,CAES"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/agents/react/index.ts"],"sourcesContent":["import type { ToolInterface } from \"@langchain/core/tools\";\nimport { BasePromptTemplate } from \"@langchain/core/prompts\";\nimport type {\n BaseLanguageModel,\n BaseLanguageModelInterface,\n} from \"@langchain/core/language_models/base\";\nimport { RunnablePassthrough } from \"@langchain/core/runnables\";\nimport { AgentStep } from \"@langchain/core/agents\";\nimport { renderTextDescription } from \"../../tools/render.js\";\nimport { formatLogToString } from \"../format_scratchpad/log.js\";\nimport { ReActSingleInputOutputParser } from \"./output_parser.js\";\nimport { AgentRunnableSequence } from \"../agent.js\";\n\n/**\n * Params used by the createXmlAgent function.\n */\nexport type CreateReactAgentParams = {\n /** LLM to use for the agent. */\n llm: BaseLanguageModelInterface;\n /** Tools this agent has access to. */\n tools: ToolInterface[];\n /**\n * The prompt to use. Must have input keys for\n * `tools`, `tool_names`, and `agent_scratchpad`.\n */\n prompt: BasePromptTemplate;\n /**\n * Whether to invoke the underlying model in streaming mode,\n * allowing streaming of intermediate steps. Defaults to true.\n */\n streamRunnable?: boolean;\n};\n\n/**\n * Create an agent that uses ReAct prompting.\n * @param params Params required to create the agent. Includes an LLM, tools, and prompt.\n * @returns A runnable sequence representing an agent. It takes as input all the same input\n * variables as the prompt passed in does. It returns as output either an\n * AgentAction or AgentFinish.\n *\n * @example\n * ```typescript\n * import { AgentExecutor, createReactAgent } from \"langchain/agents\";\n * import { pull } from \"langchain/hub\";\n * import type { PromptTemplate } from \"@langchain/core/prompts\";\n *\n * import { OpenAI } from \"@langchain/openai\";\n *\n * // Define the tools the agent will have access to.\n * const tools = [...];\n *\n * // Get the prompt to use - you can modify this!\n * // If you want to see the prompt in full, you can at:\n * // https://smith.langchain.com/hub/hwchase17/react\n * const prompt = await pull<PromptTemplate>(\"hwchase17/react\");\n *\n * const llm = new OpenAI({\n * temperature: 0,\n * });\n *\n * const agent = await createReactAgent({\n * llm,\n * tools,\n * prompt,\n * });\n *\n * const agentExecutor = new AgentExecutor({\n * agent,\n * tools,\n * });\n *\n * const result = await agentExecutor.invoke({\n * input: \"what is LangChain?\",\n * });\n * ```\n */\nexport async function createReactAgent({\n llm,\n tools,\n prompt,\n streamRunnable,\n}: CreateReactAgentParams) {\n const missingVariables = [\"tools\", \"tool_names\", \"agent_scratchpad\"].filter(\n (v) => !prompt.inputVariables.includes(v)\n );\n if (missingVariables.length > 0) {\n throw new Error(\n `Provided prompt is missing required input variables: ${JSON.stringify(\n missingVariables\n )}`\n );\n }\n const toolNames = tools.map((tool) => tool.name);\n const partialedPrompt = await prompt.partial({\n tools: renderTextDescription(tools),\n tool_names: toolNames.join(\", \"),\n });\n const llmWithStop = (llm as BaseLanguageModel).withConfig({\n stop: [\"\\nObservation:\"],\n });\n const agent = AgentRunnableSequence.fromRunnables(\n [\n RunnablePassthrough.assign({\n agent_scratchpad: (input: { steps: AgentStep[] }) =>\n formatLogToString(input.steps),\n }),\n partialedPrompt,\n llmWithStop,\n new ReActSingleInputOutputParser({\n toolNames,\n }),\n ],\n {\n name: \"ReactAgent\",\n streamRunnable,\n singleAction: true,\n }\n );\n return agent;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4EA,eAAsB,iBAAiB,EACrC,KACA,OACA,QACA,kBACyB;CACzB,MAAM,mBAAmB;EAAC;EAAS;EAAc;EAAmB,CAAC,QAClE,MAAM,CAAC,OAAO,eAAe,SAAS,EAAE,CAC1C;AACD,KAAI,iBAAiB,SAAS,EAC5B,OAAM,IAAI,MACR,wDAAwD,KAAK,UAC3D,iBACD,GACF;CAEH,MAAM,YAAY,MAAM,KAAK,SAAS,KAAK,KAAK;CAChD,MAAM,kBAAkB,MAAM,OAAO,QAAQ;EAC3C,OAAO,sBAAsB,MAAM;EACnC,YAAY,UAAU,KAAK,KAAK;EACjC,CAAC;CACF,MAAM,cAAe,IAA0B,WAAW,EACxD,MAAM,CAAC,iBAAiB,EACzB,CAAC;AAmBF,QAlBc,sBAAsB,cAClC;EACE,oBAAoB,OAAO,EACzB,mBAAmB,UACjB,kBAAkB,MAAM,MAAM,EACjC,CAAC;EACF;EACA;EACA,IAAI,6BAA6B,EAC/B,WACD,CAAC;EACH,EACD;EACE,MAAM;EACN;EACA,cAAc;EACf,
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/agents/react/index.ts"],"sourcesContent":["import type { ToolInterface } from \"@langchain/core/tools\";\nimport { BasePromptTemplate } from \"@langchain/core/prompts\";\nimport type {\n BaseLanguageModel,\n BaseLanguageModelInterface,\n} from \"@langchain/core/language_models/base\";\nimport { RunnablePassthrough } from \"@langchain/core/runnables\";\nimport { AgentStep } from \"@langchain/core/agents\";\nimport { renderTextDescription } from \"../../tools/render.js\";\nimport { formatLogToString } from \"../format_scratchpad/log.js\";\nimport { ReActSingleInputOutputParser } from \"./output_parser.js\";\nimport { AgentRunnableSequence } from \"../agent.js\";\n\n/**\n * Params used by the createXmlAgent function.\n */\nexport type CreateReactAgentParams = {\n /** LLM to use for the agent. */\n llm: BaseLanguageModelInterface;\n /** Tools this agent has access to. */\n tools: ToolInterface[];\n /**\n * The prompt to use. Must have input keys for\n * `tools`, `tool_names`, and `agent_scratchpad`.\n */\n prompt: BasePromptTemplate;\n /**\n * Whether to invoke the underlying model in streaming mode,\n * allowing streaming of intermediate steps. Defaults to true.\n */\n streamRunnable?: boolean;\n};\n\n/**\n * Create an agent that uses ReAct prompting.\n * @param params Params required to create the agent. Includes an LLM, tools, and prompt.\n * @returns A runnable sequence representing an agent. It takes as input all the same input\n * variables as the prompt passed in does. It returns as output either an\n * AgentAction or AgentFinish.\n *\n * @example\n * ```typescript\n * import { AgentExecutor, createReactAgent } from \"langchain/agents\";\n * import { pull } from \"langchain/hub\";\n * import type { PromptTemplate } from \"@langchain/core/prompts\";\n *\n * import { OpenAI } from \"@langchain/openai\";\n *\n * // Define the tools the agent will have access to.\n * const tools = [...];\n *\n * // Get the prompt to use - you can modify this!\n * // If you want to see the prompt in full, you can at:\n * // https://smith.langchain.com/hub/hwchase17/react\n * const prompt = await pull<PromptTemplate>(\"hwchase17/react\");\n *\n * const llm = new OpenAI({\n * temperature: 0,\n * });\n *\n * const agent = await createReactAgent({\n * llm,\n * tools,\n * prompt,\n * });\n *\n * const agentExecutor = new AgentExecutor({\n * agent,\n * tools,\n * });\n *\n * const result = await agentExecutor.invoke({\n * input: \"what is LangChain?\",\n * });\n * ```\n */\nexport async function createReactAgent({\n llm,\n tools,\n prompt,\n streamRunnable,\n}: CreateReactAgentParams) {\n const missingVariables = [\"tools\", \"tool_names\", \"agent_scratchpad\"].filter(\n (v) => !prompt.inputVariables.includes(v)\n );\n if (missingVariables.length > 0) {\n throw new Error(\n `Provided prompt is missing required input variables: ${JSON.stringify(\n missingVariables\n )}`\n );\n }\n const toolNames = tools.map((tool) => tool.name);\n const partialedPrompt = await prompt.partial({\n tools: renderTextDescription(tools),\n tool_names: toolNames.join(\", \"),\n });\n const llmWithStop = (llm as BaseLanguageModel).withConfig({\n stop: [\"\\nObservation:\"],\n });\n const agent = AgentRunnableSequence.fromRunnables(\n [\n RunnablePassthrough.assign({\n agent_scratchpad: (input: { steps: AgentStep[] }) =>\n formatLogToString(input.steps),\n }),\n partialedPrompt,\n llmWithStop,\n new ReActSingleInputOutputParser({\n toolNames,\n }),\n ],\n {\n name: \"ReactAgent\",\n streamRunnable,\n singleAction: true,\n }\n );\n return agent;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4EA,eAAsB,iBAAiB,EACrC,KACA,OACA,QACA,kBACyB;CACzB,MAAM,mBAAmB;EAAC;EAAS;EAAc;EAAmB,CAAC,QAClE,MAAM,CAAC,OAAO,eAAe,SAAS,EAAE,CAC1C;AACD,KAAI,iBAAiB,SAAS,EAC5B,OAAM,IAAI,MACR,wDAAwD,KAAK,UAC3D,iBACD,GACF;CAEH,MAAM,YAAY,MAAM,KAAK,SAAS,KAAK,KAAK;CAChD,MAAM,kBAAkB,MAAM,OAAO,QAAQ;EAC3C,OAAO,sBAAsB,MAAM;EACnC,YAAY,UAAU,KAAK,KAAK;EACjC,CAAC;CACF,MAAM,cAAe,IAA0B,WAAW,EACxD,MAAM,CAAC,iBAAiB,EACzB,CAAC;AAmBF,QAlBc,sBAAsB,cAClC;EACE,oBAAoB,OAAO,EACzB,mBAAmB,UACjB,kBAAkB,MAAM,MAAM,EACjC,CAAC;EACF;EACA;EACA,IAAI,6BAA6B,EAC/B,WACD,CAAC;EACH,EACD;EACE,MAAM;EACN;EACA,cAAc;EACf,CAES"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"output_parser.cjs","names":["AgentActionOutputParser","OutputParserException","FORMAT_INSTRUCTIONS"],"sources":["../../../src/agents/react/output_parser.ts"],"sourcesContent":["import { AgentAction, AgentFinish } from \"@langchain/core/agents\";\nimport { renderTemplate } from \"@langchain/core/prompts\";\nimport { OutputParserException } from \"@langchain/core/output_parsers\";\nimport { AgentActionOutputParser } from \"../types.js\";\nimport { FORMAT_INSTRUCTIONS } from \"./prompt.js\";\n\nconst FINAL_ANSWER_ACTION = \"Final Answer:\";\nconst FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE =\n \"Parsing LLM output produced both a final answer and a parse-able action:\";\n\n/**\n * Parses ReAct-style LLM calls that have a single tool input.\n *\n * Expects output to be in one of two formats.\n *\n * If the output signals that an action should be taken,\n * should be in the below format. This will result in an AgentAction\n * being returned.\n *\n * ```\n * Thought: agent thought here\n * Action: search\n * Action Input: what is the temperature in SF?\n * ```\n *\n * If the output signals that a final answer should be given,\n * should be in the below format. This will result in an AgentFinish\n * being returned.\n *\n * ```\n * Thought: agent thought here\n * Final Answer: The temperature is 100 degrees\n * ```\n * @example\n * ```typescript\n *\n * const runnableAgent = RunnableSequence.from([\n * ...rest of runnable\n * new ReActSingleInputOutputParser({ toolNames: [\"SerpAPI\", \"Calculator\"] }),\n * ]);\n * const agent = AgentExecutor.fromAgentAndTools({\n * agent: runnableAgent,\n * tools: [new SerpAPI(), new Calculator()],\n * });\n * const result = await agent.invoke({\n * input: \"whats the weather in pomfret?\",\n * });\n * ```\n */\nexport class ReActSingleInputOutputParser extends AgentActionOutputParser {\n lc_namespace = [\"langchain\", \"agents\", \"react\"];\n\n private toolNames: string[];\n\n constructor(fields: { toolNames: string[] }) {\n super(...arguments);\n this.toolNames = fields.toolNames;\n }\n\n /**\n * Parses the given text into an AgentAction or AgentFinish object. If an\n * output fixing parser is defined, uses it to parse the text.\n * @param text Text to parse.\n * @returns Promise that resolves to an AgentAction or AgentFinish object.\n */\n async parse(text: string): Promise<AgentAction | AgentFinish> {\n const includesAnswer = text.includes(FINAL_ANSWER_ACTION);\n const regex =\n /Action\\s*\\d*\\s*:[\\s]*(.*?)[\\s]*Action\\s*\\d*\\s*Input\\s*\\d*\\s*:[\\s]*(.*)/;\n const actionMatch = text.match(regex);\n if (actionMatch) {\n if (includesAnswer) {\n throw new OutputParserException(\n `${FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE}: ${text}`\n );\n }\n\n const action = actionMatch[1];\n const actionInput = actionMatch[2];\n const toolInput = actionInput.trim().replace(/^\"|\"$/g, \"\");\n\n return {\n tool: action,\n toolInput,\n log: text,\n };\n }\n\n if (includesAnswer) {\n const finalAnswerText = text.split(FINAL_ANSWER_ACTION)[1].trim();\n return {\n returnValues: {\n output: finalAnswerText,\n },\n log: text,\n };\n }\n\n throw new OutputParserException(`Could not parse LLM output: ${text}`);\n }\n\n /**\n * Returns the format instructions as a string. If the 'raw' option is\n * true, returns the raw FORMAT_INSTRUCTIONS.\n * @param options Options for getting the format instructions.\n * @returns Format instructions as a string.\n */\n getFormatInstructions(): string {\n return renderTemplate(FORMAT_INSTRUCTIONS, \"f-string\", {\n tool_names: this.toolNames.join(\", \"),\n });\n }\n}\n"],"mappings":";;;;;;;;AAMA,MAAM,sBAAsB;AAC5B,MAAM,iDACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCF,IAAa,+BAAb,cAAkDA,cAAAA,wBAAwB;CACxE,eAAe;EAAC;EAAa;EAAU;EAAQ;CAE/C;CAEA,YAAY,QAAiC;AAC3C,QAAM,GAAG,UAAU;AACnB,OAAK,YAAY,OAAO;;;;;;;;CAS1B,MAAM,MAAM,MAAkD;EAC5D,MAAM,iBAAiB,KAAK,SAAS,oBAAoB;EAGzD,MAAM,cAAc,KAAK,
|
|
1
|
+
{"version":3,"file":"output_parser.cjs","names":["AgentActionOutputParser","OutputParserException","FORMAT_INSTRUCTIONS"],"sources":["../../../src/agents/react/output_parser.ts"],"sourcesContent":["import { AgentAction, AgentFinish } from \"@langchain/core/agents\";\nimport { renderTemplate } from \"@langchain/core/prompts\";\nimport { OutputParserException } from \"@langchain/core/output_parsers\";\nimport { AgentActionOutputParser } from \"../types.js\";\nimport { FORMAT_INSTRUCTIONS } from \"./prompt.js\";\n\nconst FINAL_ANSWER_ACTION = \"Final Answer:\";\nconst FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE =\n \"Parsing LLM output produced both a final answer and a parse-able action:\";\n\n/**\n * Parses ReAct-style LLM calls that have a single tool input.\n *\n * Expects output to be in one of two formats.\n *\n * If the output signals that an action should be taken,\n * should be in the below format. This will result in an AgentAction\n * being returned.\n *\n * ```\n * Thought: agent thought here\n * Action: search\n * Action Input: what is the temperature in SF?\n * ```\n *\n * If the output signals that a final answer should be given,\n * should be in the below format. This will result in an AgentFinish\n * being returned.\n *\n * ```\n * Thought: agent thought here\n * Final Answer: The temperature is 100 degrees\n * ```\n * @example\n * ```typescript\n *\n * const runnableAgent = RunnableSequence.from([\n * ...rest of runnable\n * new ReActSingleInputOutputParser({ toolNames: [\"SerpAPI\", \"Calculator\"] }),\n * ]);\n * const agent = AgentExecutor.fromAgentAndTools({\n * agent: runnableAgent,\n * tools: [new SerpAPI(), new Calculator()],\n * });\n * const result = await agent.invoke({\n * input: \"whats the weather in pomfret?\",\n * });\n * ```\n */\nexport class ReActSingleInputOutputParser extends AgentActionOutputParser {\n lc_namespace = [\"langchain\", \"agents\", \"react\"];\n\n private toolNames: string[];\n\n constructor(fields: { toolNames: string[] }) {\n super(...arguments);\n this.toolNames = fields.toolNames;\n }\n\n /**\n * Parses the given text into an AgentAction or AgentFinish object. If an\n * output fixing parser is defined, uses it to parse the text.\n * @param text Text to parse.\n * @returns Promise that resolves to an AgentAction or AgentFinish object.\n */\n async parse(text: string): Promise<AgentAction | AgentFinish> {\n const includesAnswer = text.includes(FINAL_ANSWER_ACTION);\n const regex =\n /Action\\s*\\d*\\s*:[\\s]*(.*?)[\\s]*Action\\s*\\d*\\s*Input\\s*\\d*\\s*:[\\s]*(.*)/;\n const actionMatch = text.match(regex);\n if (actionMatch) {\n if (includesAnswer) {\n throw new OutputParserException(\n `${FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE}: ${text}`\n );\n }\n\n const action = actionMatch[1];\n const actionInput = actionMatch[2];\n const toolInput = actionInput.trim().replace(/^\"|\"$/g, \"\");\n\n return {\n tool: action,\n toolInput,\n log: text,\n };\n }\n\n if (includesAnswer) {\n const finalAnswerText = text.split(FINAL_ANSWER_ACTION)[1].trim();\n return {\n returnValues: {\n output: finalAnswerText,\n },\n log: text,\n };\n }\n\n throw new OutputParserException(`Could not parse LLM output: ${text}`);\n }\n\n /**\n * Returns the format instructions as a string. If the 'raw' option is\n * true, returns the raw FORMAT_INSTRUCTIONS.\n * @param options Options for getting the format instructions.\n * @returns Format instructions as a string.\n */\n getFormatInstructions(): string {\n return renderTemplate(FORMAT_INSTRUCTIONS, \"f-string\", {\n tool_names: this.toolNames.join(\", \"),\n });\n }\n}\n"],"mappings":";;;;;;;;AAMA,MAAM,sBAAsB;AAC5B,MAAM,iDACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCF,IAAa,+BAAb,cAAkDA,cAAAA,wBAAwB;CACxE,eAAe;EAAC;EAAa;EAAU;EAAQ;CAE/C;CAEA,YAAY,QAAiC;AAC3C,QAAM,GAAG,UAAU;AACnB,OAAK,YAAY,OAAO;;;;;;;;CAS1B,MAAM,MAAM,MAAkD;EAC5D,MAAM,iBAAiB,KAAK,SAAS,oBAAoB;EAGzD,MAAM,cAAc,KAAK,MAAM,yEAAM;AACrC,MAAI,aAAa;AACf,OAAI,eACF,OAAM,IAAIC,+BAAAA,sBACR,GAAG,+CAA+C,IAAI,OACvD;AAOH,UAAO;IACL,MALa,YAAY;IAMzB,WALkB,YAAY,GACF,MAAM,CAAC,QAAQ,UAAU,GAI5C;IACT,KAAK;IACN;;AAGH,MAAI,eAEF,QAAO;GACL,cAAc,EACZ,QAHoB,KAAK,MAAM,oBAAoB,CAAC,GAAG,MAGhC,EACxB;GACD,KAAK;GACN;AAGH,QAAM,IAAIA,+BAAAA,sBAAsB,+BAA+B,OAAO;;;;;;;;CASxE,wBAAgC;AAC9B,UAAA,GAAA,wBAAA,gBAAsBC,eAAAA,qBAAqB,YAAY,EACrD,YAAY,KAAK,UAAU,KAAK,KAAK,EACtC,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"output_parser.js","names":[],"sources":["../../../src/agents/react/output_parser.ts"],"sourcesContent":["import { AgentAction, AgentFinish } from \"@langchain/core/agents\";\nimport { renderTemplate } from \"@langchain/core/prompts\";\nimport { OutputParserException } from \"@langchain/core/output_parsers\";\nimport { AgentActionOutputParser } from \"../types.js\";\nimport { FORMAT_INSTRUCTIONS } from \"./prompt.js\";\n\nconst FINAL_ANSWER_ACTION = \"Final Answer:\";\nconst FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE =\n \"Parsing LLM output produced both a final answer and a parse-able action:\";\n\n/**\n * Parses ReAct-style LLM calls that have a single tool input.\n *\n * Expects output to be in one of two formats.\n *\n * If the output signals that an action should be taken,\n * should be in the below format. This will result in an AgentAction\n * being returned.\n *\n * ```\n * Thought: agent thought here\n * Action: search\n * Action Input: what is the temperature in SF?\n * ```\n *\n * If the output signals that a final answer should be given,\n * should be in the below format. This will result in an AgentFinish\n * being returned.\n *\n * ```\n * Thought: agent thought here\n * Final Answer: The temperature is 100 degrees\n * ```\n * @example\n * ```typescript\n *\n * const runnableAgent = RunnableSequence.from([\n * ...rest of runnable\n * new ReActSingleInputOutputParser({ toolNames: [\"SerpAPI\", \"Calculator\"] }),\n * ]);\n * const agent = AgentExecutor.fromAgentAndTools({\n * agent: runnableAgent,\n * tools: [new SerpAPI(), new Calculator()],\n * });\n * const result = await agent.invoke({\n * input: \"whats the weather in pomfret?\",\n * });\n * ```\n */\nexport class ReActSingleInputOutputParser extends AgentActionOutputParser {\n lc_namespace = [\"langchain\", \"agents\", \"react\"];\n\n private toolNames: string[];\n\n constructor(fields: { toolNames: string[] }) {\n super(...arguments);\n this.toolNames = fields.toolNames;\n }\n\n /**\n * Parses the given text into an AgentAction or AgentFinish object. If an\n * output fixing parser is defined, uses it to parse the text.\n * @param text Text to parse.\n * @returns Promise that resolves to an AgentAction or AgentFinish object.\n */\n async parse(text: string): Promise<AgentAction | AgentFinish> {\n const includesAnswer = text.includes(FINAL_ANSWER_ACTION);\n const regex =\n /Action\\s*\\d*\\s*:[\\s]*(.*?)[\\s]*Action\\s*\\d*\\s*Input\\s*\\d*\\s*:[\\s]*(.*)/;\n const actionMatch = text.match(regex);\n if (actionMatch) {\n if (includesAnswer) {\n throw new OutputParserException(\n `${FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE}: ${text}`\n );\n }\n\n const action = actionMatch[1];\n const actionInput = actionMatch[2];\n const toolInput = actionInput.trim().replace(/^\"|\"$/g, \"\");\n\n return {\n tool: action,\n toolInput,\n log: text,\n };\n }\n\n if (includesAnswer) {\n const finalAnswerText = text.split(FINAL_ANSWER_ACTION)[1].trim();\n return {\n returnValues: {\n output: finalAnswerText,\n },\n log: text,\n };\n }\n\n throw new OutputParserException(`Could not parse LLM output: ${text}`);\n }\n\n /**\n * Returns the format instructions as a string. If the 'raw' option is\n * true, returns the raw FORMAT_INSTRUCTIONS.\n * @param options Options for getting the format instructions.\n * @returns Format instructions as a string.\n */\n getFormatInstructions(): string {\n return renderTemplate(FORMAT_INSTRUCTIONS, \"f-string\", {\n tool_names: this.toolNames.join(\", \"),\n });\n }\n}\n"],"mappings":";;;;;;;AAMA,MAAM,sBAAsB;AAC5B,MAAM,iDACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCF,IAAa,+BAAb,cAAkD,wBAAwB;CACxE,eAAe;EAAC;EAAa;EAAU;EAAQ;CAE/C;CAEA,YAAY,QAAiC;AAC3C,QAAM,GAAG,UAAU;AACnB,OAAK,YAAY,OAAO;;;;;;;;CAS1B,MAAM,MAAM,MAAkD;EAC5D,MAAM,iBAAiB,KAAK,SAAS,oBAAoB;EAGzD,MAAM,cAAc,KAAK,
|
|
1
|
+
{"version":3,"file":"output_parser.js","names":[],"sources":["../../../src/agents/react/output_parser.ts"],"sourcesContent":["import { AgentAction, AgentFinish } from \"@langchain/core/agents\";\nimport { renderTemplate } from \"@langchain/core/prompts\";\nimport { OutputParserException } from \"@langchain/core/output_parsers\";\nimport { AgentActionOutputParser } from \"../types.js\";\nimport { FORMAT_INSTRUCTIONS } from \"./prompt.js\";\n\nconst FINAL_ANSWER_ACTION = \"Final Answer:\";\nconst FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE =\n \"Parsing LLM output produced both a final answer and a parse-able action:\";\n\n/**\n * Parses ReAct-style LLM calls that have a single tool input.\n *\n * Expects output to be in one of two formats.\n *\n * If the output signals that an action should be taken,\n * should be in the below format. This will result in an AgentAction\n * being returned.\n *\n * ```\n * Thought: agent thought here\n * Action: search\n * Action Input: what is the temperature in SF?\n * ```\n *\n * If the output signals that a final answer should be given,\n * should be in the below format. This will result in an AgentFinish\n * being returned.\n *\n * ```\n * Thought: agent thought here\n * Final Answer: The temperature is 100 degrees\n * ```\n * @example\n * ```typescript\n *\n * const runnableAgent = RunnableSequence.from([\n * ...rest of runnable\n * new ReActSingleInputOutputParser({ toolNames: [\"SerpAPI\", \"Calculator\"] }),\n * ]);\n * const agent = AgentExecutor.fromAgentAndTools({\n * agent: runnableAgent,\n * tools: [new SerpAPI(), new Calculator()],\n * });\n * const result = await agent.invoke({\n * input: \"whats the weather in pomfret?\",\n * });\n * ```\n */\nexport class ReActSingleInputOutputParser extends AgentActionOutputParser {\n lc_namespace = [\"langchain\", \"agents\", \"react\"];\n\n private toolNames: string[];\n\n constructor(fields: { toolNames: string[] }) {\n super(...arguments);\n this.toolNames = fields.toolNames;\n }\n\n /**\n * Parses the given text into an AgentAction or AgentFinish object. If an\n * output fixing parser is defined, uses it to parse the text.\n * @param text Text to parse.\n * @returns Promise that resolves to an AgentAction or AgentFinish object.\n */\n async parse(text: string): Promise<AgentAction | AgentFinish> {\n const includesAnswer = text.includes(FINAL_ANSWER_ACTION);\n const regex =\n /Action\\s*\\d*\\s*:[\\s]*(.*?)[\\s]*Action\\s*\\d*\\s*Input\\s*\\d*\\s*:[\\s]*(.*)/;\n const actionMatch = text.match(regex);\n if (actionMatch) {\n if (includesAnswer) {\n throw new OutputParserException(\n `${FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE}: ${text}`\n );\n }\n\n const action = actionMatch[1];\n const actionInput = actionMatch[2];\n const toolInput = actionInput.trim().replace(/^\"|\"$/g, \"\");\n\n return {\n tool: action,\n toolInput,\n log: text,\n };\n }\n\n if (includesAnswer) {\n const finalAnswerText = text.split(FINAL_ANSWER_ACTION)[1].trim();\n return {\n returnValues: {\n output: finalAnswerText,\n },\n log: text,\n };\n }\n\n throw new OutputParserException(`Could not parse LLM output: ${text}`);\n }\n\n /**\n * Returns the format instructions as a string. If the 'raw' option is\n * true, returns the raw FORMAT_INSTRUCTIONS.\n * @param options Options for getting the format instructions.\n * @returns Format instructions as a string.\n */\n getFormatInstructions(): string {\n return renderTemplate(FORMAT_INSTRUCTIONS, \"f-string\", {\n tool_names: this.toolNames.join(\", \"),\n });\n }\n}\n"],"mappings":";;;;;;;AAMA,MAAM,sBAAsB;AAC5B,MAAM,iDACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCF,IAAa,+BAAb,cAAkD,wBAAwB;CACxE,eAAe;EAAC;EAAa;EAAU;EAAQ;CAE/C;CAEA,YAAY,QAAiC;AAC3C,QAAM,GAAG,UAAU;AACnB,OAAK,YAAY,OAAO;;;;;;;;CAS1B,MAAM,MAAM,MAAkD;EAC5D,MAAM,iBAAiB,KAAK,SAAS,oBAAoB;EAGzD,MAAM,cAAc,KAAK,MAAM,yEAAM;AACrC,MAAI,aAAa;AACf,OAAI,eACF,OAAM,IAAI,sBACR,GAAG,+CAA+C,IAAI,OACvD;AAOH,UAAO;IACL,MALa,YAAY;IAMzB,WALkB,YAAY,GACF,MAAM,CAAC,QAAQ,UAAU,GAI5C;IACT,KAAK;IACN;;AAGH,MAAI,eAEF,QAAO;GACL,cAAc,EACZ,QAHoB,KAAK,MAAM,oBAAoB,CAAC,GAAG,MAGhC,EACxB;GACD,KAAK;GACN;AAGH,QAAM,IAAI,sBAAsB,+BAA+B,OAAO;;;;;;;;CASxE,wBAAgC;AAC9B,SAAO,eAAe,qBAAqB,YAAY,EACrD,YAAY,KAAK,UAAU,KAAK,KAAK,EACtC,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["Agent","StructuredChatOutputParserWithRetries","PREFIX","SUFFIX","SystemMessagePromptTemplate","PromptTemplate","FORMAT_INSTRUCTIONS","HumanMessagePromptTemplate","ChatPromptTemplate","LLMChain","isOpenAITool","isStructuredTool","renderTextDescriptionAndArgs","AgentRunnableSequence","RunnablePassthrough","formatLogToString"],"sources":["../../../src/agents/structured_chat/index.ts"],"sourcesContent":["import type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport {\n isOpenAITool,\n type BaseLanguageModel,\n type BaseLanguageModelInterface,\n type ToolDefinition,\n} from \"@langchain/core/language_models/base\";\nimport { RunnablePassthrough } from \"@langchain/core/runnables\";\nimport type { BasePromptTemplate } from \"@langchain/core/prompts\";\nimport {\n BaseMessagePromptTemplate,\n ChatPromptTemplate,\n HumanMessagePromptTemplate,\n SystemMessagePromptTemplate,\n PromptTemplate,\n} from \"@langchain/core/prompts\";\nimport { AgentStep } from \"@langchain/core/agents\";\nimport { isStructuredTool } from \"@langchain/core/utils/function_calling\";\nimport { isInteropZodSchema } from \"@langchain/core/utils/types\";\nimport {\n type JsonSchema7Type,\n toJsonSchema,\n} from \"@langchain/core/utils/json_schema\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\nimport { Optional } from \"../../types/type-utils.js\";\nimport {\n Agent,\n AgentArgs,\n AgentRunnableSequence,\n OutputParserArgs,\n} from \"../agent.js\";\nimport { AgentInput } from \"../types.js\";\nimport { StructuredChatOutputParserWithRetries } from \"./outputParser.js\";\nimport { FORMAT_INSTRUCTIONS, PREFIX, SUFFIX } from \"./prompt.js\";\nimport { renderTextDescriptionAndArgs } from \"../../tools/render.js\";\nimport { formatLogToString } from \"../format_scratchpad/log.js\";\n\n/**\n * Interface for arguments used to create a prompt for a\n * StructuredChatAgent.\n */\nexport interface StructuredChatCreatePromptArgs {\n /** String to put after the list of tools. */\n suffix?: string;\n /** String to put before the list of tools. */\n prefix?: string;\n /** String to use directly as the human message template. */\n humanMessageTemplate?: string;\n /** List of input variables the final prompt will expect. */\n inputVariables?: string[];\n /** List of historical prompts from memory. */\n memoryPrompts?: BaseMessagePromptTemplate[];\n}\n\n/**\n * Type for input data for creating a StructuredChatAgent, with the\n * 'outputParser' property made optional.\n */\nexport type StructuredChatAgentInput = Optional<AgentInput, \"outputParser\">;\n\n/**\n * Agent that interoperates with Structured Tools using React logic.\n * @augments Agent\n */\nexport class StructuredChatAgent extends Agent {\n static lc_name() {\n return \"StructuredChatAgent\";\n }\n\n lc_namespace = [\"langchain\", \"agents\", \"structured_chat\"];\n\n constructor(input: StructuredChatAgentInput) {\n const outputParser =\n input?.outputParser ?? StructuredChatAgent.getDefaultOutputParser();\n super({ ...input, outputParser });\n }\n\n _agentType() {\n return \"structured-chat-zero-shot-react-description\" as const;\n }\n\n observationPrefix() {\n return \"Observation: \";\n }\n\n llmPrefix() {\n return \"Thought:\";\n }\n\n _stop(): string[] {\n return [\"Observation:\"];\n }\n\n /**\n * Validates that all provided tools have a description. Throws an error\n * if any tool lacks a description.\n * @param tools Array of StructuredTool instances to validate.\n */\n static validateTools(tools: StructuredToolInterface[]) {\n const descriptionlessTool = tools.find((tool) => !tool.description);\n if (descriptionlessTool) {\n const msg =\n `Got a tool ${descriptionlessTool.name} without a description.` +\n ` This agent requires descriptions for all tools.`;\n throw new Error(msg);\n }\n }\n\n /**\n * Returns a default output parser for the StructuredChatAgent. If an LLM\n * is provided, it creates an output parser with retry logic from the LLM.\n * @param fields Optional fields to customize the output parser. Can include an LLM and a list of tool names.\n * @returns An instance of StructuredChatOutputParserWithRetries.\n */\n static getDefaultOutputParser(\n fields?: OutputParserArgs & {\n toolNames: string[];\n }\n ) {\n if (fields?.llm) {\n return StructuredChatOutputParserWithRetries.fromLLM(fields.llm, {\n toolNames: fields.toolNames,\n });\n }\n return new StructuredChatOutputParserWithRetries({\n toolNames: fields?.toolNames,\n });\n }\n\n /**\n * Constructs the agent's scratchpad from a list of steps. If the agent's\n * scratchpad is not empty, it prepends a message indicating that the\n * agent has not seen any previous work.\n * @param steps Array of AgentStep instances to construct the scratchpad from.\n * @returns A Promise that resolves to a string representing the agent's scratchpad.\n */\n async constructScratchPad(steps: AgentStep[]): Promise<string> {\n const agentScratchpad = await super.constructScratchPad(steps);\n if (agentScratchpad) {\n return `This was your previous work (but I haven't seen any of it! I only see what you return as final answer):\\n${agentScratchpad}`;\n }\n return agentScratchpad;\n }\n\n /**\n * Creates a string representation of the schemas of the provided tools.\n * @param tools Array of StructuredTool instances to create the schemas string from.\n * @returns A string representing the schemas of the provided tools.\n */\n static createToolSchemasString(tools: StructuredToolInterface[]) {\n return tools\n .map((tool) => {\n const jsonSchema = (\n isInteropZodSchema(tool.schema)\n ? toJsonSchema(tool.schema)\n : tool.schema\n ) as { properties?: Record<string, JsonSchema7Type> } | undefined;\n return `${tool.name}: ${tool.description}, args: ${JSON.stringify(\n jsonSchema?.properties\n )}`;\n })\n .join(\"\\n\");\n }\n\n /**\n * Create prompt in the style of the agent.\n *\n * @param tools - List of tools the agent will have access to, used to format the prompt.\n * @param args - Arguments to create the prompt with.\n * @param args.suffix - String to put after the list of tools.\n * @param args.prefix - String to put before the list of tools.\n * @param args.inputVariables List of input variables the final prompt will expect.\n * @param args.memoryPrompts List of historical prompts from memory.\n */\n static createPrompt(\n tools: StructuredToolInterface[],\n args?: StructuredChatCreatePromptArgs\n ) {\n const {\n prefix = PREFIX,\n suffix = SUFFIX,\n inputVariables = [\"input\", \"agent_scratchpad\"],\n humanMessageTemplate = \"{input}\\n\\n{agent_scratchpad}\",\n memoryPrompts = [],\n } = args ?? {};\n const template = [prefix, FORMAT_INSTRUCTIONS, suffix].join(\"\\n\\n\");\n const messages = [\n new SystemMessagePromptTemplate(\n new PromptTemplate({\n template,\n inputVariables,\n partialVariables: {\n tool_schemas: StructuredChatAgent.createToolSchemasString(tools),\n tool_names: tools.map((tool) => tool.name).join(\", \"),\n },\n })\n ),\n ...memoryPrompts,\n new HumanMessagePromptTemplate(\n new PromptTemplate({\n template: humanMessageTemplate,\n inputVariables,\n })\n ),\n ];\n return ChatPromptTemplate.fromMessages(messages);\n }\n\n /**\n * Creates a StructuredChatAgent from an LLM and a list of tools.\n * Validates the tools, creates a prompt, and sets up an LLM chain for the\n * agent.\n * @param llm BaseLanguageModel instance to create the agent from.\n * @param tools Array of StructuredTool instances to create the agent from.\n * @param args Optional arguments to customize the creation of the agent. Can include arguments for creating the prompt and AgentArgs.\n * @returns A new instance of StructuredChatAgent.\n */\n static fromLLMAndTools(\n llm: BaseLanguageModelInterface,\n tools: StructuredToolInterface[],\n args?: StructuredChatCreatePromptArgs & AgentArgs\n ) {\n StructuredChatAgent.validateTools(tools);\n const prompt = StructuredChatAgent.createPrompt(tools, args);\n const outputParser =\n args?.outputParser ??\n StructuredChatAgent.getDefaultOutputParser({\n llm,\n toolNames: tools.map((tool) => tool.name),\n });\n const chain = new LLMChain({\n prompt,\n llm,\n callbacks: args?.callbacks,\n });\n\n return new StructuredChatAgent({\n llmChain: chain,\n outputParser,\n allowedTools: tools.map((t) => t.name),\n });\n }\n}\n\n/**\n * Params used by the createStructuredChatAgent function.\n */\nexport type CreateStructuredChatAgentParams = {\n /** LLM to use as the agent. */\n llm: BaseLanguageModelInterface;\n /** Tools this agent has access to. */\n tools: (StructuredToolInterface | ToolDefinition)[];\n /**\n * The prompt to use. Must have input keys for\n * `tools`, `tool_names`, and `agent_scratchpad`.\n */\n prompt: BasePromptTemplate;\n /**\n * Whether to invoke the underlying model in streaming mode,\n * allowing streaming of intermediate steps. Defaults to true.\n */\n streamRunnable?: boolean;\n};\n\n/**\n * Create an agent aimed at supporting tools with multiple inputs.\n * @param params Params required to create the agent. Includes an LLM, tools, and prompt.\n * @returns A runnable sequence representing an agent. It takes as input all the same input\n * variables as the prompt passed in does. It returns as output either an\n * AgentAction or AgentFinish.\n *\n * @example\n * ```typescript\n * import { AgentExecutor, createStructuredChatAgent } from \"langchain/agents\";\n * import { pull } from \"langchain/hub\";\n * import type { ChatPromptTemplate } from \"@langchain/core/prompts\";\n * import { AIMessage, HumanMessage } from \"@langchain/core/messages\";\n *\n * import { ChatOpenAI } from \"@langchain/openai\";\n *\n * // Define the tools the agent will have access to.\n * const tools = [...];\n *\n * // Get the prompt to use - you can modify this!\n * // If you want to see the prompt in full, you can at:\n * // https://smith.langchain.com/hub/hwchase17/structured-chat-agent\n * const prompt = await pull<ChatPromptTemplate>(\n * \"hwchase17/structured-chat-agent\"\n * );\n *\n * const llm = new ChatOpenAI({\n * temperature: 0,\n * model: \"gpt-3.5-turbo-1106\",\n * });\n *\n * const agent = await createStructuredChatAgent({\n * llm,\n * tools,\n * prompt,\n * });\n *\n * const agentExecutor = new AgentExecutor({\n * agent,\n * tools,\n * });\n *\n * const result = await agentExecutor.invoke({\n * input: \"what is LangChain?\",\n * });\n *\n * // With chat history\n * const result2 = await agentExecutor.invoke({\n * input: \"what's my name?\",\n * chat_history: [\n * new HumanMessage(\"hi! my name is cob\"),\n * new AIMessage(\"Hello Cob! How can I assist you today?\"),\n * ],\n * });\n * ```\n */\nexport async function createStructuredChatAgent({\n llm,\n tools,\n prompt,\n streamRunnable,\n}: CreateStructuredChatAgentParams) {\n const missingVariables = [\"tools\", \"tool_names\", \"agent_scratchpad\"].filter(\n (v) => !prompt.inputVariables.includes(v)\n );\n if (missingVariables.length > 0) {\n throw new Error(\n `Provided prompt is missing required input variables: ${JSON.stringify(\n missingVariables\n )}`\n );\n }\n let toolNames: string[] = [];\n if (tools.every(isOpenAITool)) {\n toolNames = tools.map((tool) => tool.function.name);\n } else if (tools.every(isStructuredTool)) {\n toolNames = tools.map((tool) => tool.name);\n } else {\n throw new Error(\n \"All tools must be either OpenAI or Structured tools, not a mix.\"\n );\n }\n const partialedPrompt = await prompt.partial({\n tools: renderTextDescriptionAndArgs(tools),\n tool_names: toolNames.join(\", \"),\n });\n // TODO: Add .bind to core runnable interface.\n const llmWithStop = (llm as BaseLanguageModel).withConfig({\n stop: [\"Observation\"],\n });\n const agent = AgentRunnableSequence.fromRunnables(\n [\n RunnablePassthrough.assign({\n agent_scratchpad: (input: { steps: AgentStep[] }) =>\n formatLogToString(input.steps),\n }),\n partialedPrompt,\n llmWithStop,\n StructuredChatOutputParserWithRetries.fromLLM(llm, {\n toolNames,\n }),\n ],\n {\n name: \"StructuredChatAgent\",\n streamRunnable,\n singleAction: true,\n }\n );\n return agent;\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["Agent","StructuredChatOutputParserWithRetries","PREFIX","SUFFIX","SystemMessagePromptTemplate","PromptTemplate","FORMAT_INSTRUCTIONS","HumanMessagePromptTemplate","ChatPromptTemplate","LLMChain","isOpenAITool","isStructuredTool","renderTextDescriptionAndArgs","AgentRunnableSequence","RunnablePassthrough","formatLogToString"],"sources":["../../../src/agents/structured_chat/index.ts"],"sourcesContent":["import type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport {\n isOpenAITool,\n type BaseLanguageModel,\n type BaseLanguageModelInterface,\n type ToolDefinition,\n} from \"@langchain/core/language_models/base\";\nimport { RunnablePassthrough } from \"@langchain/core/runnables\";\nimport type { BasePromptTemplate } from \"@langchain/core/prompts\";\nimport {\n BaseMessagePromptTemplate,\n ChatPromptTemplate,\n HumanMessagePromptTemplate,\n SystemMessagePromptTemplate,\n PromptTemplate,\n} from \"@langchain/core/prompts\";\nimport { AgentStep } from \"@langchain/core/agents\";\nimport { isStructuredTool } from \"@langchain/core/utils/function_calling\";\nimport { isInteropZodSchema } from \"@langchain/core/utils/types\";\nimport {\n type JsonSchema7Type,\n toJsonSchema,\n} from \"@langchain/core/utils/json_schema\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\nimport { Optional } from \"../../types/type-utils.js\";\nimport {\n Agent,\n AgentArgs,\n AgentRunnableSequence,\n OutputParserArgs,\n} from \"../agent.js\";\nimport { AgentInput } from \"../types.js\";\nimport { StructuredChatOutputParserWithRetries } from \"./outputParser.js\";\nimport { FORMAT_INSTRUCTIONS, PREFIX, SUFFIX } from \"./prompt.js\";\nimport { renderTextDescriptionAndArgs } from \"../../tools/render.js\";\nimport { formatLogToString } from \"../format_scratchpad/log.js\";\n\n/**\n * Interface for arguments used to create a prompt for a\n * StructuredChatAgent.\n */\nexport interface StructuredChatCreatePromptArgs {\n /** String to put after the list of tools. */\n suffix?: string;\n /** String to put before the list of tools. */\n prefix?: string;\n /** String to use directly as the human message template. */\n humanMessageTemplate?: string;\n /** List of input variables the final prompt will expect. */\n inputVariables?: string[];\n /** List of historical prompts from memory. */\n memoryPrompts?: BaseMessagePromptTemplate[];\n}\n\n/**\n * Type for input data for creating a StructuredChatAgent, with the\n * 'outputParser' property made optional.\n */\nexport type StructuredChatAgentInput = Optional<AgentInput, \"outputParser\">;\n\n/**\n * Agent that interoperates with Structured Tools using React logic.\n * @augments Agent\n */\nexport class StructuredChatAgent extends Agent {\n static lc_name() {\n return \"StructuredChatAgent\";\n }\n\n lc_namespace = [\"langchain\", \"agents\", \"structured_chat\"];\n\n constructor(input: StructuredChatAgentInput) {\n const outputParser =\n input?.outputParser ?? StructuredChatAgent.getDefaultOutputParser();\n super({ ...input, outputParser });\n }\n\n _agentType() {\n return \"structured-chat-zero-shot-react-description\" as const;\n }\n\n observationPrefix() {\n return \"Observation: \";\n }\n\n llmPrefix() {\n return \"Thought:\";\n }\n\n _stop(): string[] {\n return [\"Observation:\"];\n }\n\n /**\n * Validates that all provided tools have a description. Throws an error\n * if any tool lacks a description.\n * @param tools Array of StructuredTool instances to validate.\n */\n static validateTools(tools: StructuredToolInterface[]) {\n const descriptionlessTool = tools.find((tool) => !tool.description);\n if (descriptionlessTool) {\n const msg =\n `Got a tool ${descriptionlessTool.name} without a description.` +\n ` This agent requires descriptions for all tools.`;\n throw new Error(msg);\n }\n }\n\n /**\n * Returns a default output parser for the StructuredChatAgent. If an LLM\n * is provided, it creates an output parser with retry logic from the LLM.\n * @param fields Optional fields to customize the output parser. Can include an LLM and a list of tool names.\n * @returns An instance of StructuredChatOutputParserWithRetries.\n */\n static getDefaultOutputParser(\n fields?: OutputParserArgs & {\n toolNames: string[];\n }\n ) {\n if (fields?.llm) {\n return StructuredChatOutputParserWithRetries.fromLLM(fields.llm, {\n toolNames: fields.toolNames,\n });\n }\n return new StructuredChatOutputParserWithRetries({\n toolNames: fields?.toolNames,\n });\n }\n\n /**\n * Constructs the agent's scratchpad from a list of steps. If the agent's\n * scratchpad is not empty, it prepends a message indicating that the\n * agent has not seen any previous work.\n * @param steps Array of AgentStep instances to construct the scratchpad from.\n * @returns A Promise that resolves to a string representing the agent's scratchpad.\n */\n async constructScratchPad(steps: AgentStep[]): Promise<string> {\n const agentScratchpad = await super.constructScratchPad(steps);\n if (agentScratchpad) {\n return `This was your previous work (but I haven't seen any of it! I only see what you return as final answer):\\n${agentScratchpad}`;\n }\n return agentScratchpad;\n }\n\n /**\n * Creates a string representation of the schemas of the provided tools.\n * @param tools Array of StructuredTool instances to create the schemas string from.\n * @returns A string representing the schemas of the provided tools.\n */\n static createToolSchemasString(tools: StructuredToolInterface[]) {\n return tools\n .map((tool) => {\n const jsonSchema = (\n isInteropZodSchema(tool.schema)\n ? toJsonSchema(tool.schema)\n : tool.schema\n ) as { properties?: Record<string, JsonSchema7Type> } | undefined;\n return `${tool.name}: ${tool.description}, args: ${JSON.stringify(\n jsonSchema?.properties\n )}`;\n })\n .join(\"\\n\");\n }\n\n /**\n * Create prompt in the style of the agent.\n *\n * @param tools - List of tools the agent will have access to, used to format the prompt.\n * @param args - Arguments to create the prompt with.\n * @param args.suffix - String to put after the list of tools.\n * @param args.prefix - String to put before the list of tools.\n * @param args.inputVariables List of input variables the final prompt will expect.\n * @param args.memoryPrompts List of historical prompts from memory.\n */\n static createPrompt(\n tools: StructuredToolInterface[],\n args?: StructuredChatCreatePromptArgs\n ) {\n const {\n prefix = PREFIX,\n suffix = SUFFIX,\n inputVariables = [\"input\", \"agent_scratchpad\"],\n humanMessageTemplate = \"{input}\\n\\n{agent_scratchpad}\",\n memoryPrompts = [],\n } = args ?? {};\n const template = [prefix, FORMAT_INSTRUCTIONS, suffix].join(\"\\n\\n\");\n const messages = [\n new SystemMessagePromptTemplate(\n new PromptTemplate({\n template,\n inputVariables,\n partialVariables: {\n tool_schemas: StructuredChatAgent.createToolSchemasString(tools),\n tool_names: tools.map((tool) => tool.name).join(\", \"),\n },\n })\n ),\n ...memoryPrompts,\n new HumanMessagePromptTemplate(\n new PromptTemplate({\n template: humanMessageTemplate,\n inputVariables,\n })\n ),\n ];\n return ChatPromptTemplate.fromMessages(messages);\n }\n\n /**\n * Creates a StructuredChatAgent from an LLM and a list of tools.\n * Validates the tools, creates a prompt, and sets up an LLM chain for the\n * agent.\n * @param llm BaseLanguageModel instance to create the agent from.\n * @param tools Array of StructuredTool instances to create the agent from.\n * @param args Optional arguments to customize the creation of the agent. Can include arguments for creating the prompt and AgentArgs.\n * @returns A new instance of StructuredChatAgent.\n */\n static fromLLMAndTools(\n llm: BaseLanguageModelInterface,\n tools: StructuredToolInterface[],\n args?: StructuredChatCreatePromptArgs & AgentArgs\n ) {\n StructuredChatAgent.validateTools(tools);\n const prompt = StructuredChatAgent.createPrompt(tools, args);\n const outputParser =\n args?.outputParser ??\n StructuredChatAgent.getDefaultOutputParser({\n llm,\n toolNames: tools.map((tool) => tool.name),\n });\n const chain = new LLMChain({\n prompt,\n llm,\n callbacks: args?.callbacks,\n });\n\n return new StructuredChatAgent({\n llmChain: chain,\n outputParser,\n allowedTools: tools.map((t) => t.name),\n });\n }\n}\n\n/**\n * Params used by the createStructuredChatAgent function.\n */\nexport type CreateStructuredChatAgentParams = {\n /** LLM to use as the agent. */\n llm: BaseLanguageModelInterface;\n /** Tools this agent has access to. */\n tools: (StructuredToolInterface | ToolDefinition)[];\n /**\n * The prompt to use. Must have input keys for\n * `tools`, `tool_names`, and `agent_scratchpad`.\n */\n prompt: BasePromptTemplate;\n /**\n * Whether to invoke the underlying model in streaming mode,\n * allowing streaming of intermediate steps. Defaults to true.\n */\n streamRunnable?: boolean;\n};\n\n/**\n * Create an agent aimed at supporting tools with multiple inputs.\n * @param params Params required to create the agent. Includes an LLM, tools, and prompt.\n * @returns A runnable sequence representing an agent. It takes as input all the same input\n * variables as the prompt passed in does. It returns as output either an\n * AgentAction or AgentFinish.\n *\n * @example\n * ```typescript\n * import { AgentExecutor, createStructuredChatAgent } from \"langchain/agents\";\n * import { pull } from \"langchain/hub\";\n * import type { ChatPromptTemplate } from \"@langchain/core/prompts\";\n * import { AIMessage, HumanMessage } from \"@langchain/core/messages\";\n *\n * import { ChatOpenAI } from \"@langchain/openai\";\n *\n * // Define the tools the agent will have access to.\n * const tools = [...];\n *\n * // Get the prompt to use - you can modify this!\n * // If you want to see the prompt in full, you can at:\n * // https://smith.langchain.com/hub/hwchase17/structured-chat-agent\n * const prompt = await pull<ChatPromptTemplate>(\n * \"hwchase17/structured-chat-agent\"\n * );\n *\n * const llm = new ChatOpenAI({\n * temperature: 0,\n * model: \"gpt-3.5-turbo-1106\",\n * });\n *\n * const agent = await createStructuredChatAgent({\n * llm,\n * tools,\n * prompt,\n * });\n *\n * const agentExecutor = new AgentExecutor({\n * agent,\n * tools,\n * });\n *\n * const result = await agentExecutor.invoke({\n * input: \"what is LangChain?\",\n * });\n *\n * // With chat history\n * const result2 = await agentExecutor.invoke({\n * input: \"what's my name?\",\n * chat_history: [\n * new HumanMessage(\"hi! my name is cob\"),\n * new AIMessage(\"Hello Cob! How can I assist you today?\"),\n * ],\n * });\n * ```\n */\nexport async function createStructuredChatAgent({\n llm,\n tools,\n prompt,\n streamRunnable,\n}: CreateStructuredChatAgentParams) {\n const missingVariables = [\"tools\", \"tool_names\", \"agent_scratchpad\"].filter(\n (v) => !prompt.inputVariables.includes(v)\n );\n if (missingVariables.length > 0) {\n throw new Error(\n `Provided prompt is missing required input variables: ${JSON.stringify(\n missingVariables\n )}`\n );\n }\n let toolNames: string[] = [];\n if (tools.every(isOpenAITool)) {\n toolNames = tools.map((tool) => tool.function.name);\n } else if (tools.every(isStructuredTool)) {\n toolNames = tools.map((tool) => tool.name);\n } else {\n throw new Error(\n \"All tools must be either OpenAI or Structured tools, not a mix.\"\n );\n }\n const partialedPrompt = await prompt.partial({\n tools: renderTextDescriptionAndArgs(tools),\n tool_names: toolNames.join(\", \"),\n });\n // TODO: Add .bind to core runnable interface.\n const llmWithStop = (llm as BaseLanguageModel).withConfig({\n stop: [\"Observation\"],\n });\n const agent = AgentRunnableSequence.fromRunnables(\n [\n RunnablePassthrough.assign({\n agent_scratchpad: (input: { steps: AgentStep[] }) =>\n formatLogToString(input.steps),\n }),\n partialedPrompt,\n llmWithStop,\n StructuredChatOutputParserWithRetries.fromLLM(llm, {\n toolNames,\n }),\n ],\n {\n name: \"StructuredChatAgent\",\n streamRunnable,\n singleAction: true,\n }\n );\n return agent;\n}\n"],"mappings":"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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/agents/structured_chat/index.ts"],"sourcesContent":["import type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport {\n isOpenAITool,\n type BaseLanguageModel,\n type BaseLanguageModelInterface,\n type ToolDefinition,\n} from \"@langchain/core/language_models/base\";\nimport { RunnablePassthrough } from \"@langchain/core/runnables\";\nimport type { BasePromptTemplate } from \"@langchain/core/prompts\";\nimport {\n BaseMessagePromptTemplate,\n ChatPromptTemplate,\n HumanMessagePromptTemplate,\n SystemMessagePromptTemplate,\n PromptTemplate,\n} from \"@langchain/core/prompts\";\nimport { AgentStep } from \"@langchain/core/agents\";\nimport { isStructuredTool } from \"@langchain/core/utils/function_calling\";\nimport { isInteropZodSchema } from \"@langchain/core/utils/types\";\nimport {\n type JsonSchema7Type,\n toJsonSchema,\n} from \"@langchain/core/utils/json_schema\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\nimport { Optional } from \"../../types/type-utils.js\";\nimport {\n Agent,\n AgentArgs,\n AgentRunnableSequence,\n OutputParserArgs,\n} from \"../agent.js\";\nimport { AgentInput } from \"../types.js\";\nimport { StructuredChatOutputParserWithRetries } from \"./outputParser.js\";\nimport { FORMAT_INSTRUCTIONS, PREFIX, SUFFIX } from \"./prompt.js\";\nimport { renderTextDescriptionAndArgs } from \"../../tools/render.js\";\nimport { formatLogToString } from \"../format_scratchpad/log.js\";\n\n/**\n * Interface for arguments used to create a prompt for a\n * StructuredChatAgent.\n */\nexport interface StructuredChatCreatePromptArgs {\n /** String to put after the list of tools. */\n suffix?: string;\n /** String to put before the list of tools. */\n prefix?: string;\n /** String to use directly as the human message template. */\n humanMessageTemplate?: string;\n /** List of input variables the final prompt will expect. */\n inputVariables?: string[];\n /** List of historical prompts from memory. */\n memoryPrompts?: BaseMessagePromptTemplate[];\n}\n\n/**\n * Type for input data for creating a StructuredChatAgent, with the\n * 'outputParser' property made optional.\n */\nexport type StructuredChatAgentInput = Optional<AgentInput, \"outputParser\">;\n\n/**\n * Agent that interoperates with Structured Tools using React logic.\n * @augments Agent\n */\nexport class StructuredChatAgent extends Agent {\n static lc_name() {\n return \"StructuredChatAgent\";\n }\n\n lc_namespace = [\"langchain\", \"agents\", \"structured_chat\"];\n\n constructor(input: StructuredChatAgentInput) {\n const outputParser =\n input?.outputParser ?? StructuredChatAgent.getDefaultOutputParser();\n super({ ...input, outputParser });\n }\n\n _agentType() {\n return \"structured-chat-zero-shot-react-description\" as const;\n }\n\n observationPrefix() {\n return \"Observation: \";\n }\n\n llmPrefix() {\n return \"Thought:\";\n }\n\n _stop(): string[] {\n return [\"Observation:\"];\n }\n\n /**\n * Validates that all provided tools have a description. Throws an error\n * if any tool lacks a description.\n * @param tools Array of StructuredTool instances to validate.\n */\n static validateTools(tools: StructuredToolInterface[]) {\n const descriptionlessTool = tools.find((tool) => !tool.description);\n if (descriptionlessTool) {\n const msg =\n `Got a tool ${descriptionlessTool.name} without a description.` +\n ` This agent requires descriptions for all tools.`;\n throw new Error(msg);\n }\n }\n\n /**\n * Returns a default output parser for the StructuredChatAgent. If an LLM\n * is provided, it creates an output parser with retry logic from the LLM.\n * @param fields Optional fields to customize the output parser. Can include an LLM and a list of tool names.\n * @returns An instance of StructuredChatOutputParserWithRetries.\n */\n static getDefaultOutputParser(\n fields?: OutputParserArgs & {\n toolNames: string[];\n }\n ) {\n if (fields?.llm) {\n return StructuredChatOutputParserWithRetries.fromLLM(fields.llm, {\n toolNames: fields.toolNames,\n });\n }\n return new StructuredChatOutputParserWithRetries({\n toolNames: fields?.toolNames,\n });\n }\n\n /**\n * Constructs the agent's scratchpad from a list of steps. If the agent's\n * scratchpad is not empty, it prepends a message indicating that the\n * agent has not seen any previous work.\n * @param steps Array of AgentStep instances to construct the scratchpad from.\n * @returns A Promise that resolves to a string representing the agent's scratchpad.\n */\n async constructScratchPad(steps: AgentStep[]): Promise<string> {\n const agentScratchpad = await super.constructScratchPad(steps);\n if (agentScratchpad) {\n return `This was your previous work (but I haven't seen any of it! I only see what you return as final answer):\\n${agentScratchpad}`;\n }\n return agentScratchpad;\n }\n\n /**\n * Creates a string representation of the schemas of the provided tools.\n * @param tools Array of StructuredTool instances to create the schemas string from.\n * @returns A string representing the schemas of the provided tools.\n */\n static createToolSchemasString(tools: StructuredToolInterface[]) {\n return tools\n .map((tool) => {\n const jsonSchema = (\n isInteropZodSchema(tool.schema)\n ? toJsonSchema(tool.schema)\n : tool.schema\n ) as { properties?: Record<string, JsonSchema7Type> } | undefined;\n return `${tool.name}: ${tool.description}, args: ${JSON.stringify(\n jsonSchema?.properties\n )}`;\n })\n .join(\"\\n\");\n }\n\n /**\n * Create prompt in the style of the agent.\n *\n * @param tools - List of tools the agent will have access to, used to format the prompt.\n * @param args - Arguments to create the prompt with.\n * @param args.suffix - String to put after the list of tools.\n * @param args.prefix - String to put before the list of tools.\n * @param args.inputVariables List of input variables the final prompt will expect.\n * @param args.memoryPrompts List of historical prompts from memory.\n */\n static createPrompt(\n tools: StructuredToolInterface[],\n args?: StructuredChatCreatePromptArgs\n ) {\n const {\n prefix = PREFIX,\n suffix = SUFFIX,\n inputVariables = [\"input\", \"agent_scratchpad\"],\n humanMessageTemplate = \"{input}\\n\\n{agent_scratchpad}\",\n memoryPrompts = [],\n } = args ?? {};\n const template = [prefix, FORMAT_INSTRUCTIONS, suffix].join(\"\\n\\n\");\n const messages = [\n new SystemMessagePromptTemplate(\n new PromptTemplate({\n template,\n inputVariables,\n partialVariables: {\n tool_schemas: StructuredChatAgent.createToolSchemasString(tools),\n tool_names: tools.map((tool) => tool.name).join(\", \"),\n },\n })\n ),\n ...memoryPrompts,\n new HumanMessagePromptTemplate(\n new PromptTemplate({\n template: humanMessageTemplate,\n inputVariables,\n })\n ),\n ];\n return ChatPromptTemplate.fromMessages(messages);\n }\n\n /**\n * Creates a StructuredChatAgent from an LLM and a list of tools.\n * Validates the tools, creates a prompt, and sets up an LLM chain for the\n * agent.\n * @param llm BaseLanguageModel instance to create the agent from.\n * @param tools Array of StructuredTool instances to create the agent from.\n * @param args Optional arguments to customize the creation of the agent. Can include arguments for creating the prompt and AgentArgs.\n * @returns A new instance of StructuredChatAgent.\n */\n static fromLLMAndTools(\n llm: BaseLanguageModelInterface,\n tools: StructuredToolInterface[],\n args?: StructuredChatCreatePromptArgs & AgentArgs\n ) {\n StructuredChatAgent.validateTools(tools);\n const prompt = StructuredChatAgent.createPrompt(tools, args);\n const outputParser =\n args?.outputParser ??\n StructuredChatAgent.getDefaultOutputParser({\n llm,\n toolNames: tools.map((tool) => tool.name),\n });\n const chain = new LLMChain({\n prompt,\n llm,\n callbacks: args?.callbacks,\n });\n\n return new StructuredChatAgent({\n llmChain: chain,\n outputParser,\n allowedTools: tools.map((t) => t.name),\n });\n }\n}\n\n/**\n * Params used by the createStructuredChatAgent function.\n */\nexport type CreateStructuredChatAgentParams = {\n /** LLM to use as the agent. */\n llm: BaseLanguageModelInterface;\n /** Tools this agent has access to. */\n tools: (StructuredToolInterface | ToolDefinition)[];\n /**\n * The prompt to use. Must have input keys for\n * `tools`, `tool_names`, and `agent_scratchpad`.\n */\n prompt: BasePromptTemplate;\n /**\n * Whether to invoke the underlying model in streaming mode,\n * allowing streaming of intermediate steps. Defaults to true.\n */\n streamRunnable?: boolean;\n};\n\n/**\n * Create an agent aimed at supporting tools with multiple inputs.\n * @param params Params required to create the agent. Includes an LLM, tools, and prompt.\n * @returns A runnable sequence representing an agent. It takes as input all the same input\n * variables as the prompt passed in does. It returns as output either an\n * AgentAction or AgentFinish.\n *\n * @example\n * ```typescript\n * import { AgentExecutor, createStructuredChatAgent } from \"langchain/agents\";\n * import { pull } from \"langchain/hub\";\n * import type { ChatPromptTemplate } from \"@langchain/core/prompts\";\n * import { AIMessage, HumanMessage } from \"@langchain/core/messages\";\n *\n * import { ChatOpenAI } from \"@langchain/openai\";\n *\n * // Define the tools the agent will have access to.\n * const tools = [...];\n *\n * // Get the prompt to use - you can modify this!\n * // If you want to see the prompt in full, you can at:\n * // https://smith.langchain.com/hub/hwchase17/structured-chat-agent\n * const prompt = await pull<ChatPromptTemplate>(\n * \"hwchase17/structured-chat-agent\"\n * );\n *\n * const llm = new ChatOpenAI({\n * temperature: 0,\n * model: \"gpt-3.5-turbo-1106\",\n * });\n *\n * const agent = await createStructuredChatAgent({\n * llm,\n * tools,\n * prompt,\n * });\n *\n * const agentExecutor = new AgentExecutor({\n * agent,\n * tools,\n * });\n *\n * const result = await agentExecutor.invoke({\n * input: \"what is LangChain?\",\n * });\n *\n * // With chat history\n * const result2 = await agentExecutor.invoke({\n * input: \"what's my name?\",\n * chat_history: [\n * new HumanMessage(\"hi! my name is cob\"),\n * new AIMessage(\"Hello Cob! How can I assist you today?\"),\n * ],\n * });\n * ```\n */\nexport async function createStructuredChatAgent({\n llm,\n tools,\n prompt,\n streamRunnable,\n}: CreateStructuredChatAgentParams) {\n const missingVariables = [\"tools\", \"tool_names\", \"agent_scratchpad\"].filter(\n (v) => !prompt.inputVariables.includes(v)\n );\n if (missingVariables.length > 0) {\n throw new Error(\n `Provided prompt is missing required input variables: ${JSON.stringify(\n missingVariables\n )}`\n );\n }\n let toolNames: string[] = [];\n if (tools.every(isOpenAITool)) {\n toolNames = tools.map((tool) => tool.function.name);\n } else if (tools.every(isStructuredTool)) {\n toolNames = tools.map((tool) => tool.name);\n } else {\n throw new Error(\n \"All tools must be either OpenAI or Structured tools, not a mix.\"\n );\n }\n const partialedPrompt = await prompt.partial({\n tools: renderTextDescriptionAndArgs(tools),\n tool_names: toolNames.join(\", \"),\n });\n // TODO: Add .bind to core runnable interface.\n const llmWithStop = (llm as BaseLanguageModel).withConfig({\n stop: [\"Observation\"],\n });\n const agent = AgentRunnableSequence.fromRunnables(\n [\n RunnablePassthrough.assign({\n agent_scratchpad: (input: { steps: AgentStep[] }) =>\n formatLogToString(input.steps),\n }),\n partialedPrompt,\n llmWithStop,\n StructuredChatOutputParserWithRetries.fromLLM(llm, {\n toolNames,\n }),\n ],\n {\n name: \"StructuredChatAgent\",\n streamRunnable,\n singleAction: true,\n }\n );\n return agent;\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/agents/structured_chat/index.ts"],"sourcesContent":["import type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport {\n isOpenAITool,\n type BaseLanguageModel,\n type BaseLanguageModelInterface,\n type ToolDefinition,\n} from \"@langchain/core/language_models/base\";\nimport { RunnablePassthrough } from \"@langchain/core/runnables\";\nimport type { BasePromptTemplate } from \"@langchain/core/prompts\";\nimport {\n BaseMessagePromptTemplate,\n ChatPromptTemplate,\n HumanMessagePromptTemplate,\n SystemMessagePromptTemplate,\n PromptTemplate,\n} from \"@langchain/core/prompts\";\nimport { AgentStep } from \"@langchain/core/agents\";\nimport { isStructuredTool } from \"@langchain/core/utils/function_calling\";\nimport { isInteropZodSchema } from \"@langchain/core/utils/types\";\nimport {\n type JsonSchema7Type,\n toJsonSchema,\n} from \"@langchain/core/utils/json_schema\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\nimport { Optional } from \"../../types/type-utils.js\";\nimport {\n Agent,\n AgentArgs,\n AgentRunnableSequence,\n OutputParserArgs,\n} from \"../agent.js\";\nimport { AgentInput } from \"../types.js\";\nimport { StructuredChatOutputParserWithRetries } from \"./outputParser.js\";\nimport { FORMAT_INSTRUCTIONS, PREFIX, SUFFIX } from \"./prompt.js\";\nimport { renderTextDescriptionAndArgs } from \"../../tools/render.js\";\nimport { formatLogToString } from \"../format_scratchpad/log.js\";\n\n/**\n * Interface for arguments used to create a prompt for a\n * StructuredChatAgent.\n */\nexport interface StructuredChatCreatePromptArgs {\n /** String to put after the list of tools. */\n suffix?: string;\n /** String to put before the list of tools. */\n prefix?: string;\n /** String to use directly as the human message template. */\n humanMessageTemplate?: string;\n /** List of input variables the final prompt will expect. */\n inputVariables?: string[];\n /** List of historical prompts from memory. */\n memoryPrompts?: BaseMessagePromptTemplate[];\n}\n\n/**\n * Type for input data for creating a StructuredChatAgent, with the\n * 'outputParser' property made optional.\n */\nexport type StructuredChatAgentInput = Optional<AgentInput, \"outputParser\">;\n\n/**\n * Agent that interoperates with Structured Tools using React logic.\n * @augments Agent\n */\nexport class StructuredChatAgent extends Agent {\n static lc_name() {\n return \"StructuredChatAgent\";\n }\n\n lc_namespace = [\"langchain\", \"agents\", \"structured_chat\"];\n\n constructor(input: StructuredChatAgentInput) {\n const outputParser =\n input?.outputParser ?? StructuredChatAgent.getDefaultOutputParser();\n super({ ...input, outputParser });\n }\n\n _agentType() {\n return \"structured-chat-zero-shot-react-description\" as const;\n }\n\n observationPrefix() {\n return \"Observation: \";\n }\n\n llmPrefix() {\n return \"Thought:\";\n }\n\n _stop(): string[] {\n return [\"Observation:\"];\n }\n\n /**\n * Validates that all provided tools have a description. Throws an error\n * if any tool lacks a description.\n * @param tools Array of StructuredTool instances to validate.\n */\n static validateTools(tools: StructuredToolInterface[]) {\n const descriptionlessTool = tools.find((tool) => !tool.description);\n if (descriptionlessTool) {\n const msg =\n `Got a tool ${descriptionlessTool.name} without a description.` +\n ` This agent requires descriptions for all tools.`;\n throw new Error(msg);\n }\n }\n\n /**\n * Returns a default output parser for the StructuredChatAgent. If an LLM\n * is provided, it creates an output parser with retry logic from the LLM.\n * @param fields Optional fields to customize the output parser. Can include an LLM and a list of tool names.\n * @returns An instance of StructuredChatOutputParserWithRetries.\n */\n static getDefaultOutputParser(\n fields?: OutputParserArgs & {\n toolNames: string[];\n }\n ) {\n if (fields?.llm) {\n return StructuredChatOutputParserWithRetries.fromLLM(fields.llm, {\n toolNames: fields.toolNames,\n });\n }\n return new StructuredChatOutputParserWithRetries({\n toolNames: fields?.toolNames,\n });\n }\n\n /**\n * Constructs the agent's scratchpad from a list of steps. If the agent's\n * scratchpad is not empty, it prepends a message indicating that the\n * agent has not seen any previous work.\n * @param steps Array of AgentStep instances to construct the scratchpad from.\n * @returns A Promise that resolves to a string representing the agent's scratchpad.\n */\n async constructScratchPad(steps: AgentStep[]): Promise<string> {\n const agentScratchpad = await super.constructScratchPad(steps);\n if (agentScratchpad) {\n return `This was your previous work (but I haven't seen any of it! I only see what you return as final answer):\\n${agentScratchpad}`;\n }\n return agentScratchpad;\n }\n\n /**\n * Creates a string representation of the schemas of the provided tools.\n * @param tools Array of StructuredTool instances to create the schemas string from.\n * @returns A string representing the schemas of the provided tools.\n */\n static createToolSchemasString(tools: StructuredToolInterface[]) {\n return tools\n .map((tool) => {\n const jsonSchema = (\n isInteropZodSchema(tool.schema)\n ? toJsonSchema(tool.schema)\n : tool.schema\n ) as { properties?: Record<string, JsonSchema7Type> } | undefined;\n return `${tool.name}: ${tool.description}, args: ${JSON.stringify(\n jsonSchema?.properties\n )}`;\n })\n .join(\"\\n\");\n }\n\n /**\n * Create prompt in the style of the agent.\n *\n * @param tools - List of tools the agent will have access to, used to format the prompt.\n * @param args - Arguments to create the prompt with.\n * @param args.suffix - String to put after the list of tools.\n * @param args.prefix - String to put before the list of tools.\n * @param args.inputVariables List of input variables the final prompt will expect.\n * @param args.memoryPrompts List of historical prompts from memory.\n */\n static createPrompt(\n tools: StructuredToolInterface[],\n args?: StructuredChatCreatePromptArgs\n ) {\n const {\n prefix = PREFIX,\n suffix = SUFFIX,\n inputVariables = [\"input\", \"agent_scratchpad\"],\n humanMessageTemplate = \"{input}\\n\\n{agent_scratchpad}\",\n memoryPrompts = [],\n } = args ?? {};\n const template = [prefix, FORMAT_INSTRUCTIONS, suffix].join(\"\\n\\n\");\n const messages = [\n new SystemMessagePromptTemplate(\n new PromptTemplate({\n template,\n inputVariables,\n partialVariables: {\n tool_schemas: StructuredChatAgent.createToolSchemasString(tools),\n tool_names: tools.map((tool) => tool.name).join(\", \"),\n },\n })\n ),\n ...memoryPrompts,\n new HumanMessagePromptTemplate(\n new PromptTemplate({\n template: humanMessageTemplate,\n inputVariables,\n })\n ),\n ];\n return ChatPromptTemplate.fromMessages(messages);\n }\n\n /**\n * Creates a StructuredChatAgent from an LLM and a list of tools.\n * Validates the tools, creates a prompt, and sets up an LLM chain for the\n * agent.\n * @param llm BaseLanguageModel instance to create the agent from.\n * @param tools Array of StructuredTool instances to create the agent from.\n * @param args Optional arguments to customize the creation of the agent. Can include arguments for creating the prompt and AgentArgs.\n * @returns A new instance of StructuredChatAgent.\n */\n static fromLLMAndTools(\n llm: BaseLanguageModelInterface,\n tools: StructuredToolInterface[],\n args?: StructuredChatCreatePromptArgs & AgentArgs\n ) {\n StructuredChatAgent.validateTools(tools);\n const prompt = StructuredChatAgent.createPrompt(tools, args);\n const outputParser =\n args?.outputParser ??\n StructuredChatAgent.getDefaultOutputParser({\n llm,\n toolNames: tools.map((tool) => tool.name),\n });\n const chain = new LLMChain({\n prompt,\n llm,\n callbacks: args?.callbacks,\n });\n\n return new StructuredChatAgent({\n llmChain: chain,\n outputParser,\n allowedTools: tools.map((t) => t.name),\n });\n }\n}\n\n/**\n * Params used by the createStructuredChatAgent function.\n */\nexport type CreateStructuredChatAgentParams = {\n /** LLM to use as the agent. */\n llm: BaseLanguageModelInterface;\n /** Tools this agent has access to. */\n tools: (StructuredToolInterface | ToolDefinition)[];\n /**\n * The prompt to use. Must have input keys for\n * `tools`, `tool_names`, and `agent_scratchpad`.\n */\n prompt: BasePromptTemplate;\n /**\n * Whether to invoke the underlying model in streaming mode,\n * allowing streaming of intermediate steps. Defaults to true.\n */\n streamRunnable?: boolean;\n};\n\n/**\n * Create an agent aimed at supporting tools with multiple inputs.\n * @param params Params required to create the agent. Includes an LLM, tools, and prompt.\n * @returns A runnable sequence representing an agent. It takes as input all the same input\n * variables as the prompt passed in does. It returns as output either an\n * AgentAction or AgentFinish.\n *\n * @example\n * ```typescript\n * import { AgentExecutor, createStructuredChatAgent } from \"langchain/agents\";\n * import { pull } from \"langchain/hub\";\n * import type { ChatPromptTemplate } from \"@langchain/core/prompts\";\n * import { AIMessage, HumanMessage } from \"@langchain/core/messages\";\n *\n * import { ChatOpenAI } from \"@langchain/openai\";\n *\n * // Define the tools the agent will have access to.\n * const tools = [...];\n *\n * // Get the prompt to use - you can modify this!\n * // If you want to see the prompt in full, you can at:\n * // https://smith.langchain.com/hub/hwchase17/structured-chat-agent\n * const prompt = await pull<ChatPromptTemplate>(\n * \"hwchase17/structured-chat-agent\"\n * );\n *\n * const llm = new ChatOpenAI({\n * temperature: 0,\n * model: \"gpt-3.5-turbo-1106\",\n * });\n *\n * const agent = await createStructuredChatAgent({\n * llm,\n * tools,\n * prompt,\n * });\n *\n * const agentExecutor = new AgentExecutor({\n * agent,\n * tools,\n * });\n *\n * const result = await agentExecutor.invoke({\n * input: \"what is LangChain?\",\n * });\n *\n * // With chat history\n * const result2 = await agentExecutor.invoke({\n * input: \"what's my name?\",\n * chat_history: [\n * new HumanMessage(\"hi! my name is cob\"),\n * new AIMessage(\"Hello Cob! How can I assist you today?\"),\n * ],\n * });\n * ```\n */\nexport async function createStructuredChatAgent({\n llm,\n tools,\n prompt,\n streamRunnable,\n}: CreateStructuredChatAgentParams) {\n const missingVariables = [\"tools\", \"tool_names\", \"agent_scratchpad\"].filter(\n (v) => !prompt.inputVariables.includes(v)\n );\n if (missingVariables.length > 0) {\n throw new Error(\n `Provided prompt is missing required input variables: ${JSON.stringify(\n missingVariables\n )}`\n );\n }\n let toolNames: string[] = [];\n if (tools.every(isOpenAITool)) {\n toolNames = tools.map((tool) => tool.function.name);\n } else if (tools.every(isStructuredTool)) {\n toolNames = tools.map((tool) => tool.name);\n } else {\n throw new Error(\n \"All tools must be either OpenAI or Structured tools, not a mix.\"\n );\n }\n const partialedPrompt = await prompt.partial({\n tools: renderTextDescriptionAndArgs(tools),\n tool_names: toolNames.join(\", \"),\n });\n // TODO: Add .bind to core runnable interface.\n const llmWithStop = (llm as BaseLanguageModel).withConfig({\n stop: [\"Observation\"],\n });\n const agent = AgentRunnableSequence.fromRunnables(\n [\n RunnablePassthrough.assign({\n agent_scratchpad: (input: { steps: AgentStep[] }) =>\n formatLogToString(input.steps),\n }),\n partialedPrompt,\n llmWithStop,\n StructuredChatOutputParserWithRetries.fromLLM(llm, {\n toolNames,\n }),\n ],\n {\n name: \"StructuredChatAgent\",\n streamRunnable,\n singleAction: true,\n }\n );\n return agent;\n}\n"],"mappings":"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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"outputParser.cjs","names":["AgentActionOutputParser","OutputParserException","AGENT_ACTION_FORMAT_INSTRUCTIONS","FORMAT_INSTRUCTIONS","OutputFixingParser"],"sources":["../../../src/agents/structured_chat/outputParser.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { Callbacks } from \"@langchain/core/callbacks/manager\";\nimport { AgentAction, AgentFinish } from \"@langchain/core/agents\";\nimport { OutputParserException } from \"@langchain/core/output_parsers\";\nimport { renderTemplate } from \"@langchain/core/prompts\";\nimport { AgentActionOutputParser } from \"../types.js\";\nimport {\n AGENT_ACTION_FORMAT_INSTRUCTIONS,\n FORMAT_INSTRUCTIONS,\n} from \"./prompt.js\";\nimport { OutputFixingParser } from \"../../output_parsers/fix.js\";\n\n/**\n * A class that provides a custom implementation for parsing the output of\n * a StructuredChatAgent action. It extends the `AgentActionOutputParser`\n * class and extracts the action and action input from the text output,\n * returning an `AgentAction` or `AgentFinish` object.\n */\nexport class StructuredChatOutputParser extends AgentActionOutputParser {\n lc_namespace = [\"langchain\", \"agents\", \"structured_chat\"];\n\n private toolNames: string[];\n\n constructor(fields: { toolNames: string[] }) {\n super(...arguments);\n this.toolNames = fields.toolNames;\n }\n\n /**\n * Parses the given text and returns an `AgentAction` or `AgentFinish`\n * object. If an `OutputFixingParser` is provided, it is used for parsing;\n * otherwise, the base parser is used.\n * @param text The text to parse.\n * @param callbacks Optional callbacks for asynchronous operations.\n * @returns A Promise that resolves to an `AgentAction` or `AgentFinish` object.\n */\n async parse(text: string): Promise<AgentAction | AgentFinish> {\n try {\n const regex = /```(?:json)?(.*)(```)/gs;\n const actionMatch = regex.exec(text);\n if (actionMatch === null) {\n throw new OutputParserException(\n `Could not parse an action. The agent action must be within a markdown code block, and \"action\" must be a provided tool or \"Final Answer\"`\n );\n }\n const response = JSON.parse(actionMatch[1].trim());\n const { action, action_input } = response;\n\n if (action === \"Final Answer\") {\n return { returnValues: { output: action_input }, log: text };\n }\n return { tool: action, toolInput: action_input || {}, log: text };\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`\n );\n }\n }\n\n /**\n * Returns the format instructions for parsing the output of an agent\n * action in the style of the StructuredChatAgent.\n * @returns A string representing the format instructions.\n */\n getFormatInstructions(): string {\n return renderTemplate(AGENT_ACTION_FORMAT_INSTRUCTIONS, \"f-string\", {\n tool_names: this.toolNames.join(\", \"),\n });\n }\n}\n\n/**\n * An interface for the arguments used to construct a\n * `StructuredChatOutputParserWithRetries` instance.\n */\nexport interface StructuredChatOutputParserArgs {\n baseParser?: StructuredChatOutputParser;\n outputFixingParser?: OutputFixingParser<AgentAction | AgentFinish>;\n toolNames?: string[];\n}\n\n/**\n * A class that provides a wrapper around the `StructuredChatOutputParser`\n * and `OutputFixingParser` classes. It extends the\n * `AgentActionOutputParser` class and allows for retrying the output\n * parsing using the `OutputFixingParser` if it is provided.\n * @example\n * ```typescript\n * const outputParser = new StructuredChatOutputParserWithRetries.fromLLM(\n * new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0 }),\n * {\n * toolNames: [\"calculator\", \"random-number-generator\"],\n * },\n * );\n * const result = await outputParser.parse(\n * \"What is a random number between 5 and 10 raised to the second power?\"\n * );\n * ```\n */\nexport class StructuredChatOutputParserWithRetries extends AgentActionOutputParser {\n lc_namespace = [\"langchain\", \"agents\", \"structured_chat\"];\n\n private baseParser: StructuredChatOutputParser;\n\n private outputFixingParser?: OutputFixingParser<AgentAction | AgentFinish>;\n\n private toolNames: string[] = [];\n\n constructor(fields: StructuredChatOutputParserArgs) {\n super(fields);\n this.toolNames = fields.toolNames ?? this.toolNames;\n this.baseParser =\n fields?.baseParser ??\n new StructuredChatOutputParser({ toolNames: this.toolNames });\n this.outputFixingParser = fields?.outputFixingParser;\n }\n\n /**\n * Parses the given text and returns an `AgentAction` or `AgentFinish`\n * object. Throws an `OutputParserException` if the parsing fails.\n * @param text The text to parse.\n * @returns A Promise that resolves to an `AgentAction` or `AgentFinish` object.\n */\n async parse(\n text: string,\n callbacks?: Callbacks\n ): Promise<AgentAction | AgentFinish> {\n if (this.outputFixingParser !== undefined) {\n return this.outputFixingParser.parse(text, callbacks);\n }\n return this.baseParser.parse(text);\n }\n\n /**\n * Returns the format instructions for parsing the output of an agent\n * action in the style of the StructuredChatAgent.\n * @returns A string representing the format instructions.\n */\n getFormatInstructions(): string {\n return renderTemplate(FORMAT_INSTRUCTIONS, \"f-string\", {\n tool_names: this.toolNames.join(\", \"),\n });\n }\n\n /**\n * Creates a new `StructuredChatOutputParserWithRetries` instance from a\n * `BaseLanguageModel` and options. The options can include a base parser\n * and tool names.\n * @param llm A `BaseLanguageModel` instance.\n * @param options Options for creating a `StructuredChatOutputParserWithRetries` instance.\n * @returns A new `StructuredChatOutputParserWithRetries` instance.\n */\n static fromLLM(\n llm: BaseLanguageModelInterface,\n options: Omit<StructuredChatOutputParserArgs, \"outputFixingParser\">\n ): StructuredChatOutputParserWithRetries {\n const baseParser =\n options.baseParser ??\n new StructuredChatOutputParser({ toolNames: options.toolNames ?? [] });\n const outputFixingParser = OutputFixingParser.fromLLM(llm, baseParser);\n return new StructuredChatOutputParserWithRetries({\n baseParser,\n outputFixingParser,\n toolNames: options.toolNames,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAkBA,IAAa,6BAAb,cAAgDA,cAAAA,wBAAwB;CACtE,eAAe;EAAC;EAAa;EAAU;EAAkB;CAEzD;CAEA,YAAY,QAAiC;AAC3C,QAAM,GAAG,UAAU;AACnB,OAAK,YAAY,OAAO;;;;;;;;;;CAW1B,MAAM,MAAM,MAAkD;AAC5D,MAAI;GAEF,MAAM,
|
|
1
|
+
{"version":3,"file":"outputParser.cjs","names":["AgentActionOutputParser","OutputParserException","AGENT_ACTION_FORMAT_INSTRUCTIONS","FORMAT_INSTRUCTIONS","OutputFixingParser"],"sources":["../../../src/agents/structured_chat/outputParser.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { Callbacks } from \"@langchain/core/callbacks/manager\";\nimport { AgentAction, AgentFinish } from \"@langchain/core/agents\";\nimport { OutputParserException } from \"@langchain/core/output_parsers\";\nimport { renderTemplate } from \"@langchain/core/prompts\";\nimport { AgentActionOutputParser } from \"../types.js\";\nimport {\n AGENT_ACTION_FORMAT_INSTRUCTIONS,\n FORMAT_INSTRUCTIONS,\n} from \"./prompt.js\";\nimport { OutputFixingParser } from \"../../output_parsers/fix.js\";\n\n/**\n * A class that provides a custom implementation for parsing the output of\n * a StructuredChatAgent action. It extends the `AgentActionOutputParser`\n * class and extracts the action and action input from the text output,\n * returning an `AgentAction` or `AgentFinish` object.\n */\nexport class StructuredChatOutputParser extends AgentActionOutputParser {\n lc_namespace = [\"langchain\", \"agents\", \"structured_chat\"];\n\n private toolNames: string[];\n\n constructor(fields: { toolNames: string[] }) {\n super(...arguments);\n this.toolNames = fields.toolNames;\n }\n\n /**\n * Parses the given text and returns an `AgentAction` or `AgentFinish`\n * object. If an `OutputFixingParser` is provided, it is used for parsing;\n * otherwise, the base parser is used.\n * @param text The text to parse.\n * @param callbacks Optional callbacks for asynchronous operations.\n * @returns A Promise that resolves to an `AgentAction` or `AgentFinish` object.\n */\n async parse(text: string): Promise<AgentAction | AgentFinish> {\n try {\n const regex = /```(?:json)?(.*)(```)/gs;\n const actionMatch = regex.exec(text);\n if (actionMatch === null) {\n throw new OutputParserException(\n `Could not parse an action. The agent action must be within a markdown code block, and \"action\" must be a provided tool or \"Final Answer\"`\n );\n }\n const response = JSON.parse(actionMatch[1].trim());\n const { action, action_input } = response;\n\n if (action === \"Final Answer\") {\n return { returnValues: { output: action_input }, log: text };\n }\n return { tool: action, toolInput: action_input || {}, log: text };\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`\n );\n }\n }\n\n /**\n * Returns the format instructions for parsing the output of an agent\n * action in the style of the StructuredChatAgent.\n * @returns A string representing the format instructions.\n */\n getFormatInstructions(): string {\n return renderTemplate(AGENT_ACTION_FORMAT_INSTRUCTIONS, \"f-string\", {\n tool_names: this.toolNames.join(\", \"),\n });\n }\n}\n\n/**\n * An interface for the arguments used to construct a\n * `StructuredChatOutputParserWithRetries` instance.\n */\nexport interface StructuredChatOutputParserArgs {\n baseParser?: StructuredChatOutputParser;\n outputFixingParser?: OutputFixingParser<AgentAction | AgentFinish>;\n toolNames?: string[];\n}\n\n/**\n * A class that provides a wrapper around the `StructuredChatOutputParser`\n * and `OutputFixingParser` classes. It extends the\n * `AgentActionOutputParser` class and allows for retrying the output\n * parsing using the `OutputFixingParser` if it is provided.\n * @example\n * ```typescript\n * const outputParser = new StructuredChatOutputParserWithRetries.fromLLM(\n * new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0 }),\n * {\n * toolNames: [\"calculator\", \"random-number-generator\"],\n * },\n * );\n * const result = await outputParser.parse(\n * \"What is a random number between 5 and 10 raised to the second power?\"\n * );\n * ```\n */\nexport class StructuredChatOutputParserWithRetries extends AgentActionOutputParser {\n lc_namespace = [\"langchain\", \"agents\", \"structured_chat\"];\n\n private baseParser: StructuredChatOutputParser;\n\n private outputFixingParser?: OutputFixingParser<AgentAction | AgentFinish>;\n\n private toolNames: string[] = [];\n\n constructor(fields: StructuredChatOutputParserArgs) {\n super(fields);\n this.toolNames = fields.toolNames ?? this.toolNames;\n this.baseParser =\n fields?.baseParser ??\n new StructuredChatOutputParser({ toolNames: this.toolNames });\n this.outputFixingParser = fields?.outputFixingParser;\n }\n\n /**\n * Parses the given text and returns an `AgentAction` or `AgentFinish`\n * object. Throws an `OutputParserException` if the parsing fails.\n * @param text The text to parse.\n * @returns A Promise that resolves to an `AgentAction` or `AgentFinish` object.\n */\n async parse(\n text: string,\n callbacks?: Callbacks\n ): Promise<AgentAction | AgentFinish> {\n if (this.outputFixingParser !== undefined) {\n return this.outputFixingParser.parse(text, callbacks);\n }\n return this.baseParser.parse(text);\n }\n\n /**\n * Returns the format instructions for parsing the output of an agent\n * action in the style of the StructuredChatAgent.\n * @returns A string representing the format instructions.\n */\n getFormatInstructions(): string {\n return renderTemplate(FORMAT_INSTRUCTIONS, \"f-string\", {\n tool_names: this.toolNames.join(\", \"),\n });\n }\n\n /**\n * Creates a new `StructuredChatOutputParserWithRetries` instance from a\n * `BaseLanguageModel` and options. The options can include a base parser\n * and tool names.\n * @param llm A `BaseLanguageModel` instance.\n * @param options Options for creating a `StructuredChatOutputParserWithRetries` instance.\n * @returns A new `StructuredChatOutputParserWithRetries` instance.\n */\n static fromLLM(\n llm: BaseLanguageModelInterface,\n options: Omit<StructuredChatOutputParserArgs, \"outputFixingParser\">\n ): StructuredChatOutputParserWithRetries {\n const baseParser =\n options.baseParser ??\n new StructuredChatOutputParser({ toolNames: options.toolNames ?? [] });\n const outputFixingParser = OutputFixingParser.fromLLM(llm, baseParser);\n return new StructuredChatOutputParserWithRetries({\n baseParser,\n outputFixingParser,\n toolNames: options.toolNames,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAkBA,IAAa,6BAAb,cAAgDA,cAAAA,wBAAwB;CACtE,eAAe;EAAC;EAAa;EAAU;EAAkB;CAEzD;CAEA,YAAY,QAAiC;AAC3C,QAAM,GAAG,UAAU;AACnB,OAAK,YAAY,OAAO;;;;;;;;;;CAW1B,MAAM,MAAM,MAAkD;AAC5D,MAAI;GAEF,MAAM,cAAc,0BAAM,KAAK,KAAK;AACpC,OAAI,gBAAgB,KAClB,OAAM,IAAIC,+BAAAA,sBACR,2IACD;GAGH,MAAM,EAAE,QAAQ,iBADC,KAAK,MAAM,YAAY,GAAG,MAAM,CACR;AAEzC,OAAI,WAAW,eACb,QAAO;IAAE,cAAc,EAAE,QAAQ,cAAc;IAAE,KAAK;IAAM;AAE9D,UAAO;IAAE,MAAM;IAAQ,WAAW,gBAAgB,EAAE;IAAE,KAAK;IAAM;WAC1D,GAAG;AACV,SAAM,IAAIA,+BAAAA,sBACR,2BAA2B,KAAK,YAAY,IAC7C;;;;;;;;CASL,wBAAgC;AAC9B,UAAA,GAAA,wBAAA,gBAAsBC,eAAAA,kCAAkC,YAAY,EAClE,YAAY,KAAK,UAAU,KAAK,KAAK,EACtC,CAAC;;;;;;;;;;;;;;;;;;;;;AAgCN,IAAa,wCAAb,MAAa,8CAA8CF,cAAAA,wBAAwB;CACjF,eAAe;EAAC;EAAa;EAAU;EAAkB;CAEzD;CAEA;CAEA,YAA8B,EAAE;CAEhC,YAAY,QAAwC;AAClD,QAAM,OAAO;AACb,OAAK,YAAY,OAAO,aAAa,KAAK;AAC1C,OAAK,aACH,QAAQ,cACR,IAAI,2BAA2B,EAAE,WAAW,KAAK,WAAW,CAAC;AAC/D,OAAK,qBAAqB,QAAQ;;;;;;;;CASpC,MAAM,MACJ,MACA,WACoC;AACpC,MAAI,KAAK,uBAAuB,KAAA,EAC9B,QAAO,KAAK,mBAAmB,MAAM,MAAM,UAAU;AAEvD,SAAO,KAAK,WAAW,MAAM,KAAK;;;;;;;CAQpC,wBAAgC;AAC9B,UAAA,GAAA,wBAAA,gBAAsBG,eAAAA,qBAAqB,YAAY,EACrD,YAAY,KAAK,UAAU,KAAK,KAAK,EACtC,CAAC;;;;;;;;;;CAWJ,OAAO,QACL,KACA,SACuC;EACvC,MAAM,aACJ,QAAQ,cACR,IAAI,2BAA2B,EAAE,WAAW,QAAQ,aAAa,EAAE,EAAE,CAAC;AAExE,SAAO,IAAI,sCAAsC;GAC/C;GACA,oBAHyBC,YAAAA,mBAAmB,QAAQ,KAAK,WAGvC;GAClB,WAAW,QAAQ;GACpB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"outputParser.js","names":[],"sources":["../../../src/agents/structured_chat/outputParser.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { Callbacks } from \"@langchain/core/callbacks/manager\";\nimport { AgentAction, AgentFinish } from \"@langchain/core/agents\";\nimport { OutputParserException } from \"@langchain/core/output_parsers\";\nimport { renderTemplate } from \"@langchain/core/prompts\";\nimport { AgentActionOutputParser } from \"../types.js\";\nimport {\n AGENT_ACTION_FORMAT_INSTRUCTIONS,\n FORMAT_INSTRUCTIONS,\n} from \"./prompt.js\";\nimport { OutputFixingParser } from \"../../output_parsers/fix.js\";\n\n/**\n * A class that provides a custom implementation for parsing the output of\n * a StructuredChatAgent action. It extends the `AgentActionOutputParser`\n * class and extracts the action and action input from the text output,\n * returning an `AgentAction` or `AgentFinish` object.\n */\nexport class StructuredChatOutputParser extends AgentActionOutputParser {\n lc_namespace = [\"langchain\", \"agents\", \"structured_chat\"];\n\n private toolNames: string[];\n\n constructor(fields: { toolNames: string[] }) {\n super(...arguments);\n this.toolNames = fields.toolNames;\n }\n\n /**\n * Parses the given text and returns an `AgentAction` or `AgentFinish`\n * object. If an `OutputFixingParser` is provided, it is used for parsing;\n * otherwise, the base parser is used.\n * @param text The text to parse.\n * @param callbacks Optional callbacks for asynchronous operations.\n * @returns A Promise that resolves to an `AgentAction` or `AgentFinish` object.\n */\n async parse(text: string): Promise<AgentAction | AgentFinish> {\n try {\n const regex = /```(?:json)?(.*)(```)/gs;\n const actionMatch = regex.exec(text);\n if (actionMatch === null) {\n throw new OutputParserException(\n `Could not parse an action. The agent action must be within a markdown code block, and \"action\" must be a provided tool or \"Final Answer\"`\n );\n }\n const response = JSON.parse(actionMatch[1].trim());\n const { action, action_input } = response;\n\n if (action === \"Final Answer\") {\n return { returnValues: { output: action_input }, log: text };\n }\n return { tool: action, toolInput: action_input || {}, log: text };\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`\n );\n }\n }\n\n /**\n * Returns the format instructions for parsing the output of an agent\n * action in the style of the StructuredChatAgent.\n * @returns A string representing the format instructions.\n */\n getFormatInstructions(): string {\n return renderTemplate(AGENT_ACTION_FORMAT_INSTRUCTIONS, \"f-string\", {\n tool_names: this.toolNames.join(\", \"),\n });\n }\n}\n\n/**\n * An interface for the arguments used to construct a\n * `StructuredChatOutputParserWithRetries` instance.\n */\nexport interface StructuredChatOutputParserArgs {\n baseParser?: StructuredChatOutputParser;\n outputFixingParser?: OutputFixingParser<AgentAction | AgentFinish>;\n toolNames?: string[];\n}\n\n/**\n * A class that provides a wrapper around the `StructuredChatOutputParser`\n * and `OutputFixingParser` classes. It extends the\n * `AgentActionOutputParser` class and allows for retrying the output\n * parsing using the `OutputFixingParser` if it is provided.\n * @example\n * ```typescript\n * const outputParser = new StructuredChatOutputParserWithRetries.fromLLM(\n * new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0 }),\n * {\n * toolNames: [\"calculator\", \"random-number-generator\"],\n * },\n * );\n * const result = await outputParser.parse(\n * \"What is a random number between 5 and 10 raised to the second power?\"\n * );\n * ```\n */\nexport class StructuredChatOutputParserWithRetries extends AgentActionOutputParser {\n lc_namespace = [\"langchain\", \"agents\", \"structured_chat\"];\n\n private baseParser: StructuredChatOutputParser;\n\n private outputFixingParser?: OutputFixingParser<AgentAction | AgentFinish>;\n\n private toolNames: string[] = [];\n\n constructor(fields: StructuredChatOutputParserArgs) {\n super(fields);\n this.toolNames = fields.toolNames ?? this.toolNames;\n this.baseParser =\n fields?.baseParser ??\n new StructuredChatOutputParser({ toolNames: this.toolNames });\n this.outputFixingParser = fields?.outputFixingParser;\n }\n\n /**\n * Parses the given text and returns an `AgentAction` or `AgentFinish`\n * object. Throws an `OutputParserException` if the parsing fails.\n * @param text The text to parse.\n * @returns A Promise that resolves to an `AgentAction` or `AgentFinish` object.\n */\n async parse(\n text: string,\n callbacks?: Callbacks\n ): Promise<AgentAction | AgentFinish> {\n if (this.outputFixingParser !== undefined) {\n return this.outputFixingParser.parse(text, callbacks);\n }\n return this.baseParser.parse(text);\n }\n\n /**\n * Returns the format instructions for parsing the output of an agent\n * action in the style of the StructuredChatAgent.\n * @returns A string representing the format instructions.\n */\n getFormatInstructions(): string {\n return renderTemplate(FORMAT_INSTRUCTIONS, \"f-string\", {\n tool_names: this.toolNames.join(\", \"),\n });\n }\n\n /**\n * Creates a new `StructuredChatOutputParserWithRetries` instance from a\n * `BaseLanguageModel` and options. The options can include a base parser\n * and tool names.\n * @param llm A `BaseLanguageModel` instance.\n * @param options Options for creating a `StructuredChatOutputParserWithRetries` instance.\n * @returns A new `StructuredChatOutputParserWithRetries` instance.\n */\n static fromLLM(\n llm: BaseLanguageModelInterface,\n options: Omit<StructuredChatOutputParserArgs, \"outputFixingParser\">\n ): StructuredChatOutputParserWithRetries {\n const baseParser =\n options.baseParser ??\n new StructuredChatOutputParser({ toolNames: options.toolNames ?? [] });\n const outputFixingParser = OutputFixingParser.fromLLM(llm, baseParser);\n return new StructuredChatOutputParserWithRetries({\n baseParser,\n outputFixingParser,\n toolNames: options.toolNames,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;AAkBA,IAAa,6BAAb,cAAgD,wBAAwB;CACtE,eAAe;EAAC;EAAa;EAAU;EAAkB;CAEzD;CAEA,YAAY,QAAiC;AAC3C,QAAM,GAAG,UAAU;AACnB,OAAK,YAAY,OAAO;;;;;;;;;;CAW1B,MAAM,MAAM,MAAkD;AAC5D,MAAI;GAEF,MAAM,
|
|
1
|
+
{"version":3,"file":"outputParser.js","names":[],"sources":["../../../src/agents/structured_chat/outputParser.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { Callbacks } from \"@langchain/core/callbacks/manager\";\nimport { AgentAction, AgentFinish } from \"@langchain/core/agents\";\nimport { OutputParserException } from \"@langchain/core/output_parsers\";\nimport { renderTemplate } from \"@langchain/core/prompts\";\nimport { AgentActionOutputParser } from \"../types.js\";\nimport {\n AGENT_ACTION_FORMAT_INSTRUCTIONS,\n FORMAT_INSTRUCTIONS,\n} from \"./prompt.js\";\nimport { OutputFixingParser } from \"../../output_parsers/fix.js\";\n\n/**\n * A class that provides a custom implementation for parsing the output of\n * a StructuredChatAgent action. It extends the `AgentActionOutputParser`\n * class and extracts the action and action input from the text output,\n * returning an `AgentAction` or `AgentFinish` object.\n */\nexport class StructuredChatOutputParser extends AgentActionOutputParser {\n lc_namespace = [\"langchain\", \"agents\", \"structured_chat\"];\n\n private toolNames: string[];\n\n constructor(fields: { toolNames: string[] }) {\n super(...arguments);\n this.toolNames = fields.toolNames;\n }\n\n /**\n * Parses the given text and returns an `AgentAction` or `AgentFinish`\n * object. If an `OutputFixingParser` is provided, it is used for parsing;\n * otherwise, the base parser is used.\n * @param text The text to parse.\n * @param callbacks Optional callbacks for asynchronous operations.\n * @returns A Promise that resolves to an `AgentAction` or `AgentFinish` object.\n */\n async parse(text: string): Promise<AgentAction | AgentFinish> {\n try {\n const regex = /```(?:json)?(.*)(```)/gs;\n const actionMatch = regex.exec(text);\n if (actionMatch === null) {\n throw new OutputParserException(\n `Could not parse an action. The agent action must be within a markdown code block, and \"action\" must be a provided tool or \"Final Answer\"`\n );\n }\n const response = JSON.parse(actionMatch[1].trim());\n const { action, action_input } = response;\n\n if (action === \"Final Answer\") {\n return { returnValues: { output: action_input }, log: text };\n }\n return { tool: action, toolInput: action_input || {}, log: text };\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`\n );\n }\n }\n\n /**\n * Returns the format instructions for parsing the output of an agent\n * action in the style of the StructuredChatAgent.\n * @returns A string representing the format instructions.\n */\n getFormatInstructions(): string {\n return renderTemplate(AGENT_ACTION_FORMAT_INSTRUCTIONS, \"f-string\", {\n tool_names: this.toolNames.join(\", \"),\n });\n }\n}\n\n/**\n * An interface for the arguments used to construct a\n * `StructuredChatOutputParserWithRetries` instance.\n */\nexport interface StructuredChatOutputParserArgs {\n baseParser?: StructuredChatOutputParser;\n outputFixingParser?: OutputFixingParser<AgentAction | AgentFinish>;\n toolNames?: string[];\n}\n\n/**\n * A class that provides a wrapper around the `StructuredChatOutputParser`\n * and `OutputFixingParser` classes. It extends the\n * `AgentActionOutputParser` class and allows for retrying the output\n * parsing using the `OutputFixingParser` if it is provided.\n * @example\n * ```typescript\n * const outputParser = new StructuredChatOutputParserWithRetries.fromLLM(\n * new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0 }),\n * {\n * toolNames: [\"calculator\", \"random-number-generator\"],\n * },\n * );\n * const result = await outputParser.parse(\n * \"What is a random number between 5 and 10 raised to the second power?\"\n * );\n * ```\n */\nexport class StructuredChatOutputParserWithRetries extends AgentActionOutputParser {\n lc_namespace = [\"langchain\", \"agents\", \"structured_chat\"];\n\n private baseParser: StructuredChatOutputParser;\n\n private outputFixingParser?: OutputFixingParser<AgentAction | AgentFinish>;\n\n private toolNames: string[] = [];\n\n constructor(fields: StructuredChatOutputParserArgs) {\n super(fields);\n this.toolNames = fields.toolNames ?? this.toolNames;\n this.baseParser =\n fields?.baseParser ??\n new StructuredChatOutputParser({ toolNames: this.toolNames });\n this.outputFixingParser = fields?.outputFixingParser;\n }\n\n /**\n * Parses the given text and returns an `AgentAction` or `AgentFinish`\n * object. Throws an `OutputParserException` if the parsing fails.\n * @param text The text to parse.\n * @returns A Promise that resolves to an `AgentAction` or `AgentFinish` object.\n */\n async parse(\n text: string,\n callbacks?: Callbacks\n ): Promise<AgentAction | AgentFinish> {\n if (this.outputFixingParser !== undefined) {\n return this.outputFixingParser.parse(text, callbacks);\n }\n return this.baseParser.parse(text);\n }\n\n /**\n * Returns the format instructions for parsing the output of an agent\n * action in the style of the StructuredChatAgent.\n * @returns A string representing the format instructions.\n */\n getFormatInstructions(): string {\n return renderTemplate(FORMAT_INSTRUCTIONS, \"f-string\", {\n tool_names: this.toolNames.join(\", \"),\n });\n }\n\n /**\n * Creates a new `StructuredChatOutputParserWithRetries` instance from a\n * `BaseLanguageModel` and options. The options can include a base parser\n * and tool names.\n * @param llm A `BaseLanguageModel` instance.\n * @param options Options for creating a `StructuredChatOutputParserWithRetries` instance.\n * @returns A new `StructuredChatOutputParserWithRetries` instance.\n */\n static fromLLM(\n llm: BaseLanguageModelInterface,\n options: Omit<StructuredChatOutputParserArgs, \"outputFixingParser\">\n ): StructuredChatOutputParserWithRetries {\n const baseParser =\n options.baseParser ??\n new StructuredChatOutputParser({ toolNames: options.toolNames ?? [] });\n const outputFixingParser = OutputFixingParser.fromLLM(llm, baseParser);\n return new StructuredChatOutputParserWithRetries({\n baseParser,\n outputFixingParser,\n toolNames: options.toolNames,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;AAkBA,IAAa,6BAAb,cAAgD,wBAAwB;CACtE,eAAe;EAAC;EAAa;EAAU;EAAkB;CAEzD;CAEA,YAAY,QAAiC;AAC3C,QAAM,GAAG,UAAU;AACnB,OAAK,YAAY,OAAO;;;;;;;;;;CAW1B,MAAM,MAAM,MAAkD;AAC5D,MAAI;GAEF,MAAM,cAAc,0BAAM,KAAK,KAAK;AACpC,OAAI,gBAAgB,KAClB,OAAM,IAAI,sBACR,2IACD;GAGH,MAAM,EAAE,QAAQ,iBADC,KAAK,MAAM,YAAY,GAAG,MAAM,CACR;AAEzC,OAAI,WAAW,eACb,QAAO;IAAE,cAAc,EAAE,QAAQ,cAAc;IAAE,KAAK;IAAM;AAE9D,UAAO;IAAE,MAAM;IAAQ,WAAW,gBAAgB,EAAE;IAAE,KAAK;IAAM;WAC1D,GAAG;AACV,SAAM,IAAI,sBACR,2BAA2B,KAAK,YAAY,IAC7C;;;;;;;;CASL,wBAAgC;AAC9B,SAAO,eAAe,kCAAkC,YAAY,EAClE,YAAY,KAAK,UAAU,KAAK,KAAK,EACtC,CAAC;;;;;;;;;;;;;;;;;;;;;AAgCN,IAAa,wCAAb,MAAa,8CAA8C,wBAAwB;CACjF,eAAe;EAAC;EAAa;EAAU;EAAkB;CAEzD;CAEA;CAEA,YAA8B,EAAE;CAEhC,YAAY,QAAwC;AAClD,QAAM,OAAO;AACb,OAAK,YAAY,OAAO,aAAa,KAAK;AAC1C,OAAK,aACH,QAAQ,cACR,IAAI,2BAA2B,EAAE,WAAW,KAAK,WAAW,CAAC;AAC/D,OAAK,qBAAqB,QAAQ;;;;;;;;CASpC,MAAM,MACJ,MACA,WACoC;AACpC,MAAI,KAAK,uBAAuB,KAAA,EAC9B,QAAO,KAAK,mBAAmB,MAAM,MAAM,UAAU;AAEvD,SAAO,KAAK,WAAW,MAAM,KAAK;;;;;;;CAQpC,wBAAgC;AAC9B,SAAO,eAAe,qBAAqB,YAAY,EACrD,YAAY,KAAK,UAAU,KAAK,KAAK,EACtC,CAAC;;;;;;;;;;CAWJ,OAAO,QACL,KACA,SACuC;EACvC,MAAM,aACJ,QAAQ,cACR,IAAI,2BAA2B,EAAE,WAAW,QAAQ,aAAa,EAAE,EAAE,CAAC;AAExE,SAAO,IAAI,sCAAsC;GAC/C;GACA,oBAHyB,mBAAmB,QAAQ,KAAK,WAGvC;GAClB,WAAW,QAAQ;GACpB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["AgentRunnableSequence","RunnablePassthrough","formatToToolMessages","ToolCallingAgentOutputParser"],"sources":["../../../src/agents/tool_calling/index.ts"],"sourcesContent":["import { ChatPromptTemplate } from \"@langchain/core/prompts\";\nimport { StructuredToolInterface } from \"@langchain/core/tools\";\nimport { RunnablePassthrough } from \"@langchain/core/runnables\";\nimport {\n LanguageModelLike,\n ToolDefinition,\n} from \"@langchain/core/language_models/base\";\nimport { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport { AgentRunnableSequence } from \"../agent.js\";\nimport {\n ToolCallingAgentOutputParser,\n ToolsAgentStep,\n} from \"./output_parser.js\";\nimport { formatToToolMessages } from \"../format_scratchpad/tool_calling.js\";\n\nfunction _isBaseChatModel(x: LanguageModelLike): x is BaseChatModel {\n const model = x as BaseChatModel;\n return (\n typeof model._modelType === \"function\" &&\n model._modelType() === \"base_chat_model\"\n );\n}\n\n/**\n * Params used by the createOpenAIToolsAgent function.\n */\nexport type CreateToolCallingAgentParams = {\n /**\n * LLM to use as the agent. Should work with OpenAI tool calling,\n * so must either be an OpenAI model that supports that or a wrapper of\n * a different model that adds in equivalent support.\n */\n llm: LanguageModelLike;\n /** Tools this agent has access to. */\n tools: StructuredToolInterface[] | ToolDefinition[];\n /** The prompt to use, must have an input key of `agent_scratchpad`. */\n prompt: ChatPromptTemplate;\n /**\n * Whether to invoke the underlying model in streaming mode,\n * allowing streaming of intermediate steps. Defaults to true.\n */\n streamRunnable?: boolean;\n};\n\n/**\n * Create an agent that uses tools.\n * @param params Params required to create the agent. Includes an LLM, tools, and prompt.\n * @returns A runnable sequence representing an agent. It takes as input all the same input\n * variables as the prompt passed in does. It returns as output either an\n * AgentAction or AgentFinish.\n * @example\n * ```typescript\n * import { ChatAnthropic } from \"@langchain/anthropic\";\n * import { ChatPromptTemplate, MessagesPlaceholder } from \"@langchain/core/prompts\";\n * import { AgentExecutor, createToolCallingAgent } from \"langchain/agents\";\n *\n * const prompt = ChatPromptTemplate.fromMessages(\n * [\n * [\"system\", \"You are a helpful assistant\"],\n * [\"placeholder\", \"{chat_history}\"],\n * [\"human\", \"{input}\"],\n * [\"placeholder\", \"{agent_scratchpad}\"],\n * ]\n * );\n *\n *\n * const llm = new ChatAnthropic({\n * modelName: \"claude-3-opus-20240229\",\n * temperature: 0,\n * });\n *\n * // Define the tools the agent will have access to.\n * const tools = [...];\n *\n * const agent = createToolCallingAgent({ llm, tools, prompt });\n *\n * const agentExecutor = new AgentExecutor({ agent, tools });\n *\n * const result = await agentExecutor.invoke({input: \"what is LangChain?\"});\n *\n * // Using with chat history\n * import { AIMessage, HumanMessage } from \"@langchain/core/messages\";\n *\n * const result2 = await agentExecutor.invoke(\n * {\n * input: \"what's my name?\",\n * chat_history: [\n * new HumanMessage({content: \"hi! my name is bob\"}),\n * new AIMessage({content: \"Hello Bob! How can I assist you today?\"}),\n * ],\n * }\n * );\n * ```\n */\nexport function createToolCallingAgent({\n llm,\n tools,\n prompt,\n streamRunnable,\n}: CreateToolCallingAgentParams) {\n if (!prompt.inputVariables.includes(\"agent_scratchpad\")) {\n throw new Error(\n [\n `Prompt must have an input variable named \"agent_scratchpad\".`,\n `Found ${JSON.stringify(prompt.inputVariables)} instead.`,\n ].join(\"\\n\")\n );\n }\n let modelWithTools;\n if (_isBaseChatModel(llm)) {\n if (llm.bindTools === undefined) {\n throw new Error(\n `This agent requires that the \"bind_tools()\" method be implemented on the input model.`\n );\n }\n modelWithTools = llm.bindTools(tools);\n } else {\n modelWithTools = llm;\n }\n\n const agent = AgentRunnableSequence.fromRunnables(\n [\n RunnablePassthrough.assign({\n agent_scratchpad: (input: { steps: ToolsAgentStep[] }) =>\n formatToToolMessages(input.steps),\n }),\n prompt,\n modelWithTools,\n new ToolCallingAgentOutputParser(),\n ],\n {\n name: \"ToolCallingAgent\",\n streamRunnable,\n singleAction: false,\n }\n );\n return agent;\n}\n"],"mappings":";;;;;;AAeA,SAAS,iBAAiB,GAA0C;CAClE,MAAM,QAAQ;AACd,QACE,OAAO,MAAM,eAAe,cAC5B,MAAM,YAAY,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2E3B,SAAgB,uBAAuB,EACrC,KACA,OACA,QACA,kBAC+B;AAC/B,KAAI,CAAC,OAAO,eAAe,SAAS,mBAAmB,CACrD,OAAM,IAAI,MACR,CACE,gEACA,SAAS,KAAK,UAAU,OAAO,eAAe,CAAC,WAChD,CAAC,KAAK,KAAK,CACb;CAEH,IAAI;AACJ,KAAI,iBAAiB,IAAI,EAAE;AACzB,MAAI,IAAI,cAAc,KAAA,EACpB,OAAM,IAAI,MACR,wFACD;AAEH,mBAAiB,IAAI,UAAU,MAAM;OAErC,kBAAiB;AAmBnB,QAhBcA,cAAAA,sBAAsB,cAClC;EACEC,0BAAAA,oBAAoB,OAAO,EACzB,mBAAmB,UACjBC,qBAAAA,qBAAqB,MAAM,MAAM,EACpC,CAAC;EACF;EACA;EACA,IAAIC,sBAAAA,8BAA8B;EACnC,EACD;EACE,MAAM;EACN;EACA,cAAc;EACf,
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["AgentRunnableSequence","RunnablePassthrough","formatToToolMessages","ToolCallingAgentOutputParser"],"sources":["../../../src/agents/tool_calling/index.ts"],"sourcesContent":["import { ChatPromptTemplate } from \"@langchain/core/prompts\";\nimport { StructuredToolInterface } from \"@langchain/core/tools\";\nimport { RunnablePassthrough } from \"@langchain/core/runnables\";\nimport {\n LanguageModelLike,\n ToolDefinition,\n} from \"@langchain/core/language_models/base\";\nimport { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport { AgentRunnableSequence } from \"../agent.js\";\nimport {\n ToolCallingAgentOutputParser,\n ToolsAgentStep,\n} from \"./output_parser.js\";\nimport { formatToToolMessages } from \"../format_scratchpad/tool_calling.js\";\n\nfunction _isBaseChatModel(x: LanguageModelLike): x is BaseChatModel {\n const model = x as BaseChatModel;\n return (\n typeof model._modelType === \"function\" &&\n model._modelType() === \"base_chat_model\"\n );\n}\n\n/**\n * Params used by the createOpenAIToolsAgent function.\n */\nexport type CreateToolCallingAgentParams = {\n /**\n * LLM to use as the agent. Should work with OpenAI tool calling,\n * so must either be an OpenAI model that supports that or a wrapper of\n * a different model that adds in equivalent support.\n */\n llm: LanguageModelLike;\n /** Tools this agent has access to. */\n tools: StructuredToolInterface[] | ToolDefinition[];\n /** The prompt to use, must have an input key of `agent_scratchpad`. */\n prompt: ChatPromptTemplate;\n /**\n * Whether to invoke the underlying model in streaming mode,\n * allowing streaming of intermediate steps. Defaults to true.\n */\n streamRunnable?: boolean;\n};\n\n/**\n * Create an agent that uses tools.\n * @param params Params required to create the agent. Includes an LLM, tools, and prompt.\n * @returns A runnable sequence representing an agent. It takes as input all the same input\n * variables as the prompt passed in does. It returns as output either an\n * AgentAction or AgentFinish.\n * @example\n * ```typescript\n * import { ChatAnthropic } from \"@langchain/anthropic\";\n * import { ChatPromptTemplate, MessagesPlaceholder } from \"@langchain/core/prompts\";\n * import { AgentExecutor, createToolCallingAgent } from \"langchain/agents\";\n *\n * const prompt = ChatPromptTemplate.fromMessages(\n * [\n * [\"system\", \"You are a helpful assistant\"],\n * [\"placeholder\", \"{chat_history}\"],\n * [\"human\", \"{input}\"],\n * [\"placeholder\", \"{agent_scratchpad}\"],\n * ]\n * );\n *\n *\n * const llm = new ChatAnthropic({\n * modelName: \"claude-3-opus-20240229\",\n * temperature: 0,\n * });\n *\n * // Define the tools the agent will have access to.\n * const tools = [...];\n *\n * const agent = createToolCallingAgent({ llm, tools, prompt });\n *\n * const agentExecutor = new AgentExecutor({ agent, tools });\n *\n * const result = await agentExecutor.invoke({input: \"what is LangChain?\"});\n *\n * // Using with chat history\n * import { AIMessage, HumanMessage } from \"@langchain/core/messages\";\n *\n * const result2 = await agentExecutor.invoke(\n * {\n * input: \"what's my name?\",\n * chat_history: [\n * new HumanMessage({content: \"hi! my name is bob\"}),\n * new AIMessage({content: \"Hello Bob! How can I assist you today?\"}),\n * ],\n * }\n * );\n * ```\n */\nexport function createToolCallingAgent({\n llm,\n tools,\n prompt,\n streamRunnable,\n}: CreateToolCallingAgentParams) {\n if (!prompt.inputVariables.includes(\"agent_scratchpad\")) {\n throw new Error(\n [\n `Prompt must have an input variable named \"agent_scratchpad\".`,\n `Found ${JSON.stringify(prompt.inputVariables)} instead.`,\n ].join(\"\\n\")\n );\n }\n let modelWithTools;\n if (_isBaseChatModel(llm)) {\n if (llm.bindTools === undefined) {\n throw new Error(\n `This agent requires that the \"bind_tools()\" method be implemented on the input model.`\n );\n }\n modelWithTools = llm.bindTools(tools);\n } else {\n modelWithTools = llm;\n }\n\n const agent = AgentRunnableSequence.fromRunnables(\n [\n RunnablePassthrough.assign({\n agent_scratchpad: (input: { steps: ToolsAgentStep[] }) =>\n formatToToolMessages(input.steps),\n }),\n prompt,\n modelWithTools,\n new ToolCallingAgentOutputParser(),\n ],\n {\n name: \"ToolCallingAgent\",\n streamRunnable,\n singleAction: false,\n }\n );\n return agent;\n}\n"],"mappings":";;;;;;AAeA,SAAS,iBAAiB,GAA0C;CAClE,MAAM,QAAQ;AACd,QACE,OAAO,MAAM,eAAe,cAC5B,MAAM,YAAY,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2E3B,SAAgB,uBAAuB,EACrC,KACA,OACA,QACA,kBAC+B;AAC/B,KAAI,CAAC,OAAO,eAAe,SAAS,mBAAmB,CACrD,OAAM,IAAI,MACR,CACE,gEACA,SAAS,KAAK,UAAU,OAAO,eAAe,CAAC,WAChD,CAAC,KAAK,KAAK,CACb;CAEH,IAAI;AACJ,KAAI,iBAAiB,IAAI,EAAE;AACzB,MAAI,IAAI,cAAc,KAAA,EACpB,OAAM,IAAI,MACR,wFACD;AAEH,mBAAiB,IAAI,UAAU,MAAM;OAErC,kBAAiB;AAmBnB,QAhBcA,cAAAA,sBAAsB,cAClC;EACEC,0BAAAA,oBAAoB,OAAO,EACzB,mBAAmB,UACjBC,qBAAAA,qBAAqB,MAAM,MAAM,EACpC,CAAC;EACF;EACA;EACA,IAAIC,sBAAAA,8BAA8B;EACnC,EACD;EACE,MAAM;EACN;EACA,cAAc;EACf,CAES"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/agents/tool_calling/index.ts"],"sourcesContent":["import { ChatPromptTemplate } from \"@langchain/core/prompts\";\nimport { StructuredToolInterface } from \"@langchain/core/tools\";\nimport { RunnablePassthrough } from \"@langchain/core/runnables\";\nimport {\n LanguageModelLike,\n ToolDefinition,\n} from \"@langchain/core/language_models/base\";\nimport { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport { AgentRunnableSequence } from \"../agent.js\";\nimport {\n ToolCallingAgentOutputParser,\n ToolsAgentStep,\n} from \"./output_parser.js\";\nimport { formatToToolMessages } from \"../format_scratchpad/tool_calling.js\";\n\nfunction _isBaseChatModel(x: LanguageModelLike): x is BaseChatModel {\n const model = x as BaseChatModel;\n return (\n typeof model._modelType === \"function\" &&\n model._modelType() === \"base_chat_model\"\n );\n}\n\n/**\n * Params used by the createOpenAIToolsAgent function.\n */\nexport type CreateToolCallingAgentParams = {\n /**\n * LLM to use as the agent. Should work with OpenAI tool calling,\n * so must either be an OpenAI model that supports that or a wrapper of\n * a different model that adds in equivalent support.\n */\n llm: LanguageModelLike;\n /** Tools this agent has access to. */\n tools: StructuredToolInterface[] | ToolDefinition[];\n /** The prompt to use, must have an input key of `agent_scratchpad`. */\n prompt: ChatPromptTemplate;\n /**\n * Whether to invoke the underlying model in streaming mode,\n * allowing streaming of intermediate steps. Defaults to true.\n */\n streamRunnable?: boolean;\n};\n\n/**\n * Create an agent that uses tools.\n * @param params Params required to create the agent. Includes an LLM, tools, and prompt.\n * @returns A runnable sequence representing an agent. It takes as input all the same input\n * variables as the prompt passed in does. It returns as output either an\n * AgentAction or AgentFinish.\n * @example\n * ```typescript\n * import { ChatAnthropic } from \"@langchain/anthropic\";\n * import { ChatPromptTemplate, MessagesPlaceholder } from \"@langchain/core/prompts\";\n * import { AgentExecutor, createToolCallingAgent } from \"langchain/agents\";\n *\n * const prompt = ChatPromptTemplate.fromMessages(\n * [\n * [\"system\", \"You are a helpful assistant\"],\n * [\"placeholder\", \"{chat_history}\"],\n * [\"human\", \"{input}\"],\n * [\"placeholder\", \"{agent_scratchpad}\"],\n * ]\n * );\n *\n *\n * const llm = new ChatAnthropic({\n * modelName: \"claude-3-opus-20240229\",\n * temperature: 0,\n * });\n *\n * // Define the tools the agent will have access to.\n * const tools = [...];\n *\n * const agent = createToolCallingAgent({ llm, tools, prompt });\n *\n * const agentExecutor = new AgentExecutor({ agent, tools });\n *\n * const result = await agentExecutor.invoke({input: \"what is LangChain?\"});\n *\n * // Using with chat history\n * import { AIMessage, HumanMessage } from \"@langchain/core/messages\";\n *\n * const result2 = await agentExecutor.invoke(\n * {\n * input: \"what's my name?\",\n * chat_history: [\n * new HumanMessage({content: \"hi! my name is bob\"}),\n * new AIMessage({content: \"Hello Bob! How can I assist you today?\"}),\n * ],\n * }\n * );\n * ```\n */\nexport function createToolCallingAgent({\n llm,\n tools,\n prompt,\n streamRunnable,\n}: CreateToolCallingAgentParams) {\n if (!prompt.inputVariables.includes(\"agent_scratchpad\")) {\n throw new Error(\n [\n `Prompt must have an input variable named \"agent_scratchpad\".`,\n `Found ${JSON.stringify(prompt.inputVariables)} instead.`,\n ].join(\"\\n\")\n );\n }\n let modelWithTools;\n if (_isBaseChatModel(llm)) {\n if (llm.bindTools === undefined) {\n throw new Error(\n `This agent requires that the \"bind_tools()\" method be implemented on the input model.`\n );\n }\n modelWithTools = llm.bindTools(tools);\n } else {\n modelWithTools = llm;\n }\n\n const agent = AgentRunnableSequence.fromRunnables(\n [\n RunnablePassthrough.assign({\n agent_scratchpad: (input: { steps: ToolsAgentStep[] }) =>\n formatToToolMessages(input.steps),\n }),\n prompt,\n modelWithTools,\n new ToolCallingAgentOutputParser(),\n ],\n {\n name: \"ToolCallingAgent\",\n streamRunnable,\n singleAction: false,\n }\n );\n return agent;\n}\n"],"mappings":";;;;;AAeA,SAAS,iBAAiB,GAA0C;CAClE,MAAM,QAAQ;AACd,QACE,OAAO,MAAM,eAAe,cAC5B,MAAM,YAAY,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2E3B,SAAgB,uBAAuB,EACrC,KACA,OACA,QACA,kBAC+B;AAC/B,KAAI,CAAC,OAAO,eAAe,SAAS,mBAAmB,CACrD,OAAM,IAAI,MACR,CACE,gEACA,SAAS,KAAK,UAAU,OAAO,eAAe,CAAC,WAChD,CAAC,KAAK,KAAK,CACb;CAEH,IAAI;AACJ,KAAI,iBAAiB,IAAI,EAAE;AACzB,MAAI,IAAI,cAAc,KAAA,EACpB,OAAM,IAAI,MACR,wFACD;AAEH,mBAAiB,IAAI,UAAU,MAAM;OAErC,kBAAiB;AAmBnB,QAhBc,sBAAsB,cAClC;EACE,oBAAoB,OAAO,EACzB,mBAAmB,UACjB,qBAAqB,MAAM,MAAM,EACpC,CAAC;EACF;EACA;EACA,IAAI,8BAA8B;EACnC,EACD;EACE,MAAM;EACN;EACA,cAAc;EACf,
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/agents/tool_calling/index.ts"],"sourcesContent":["import { ChatPromptTemplate } from \"@langchain/core/prompts\";\nimport { StructuredToolInterface } from \"@langchain/core/tools\";\nimport { RunnablePassthrough } from \"@langchain/core/runnables\";\nimport {\n LanguageModelLike,\n ToolDefinition,\n} from \"@langchain/core/language_models/base\";\nimport { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport { AgentRunnableSequence } from \"../agent.js\";\nimport {\n ToolCallingAgentOutputParser,\n ToolsAgentStep,\n} from \"./output_parser.js\";\nimport { formatToToolMessages } from \"../format_scratchpad/tool_calling.js\";\n\nfunction _isBaseChatModel(x: LanguageModelLike): x is BaseChatModel {\n const model = x as BaseChatModel;\n return (\n typeof model._modelType === \"function\" &&\n model._modelType() === \"base_chat_model\"\n );\n}\n\n/**\n * Params used by the createOpenAIToolsAgent function.\n */\nexport type CreateToolCallingAgentParams = {\n /**\n * LLM to use as the agent. Should work with OpenAI tool calling,\n * so must either be an OpenAI model that supports that or a wrapper of\n * a different model that adds in equivalent support.\n */\n llm: LanguageModelLike;\n /** Tools this agent has access to. */\n tools: StructuredToolInterface[] | ToolDefinition[];\n /** The prompt to use, must have an input key of `agent_scratchpad`. */\n prompt: ChatPromptTemplate;\n /**\n * Whether to invoke the underlying model in streaming mode,\n * allowing streaming of intermediate steps. Defaults to true.\n */\n streamRunnable?: boolean;\n};\n\n/**\n * Create an agent that uses tools.\n * @param params Params required to create the agent. Includes an LLM, tools, and prompt.\n * @returns A runnable sequence representing an agent. It takes as input all the same input\n * variables as the prompt passed in does. It returns as output either an\n * AgentAction or AgentFinish.\n * @example\n * ```typescript\n * import { ChatAnthropic } from \"@langchain/anthropic\";\n * import { ChatPromptTemplate, MessagesPlaceholder } from \"@langchain/core/prompts\";\n * import { AgentExecutor, createToolCallingAgent } from \"langchain/agents\";\n *\n * const prompt = ChatPromptTemplate.fromMessages(\n * [\n * [\"system\", \"You are a helpful assistant\"],\n * [\"placeholder\", \"{chat_history}\"],\n * [\"human\", \"{input}\"],\n * [\"placeholder\", \"{agent_scratchpad}\"],\n * ]\n * );\n *\n *\n * const llm = new ChatAnthropic({\n * modelName: \"claude-3-opus-20240229\",\n * temperature: 0,\n * });\n *\n * // Define the tools the agent will have access to.\n * const tools = [...];\n *\n * const agent = createToolCallingAgent({ llm, tools, prompt });\n *\n * const agentExecutor = new AgentExecutor({ agent, tools });\n *\n * const result = await agentExecutor.invoke({input: \"what is LangChain?\"});\n *\n * // Using with chat history\n * import { AIMessage, HumanMessage } from \"@langchain/core/messages\";\n *\n * const result2 = await agentExecutor.invoke(\n * {\n * input: \"what's my name?\",\n * chat_history: [\n * new HumanMessage({content: \"hi! my name is bob\"}),\n * new AIMessage({content: \"Hello Bob! How can I assist you today?\"}),\n * ],\n * }\n * );\n * ```\n */\nexport function createToolCallingAgent({\n llm,\n tools,\n prompt,\n streamRunnable,\n}: CreateToolCallingAgentParams) {\n if (!prompt.inputVariables.includes(\"agent_scratchpad\")) {\n throw new Error(\n [\n `Prompt must have an input variable named \"agent_scratchpad\".`,\n `Found ${JSON.stringify(prompt.inputVariables)} instead.`,\n ].join(\"\\n\")\n );\n }\n let modelWithTools;\n if (_isBaseChatModel(llm)) {\n if (llm.bindTools === undefined) {\n throw new Error(\n `This agent requires that the \"bind_tools()\" method be implemented on the input model.`\n );\n }\n modelWithTools = llm.bindTools(tools);\n } else {\n modelWithTools = llm;\n }\n\n const agent = AgentRunnableSequence.fromRunnables(\n [\n RunnablePassthrough.assign({\n agent_scratchpad: (input: { steps: ToolsAgentStep[] }) =>\n formatToToolMessages(input.steps),\n }),\n prompt,\n modelWithTools,\n new ToolCallingAgentOutputParser(),\n ],\n {\n name: \"ToolCallingAgent\",\n streamRunnable,\n singleAction: false,\n }\n );\n return agent;\n}\n"],"mappings":";;;;;AAeA,SAAS,iBAAiB,GAA0C;CAClE,MAAM,QAAQ;AACd,QACE,OAAO,MAAM,eAAe,cAC5B,MAAM,YAAY,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2E3B,SAAgB,uBAAuB,EACrC,KACA,OACA,QACA,kBAC+B;AAC/B,KAAI,CAAC,OAAO,eAAe,SAAS,mBAAmB,CACrD,OAAM,IAAI,MACR,CACE,gEACA,SAAS,KAAK,UAAU,OAAO,eAAe,CAAC,WAChD,CAAC,KAAK,KAAK,CACb;CAEH,IAAI;AACJ,KAAI,iBAAiB,IAAI,EAAE;AACzB,MAAI,IAAI,cAAc,KAAA,EACpB,OAAM,IAAI,MACR,wFACD;AAEH,mBAAiB,IAAI,UAAU,MAAM;OAErC,kBAAiB;AAmBnB,QAhBc,sBAAsB,cAClC;EACE,oBAAoB,OAAO,EACzB,mBAAmB,UACjB,qBAAqB,MAAM,MAAM,EACpC,CAAC;EACF;EACA;EACA,IAAI,8BAA8B;EACnC,EACD;EACE,MAAM;EACN;EACA,cAAc;EACf,CAES"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai_functions.cjs","names":["OpenAIAgentTokenBufferMemory","ConversationSummaryBufferMemory","initializeAgentExecutorWithOptions"],"sources":["../../../../src/agents/toolkits/conversational_retrieval/openai_functions.ts"],"sourcesContent":["import { StructuredToolInterface } from \"@langchain/core/tools\";\nimport { ChatOpenAI } from \"@langchain/openai\";\nimport { ConversationSummaryBufferMemory } from \"../../../memory/summary_buffer.js\";\nimport { initializeAgentExecutorWithOptions } from \"../../initialize.js\";\nimport { OpenAIAgentTokenBufferMemory } from \"./token_buffer_memory.js\";\n\nexport type ConversationalRetrievalAgentOptions = {\n rememberIntermediateSteps?: boolean;\n memoryKey?: string;\n outputKey?: string;\n inputKey?: string;\n prefix?: string;\n verbose?: boolean;\n};\n\n/**\n * Asynchronous function that creates a conversational retrieval agent\n * using a language model, tools, and options. It initializes the buffer\n * memory based on the provided options and initializes the AgentExecutor\n * with the tools, language model, and memory.\n * @param llm Instance of ChatOpenAI used as the language model for the agent.\n * @param tools Array of StructuredTool instances used by the agent.\n * @param options Optional ConversationalRetrievalAgentOptions to customize the agent.\n * @returns A Promise that resolves to an initialized AgentExecutor.\n */\nexport async function createConversationalRetrievalAgent(\n llm: ChatOpenAI,\n tools: StructuredToolInterface[],\n options?: ConversationalRetrievalAgentOptions\n) {\n const {\n rememberIntermediateSteps = true,\n memoryKey = \"chat_history\",\n outputKey = \"output\",\n inputKey = \"input\",\n prefix,\n verbose,\n } = options ?? {};\n let memory;\n if (rememberIntermediateSteps) {\n memory = new OpenAIAgentTokenBufferMemory({\n memoryKey,\n llm,\n outputKey,\n inputKey,\n });\n } else {\n memory = new ConversationSummaryBufferMemory({\n memoryKey,\n llm,\n maxTokenLimit: 12000,\n returnMessages: true,\n outputKey,\n inputKey,\n });\n }\n const executor = await initializeAgentExecutorWithOptions(tools, llm, {\n agentType: \"openai-functions\",\n memory,\n verbose,\n returnIntermediateSteps: rememberIntermediateSteps,\n agentArgs: {\n prefix:\n prefix ??\n `Do your best to answer the questions. Feel free to use any tools available to look up relevant information, only if necessary.`,\n },\n });\n return executor;\n}\n"],"mappings":";;;;;;;;;;;;;;AAyBA,eAAsB,mCACpB,KACA,OACA,SACA;CACA,MAAM,EACJ,4BAA4B,MAC5B,YAAY,gBACZ,YAAY,UACZ,WAAW,SACX,QACA,YACE,WAAW,EAAE;CACjB,IAAI;AACJ,KAAI,0BACF,UAAS,IAAIA,4BAAAA,6BAA6B;EACxC;EACA;EACA;EACA;EACD,CAAC;KAEF,UAAS,IAAIC,uBAAAA,gCAAgC;EAC3C;EACA;EACA,eAAe;EACf,gBAAgB;EAChB;EACA;EACD,CAAC;AAaJ,
|
|
1
|
+
{"version":3,"file":"openai_functions.cjs","names":["OpenAIAgentTokenBufferMemory","ConversationSummaryBufferMemory","initializeAgentExecutorWithOptions"],"sources":["../../../../src/agents/toolkits/conversational_retrieval/openai_functions.ts"],"sourcesContent":["import { StructuredToolInterface } from \"@langchain/core/tools\";\nimport { ChatOpenAI } from \"@langchain/openai\";\nimport { ConversationSummaryBufferMemory } from \"../../../memory/summary_buffer.js\";\nimport { initializeAgentExecutorWithOptions } from \"../../initialize.js\";\nimport { OpenAIAgentTokenBufferMemory } from \"./token_buffer_memory.js\";\n\nexport type ConversationalRetrievalAgentOptions = {\n rememberIntermediateSteps?: boolean;\n memoryKey?: string;\n outputKey?: string;\n inputKey?: string;\n prefix?: string;\n verbose?: boolean;\n};\n\n/**\n * Asynchronous function that creates a conversational retrieval agent\n * using a language model, tools, and options. It initializes the buffer\n * memory based on the provided options and initializes the AgentExecutor\n * with the tools, language model, and memory.\n * @param llm Instance of ChatOpenAI used as the language model for the agent.\n * @param tools Array of StructuredTool instances used by the agent.\n * @param options Optional ConversationalRetrievalAgentOptions to customize the agent.\n * @returns A Promise that resolves to an initialized AgentExecutor.\n */\nexport async function createConversationalRetrievalAgent(\n llm: ChatOpenAI,\n tools: StructuredToolInterface[],\n options?: ConversationalRetrievalAgentOptions\n) {\n const {\n rememberIntermediateSteps = true,\n memoryKey = \"chat_history\",\n outputKey = \"output\",\n inputKey = \"input\",\n prefix,\n verbose,\n } = options ?? {};\n let memory;\n if (rememberIntermediateSteps) {\n memory = new OpenAIAgentTokenBufferMemory({\n memoryKey,\n llm,\n outputKey,\n inputKey,\n });\n } else {\n memory = new ConversationSummaryBufferMemory({\n memoryKey,\n llm,\n maxTokenLimit: 12000,\n returnMessages: true,\n outputKey,\n inputKey,\n });\n }\n const executor = await initializeAgentExecutorWithOptions(tools, llm, {\n agentType: \"openai-functions\",\n memory,\n verbose,\n returnIntermediateSteps: rememberIntermediateSteps,\n agentArgs: {\n prefix:\n prefix ??\n `Do your best to answer the questions. Feel free to use any tools available to look up relevant information, only if necessary.`,\n },\n });\n return executor;\n}\n"],"mappings":";;;;;;;;;;;;;;AAyBA,eAAsB,mCACpB,KACA,OACA,SACA;CACA,MAAM,EACJ,4BAA4B,MAC5B,YAAY,gBACZ,YAAY,UACZ,WAAW,SACX,QACA,YACE,WAAW,EAAE;CACjB,IAAI;AACJ,KAAI,0BACF,UAAS,IAAIA,4BAAAA,6BAA6B;EACxC;EACA;EACA;EACA;EACD,CAAC;KAEF,UAAS,IAAIC,uBAAAA,gCAAgC;EAC3C;EACA;EACA,eAAe;EACf,gBAAgB;EAChB;EACA;EACD,CAAC;AAaJ,QAAO,MAXgBC,mBAAAA,mCAAmC,OAAO,KAAK;EACpE,WAAW;EACX;EACA;EACA,yBAAyB;EACzB,WAAW,EACT,QACE,UACA,kIACH;EACF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai_functions.js","names":[],"sources":["../../../../src/agents/toolkits/conversational_retrieval/openai_functions.ts"],"sourcesContent":["import { StructuredToolInterface } from \"@langchain/core/tools\";\nimport { ChatOpenAI } from \"@langchain/openai\";\nimport { ConversationSummaryBufferMemory } from \"../../../memory/summary_buffer.js\";\nimport { initializeAgentExecutorWithOptions } from \"../../initialize.js\";\nimport { OpenAIAgentTokenBufferMemory } from \"./token_buffer_memory.js\";\n\nexport type ConversationalRetrievalAgentOptions = {\n rememberIntermediateSteps?: boolean;\n memoryKey?: string;\n outputKey?: string;\n inputKey?: string;\n prefix?: string;\n verbose?: boolean;\n};\n\n/**\n * Asynchronous function that creates a conversational retrieval agent\n * using a language model, tools, and options. It initializes the buffer\n * memory based on the provided options and initializes the AgentExecutor\n * with the tools, language model, and memory.\n * @param llm Instance of ChatOpenAI used as the language model for the agent.\n * @param tools Array of StructuredTool instances used by the agent.\n * @param options Optional ConversationalRetrievalAgentOptions to customize the agent.\n * @returns A Promise that resolves to an initialized AgentExecutor.\n */\nexport async function createConversationalRetrievalAgent(\n llm: ChatOpenAI,\n tools: StructuredToolInterface[],\n options?: ConversationalRetrievalAgentOptions\n) {\n const {\n rememberIntermediateSteps = true,\n memoryKey = \"chat_history\",\n outputKey = \"output\",\n inputKey = \"input\",\n prefix,\n verbose,\n } = options ?? {};\n let memory;\n if (rememberIntermediateSteps) {\n memory = new OpenAIAgentTokenBufferMemory({\n memoryKey,\n llm,\n outputKey,\n inputKey,\n });\n } else {\n memory = new ConversationSummaryBufferMemory({\n memoryKey,\n llm,\n maxTokenLimit: 12000,\n returnMessages: true,\n outputKey,\n inputKey,\n });\n }\n const executor = await initializeAgentExecutorWithOptions(tools, llm, {\n agentType: \"openai-functions\",\n memory,\n verbose,\n returnIntermediateSteps: rememberIntermediateSteps,\n agentArgs: {\n prefix:\n prefix ??\n `Do your best to answer the questions. Feel free to use any tools available to look up relevant information, only if necessary.`,\n },\n });\n return executor;\n}\n"],"mappings":";;;;;;;;;;;;;;AAyBA,eAAsB,mCACpB,KACA,OACA,SACA;CACA,MAAM,EACJ,4BAA4B,MAC5B,YAAY,gBACZ,YAAY,UACZ,WAAW,SACX,QACA,YACE,WAAW,EAAE;CACjB,IAAI;AACJ,KAAI,0BACF,UAAS,IAAI,6BAA6B;EACxC;EACA;EACA;EACA;EACD,CAAC;KAEF,UAAS,IAAI,gCAAgC;EAC3C;EACA;EACA,eAAe;EACf,gBAAgB;EAChB;EACA;EACD,CAAC;AAaJ,
|
|
1
|
+
{"version":3,"file":"openai_functions.js","names":[],"sources":["../../../../src/agents/toolkits/conversational_retrieval/openai_functions.ts"],"sourcesContent":["import { StructuredToolInterface } from \"@langchain/core/tools\";\nimport { ChatOpenAI } from \"@langchain/openai\";\nimport { ConversationSummaryBufferMemory } from \"../../../memory/summary_buffer.js\";\nimport { initializeAgentExecutorWithOptions } from \"../../initialize.js\";\nimport { OpenAIAgentTokenBufferMemory } from \"./token_buffer_memory.js\";\n\nexport type ConversationalRetrievalAgentOptions = {\n rememberIntermediateSteps?: boolean;\n memoryKey?: string;\n outputKey?: string;\n inputKey?: string;\n prefix?: string;\n verbose?: boolean;\n};\n\n/**\n * Asynchronous function that creates a conversational retrieval agent\n * using a language model, tools, and options. It initializes the buffer\n * memory based on the provided options and initializes the AgentExecutor\n * with the tools, language model, and memory.\n * @param llm Instance of ChatOpenAI used as the language model for the agent.\n * @param tools Array of StructuredTool instances used by the agent.\n * @param options Optional ConversationalRetrievalAgentOptions to customize the agent.\n * @returns A Promise that resolves to an initialized AgentExecutor.\n */\nexport async function createConversationalRetrievalAgent(\n llm: ChatOpenAI,\n tools: StructuredToolInterface[],\n options?: ConversationalRetrievalAgentOptions\n) {\n const {\n rememberIntermediateSteps = true,\n memoryKey = \"chat_history\",\n outputKey = \"output\",\n inputKey = \"input\",\n prefix,\n verbose,\n } = options ?? {};\n let memory;\n if (rememberIntermediateSteps) {\n memory = new OpenAIAgentTokenBufferMemory({\n memoryKey,\n llm,\n outputKey,\n inputKey,\n });\n } else {\n memory = new ConversationSummaryBufferMemory({\n memoryKey,\n llm,\n maxTokenLimit: 12000,\n returnMessages: true,\n outputKey,\n inputKey,\n });\n }\n const executor = await initializeAgentExecutorWithOptions(tools, llm, {\n agentType: \"openai-functions\",\n memory,\n verbose,\n returnIntermediateSteps: rememberIntermediateSteps,\n agentArgs: {\n prefix:\n prefix ??\n `Do your best to answer the questions. Feel free to use any tools available to look up relevant information, only if necessary.`,\n },\n });\n return executor;\n}\n"],"mappings":";;;;;;;;;;;;;;AAyBA,eAAsB,mCACpB,KACA,OACA,SACA;CACA,MAAM,EACJ,4BAA4B,MAC5B,YAAY,gBACZ,YAAY,UACZ,WAAW,SACX,QACA,YACE,WAAW,EAAE;CACjB,IAAI;AACJ,KAAI,0BACF,UAAS,IAAI,6BAA6B;EACxC;EACA;EACA;EACA;EACD,CAAC;KAEF,UAAS,IAAI,gCAAgC;EAC3C;EACA;EACA,eAAe;EACf,gBAAgB;EAChB;EACA;EACD,CAAC;AAaJ,QAAO,MAXgB,mCAAmC,OAAO,KAAK;EACpE,WAAW;EACX;EACA;EACA,yBAAyB;EACzB,WAAW,EACT,QACE,UACA,kIACH;EACF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.cjs","names":["formatDocumentsAsString","z","DynamicStructuredTool"],"sources":["../../../../src/agents/toolkits/conversational_retrieval/tool.ts"],"sourcesContent":["import type { BaseRetrieverInterface } from \"@langchain/core/retrievers\";\nimport { z } from \"zod\";\nimport { CallbackManagerForToolRun } from \"@langchain/core/callbacks/manager\";\nimport {\n DynamicStructuredTool,\n DynamicStructuredToolInput,\n} from \"@langchain/core/tools\";\nimport { formatDocumentsAsString } from \"../../../util/document.js\";\n\nexport function createRetrieverTool(\n retriever: BaseRetrieverInterface,\n input: Omit<DynamicStructuredToolInput, \"func\" | \"schema\">\n) {\n const func = async (\n { input }: { input: string },\n runManager?: CallbackManagerForToolRun\n ) => {\n const docs = await retriever.invoke(\n input,\n runManager?.getChild(\"retriever\")\n );\n return formatDocumentsAsString(docs);\n };\n const schema = z.object({\n input: z\n .string()\n .describe(\"Natural language query used as input to the retriever\"),\n });\n return new DynamicStructuredTool({ ...input, func, schema });\n}\n"],"mappings":";;;;;AASA,SAAgB,oBACd,WACA,OACA;CACA,MAAM,OAAO,OACX,EAAE,SACF,eACG;AAKH,SAAOA,sBAAAA,
|
|
1
|
+
{"version":3,"file":"tool.cjs","names":["formatDocumentsAsString","z","DynamicStructuredTool"],"sources":["../../../../src/agents/toolkits/conversational_retrieval/tool.ts"],"sourcesContent":["import type { BaseRetrieverInterface } from \"@langchain/core/retrievers\";\nimport { z } from \"zod\";\nimport { CallbackManagerForToolRun } from \"@langchain/core/callbacks/manager\";\nimport {\n DynamicStructuredTool,\n DynamicStructuredToolInput,\n} from \"@langchain/core/tools\";\nimport { formatDocumentsAsString } from \"../../../util/document.js\";\n\nexport function createRetrieverTool(\n retriever: BaseRetrieverInterface,\n input: Omit<DynamicStructuredToolInput, \"func\" | \"schema\">\n) {\n const func = async (\n { input }: { input: string },\n runManager?: CallbackManagerForToolRun\n ) => {\n const docs = await retriever.invoke(\n input,\n runManager?.getChild(\"retriever\")\n );\n return formatDocumentsAsString(docs);\n };\n const schema = z.object({\n input: z\n .string()\n .describe(\"Natural language query used as input to the retriever\"),\n });\n return new DynamicStructuredTool({ ...input, func, schema });\n}\n"],"mappings":";;;;;AASA,SAAgB,oBACd,WACA,OACA;CACA,MAAM,OAAO,OACX,EAAE,SACF,eACG;AAKH,SAAOA,sBAAAA,wBAAwB,MAJZ,UAAU,OAC3B,OACA,YAAY,SAAS,YAAY,CAClC,CACmC;;CAEtC,MAAM,SAASC,IAAAA,EAAE,OAAO,EACtB,OAAOA,IAAAA,EACJ,QAAQ,CACR,SAAS,wDAAwD,EACrE,CAAC;AACF,QAAO,IAAIC,sBAAAA,sBAAsB;EAAE,GAAG;EAAO;EAAM;EAAQ,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.js","names":[],"sources":["../../../../src/agents/toolkits/conversational_retrieval/tool.ts"],"sourcesContent":["import type { BaseRetrieverInterface } from \"@langchain/core/retrievers\";\nimport { z } from \"zod\";\nimport { CallbackManagerForToolRun } from \"@langchain/core/callbacks/manager\";\nimport {\n DynamicStructuredTool,\n DynamicStructuredToolInput,\n} from \"@langchain/core/tools\";\nimport { formatDocumentsAsString } from \"../../../util/document.js\";\n\nexport function createRetrieverTool(\n retriever: BaseRetrieverInterface,\n input: Omit<DynamicStructuredToolInput, \"func\" | \"schema\">\n) {\n const func = async (\n { input }: { input: string },\n runManager?: CallbackManagerForToolRun\n ) => {\n const docs = await retriever.invoke(\n input,\n runManager?.getChild(\"retriever\")\n );\n return formatDocumentsAsString(docs);\n };\n const schema = z.object({\n input: z\n .string()\n .describe(\"Natural language query used as input to the retriever\"),\n });\n return new DynamicStructuredTool({ ...input, func, schema });\n}\n"],"mappings":";;;;AASA,SAAgB,oBACd,WACA,OACA;CACA,MAAM,OAAO,OACX,EAAE,SACF,eACG;AAKH,SAAO,
|
|
1
|
+
{"version":3,"file":"tool.js","names":[],"sources":["../../../../src/agents/toolkits/conversational_retrieval/tool.ts"],"sourcesContent":["import type { BaseRetrieverInterface } from \"@langchain/core/retrievers\";\nimport { z } from \"zod\";\nimport { CallbackManagerForToolRun } from \"@langchain/core/callbacks/manager\";\nimport {\n DynamicStructuredTool,\n DynamicStructuredToolInput,\n} from \"@langchain/core/tools\";\nimport { formatDocumentsAsString } from \"../../../util/document.js\";\n\nexport function createRetrieverTool(\n retriever: BaseRetrieverInterface,\n input: Omit<DynamicStructuredToolInput, \"func\" | \"schema\">\n) {\n const func = async (\n { input }: { input: string },\n runManager?: CallbackManagerForToolRun\n ) => {\n const docs = await retriever.invoke(\n input,\n runManager?.getChild(\"retriever\")\n );\n return formatDocumentsAsString(docs);\n };\n const schema = z.object({\n input: z\n .string()\n .describe(\"Natural language query used as input to the retriever\"),\n });\n return new DynamicStructuredTool({ ...input, func, schema });\n}\n"],"mappings":";;;;AASA,SAAgB,oBACd,WACA,OACA;CACA,MAAM,OAAO,OACX,EAAE,SACF,eACG;AAKH,SAAO,wBAAwB,MAJZ,UAAU,OAC3B,OACA,YAAY,SAAS,YAAY,CAClC,CACmC;;CAEtC,MAAM,SAAS,EAAE,OAAO,EACtB,OAAO,EACJ,QAAQ,CACR,SAAS,wDAAwD,EACrE,CAAC;AACF,QAAO,IAAI,sBAAsB;EAAE,GAAG;EAAO;EAAM;EAAQ,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json.cjs","names":["BaseToolkit","JsonListKeysTool","JsonGetValueTool","JSON_PREFIX","JSON_SUFFIX","ZeroShotAgent","LLMChain","AgentExecutor"],"sources":["../../../../src/agents/toolkits/json/json.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { type ToolInterface, BaseToolkit } from \"@langchain/core/tools\";\nimport {\n JsonGetValueTool,\n JsonListKeysTool,\n JsonSpec,\n} from \"../../../tools/json.js\";\nimport { JSON_PREFIX, JSON_SUFFIX } from \"./prompt.js\";\nimport { LLMChain } from \"../../../chains/llm_chain.js\";\nimport { ZeroShotCreatePromptArgs, ZeroShotAgent } from \"../../mrkl/index.js\";\nimport { AgentExecutor } from \"../../executor.js\";\n\n/**\n * Represents a toolkit for working with JSON data. It initializes the\n * JSON tools based on the provided JSON specification.\n * @example\n * ```typescript\n * const toolkit = new JsonToolkit(new JsonSpec());\n * const executor = createJsonAgent(model, toolkit);\n * const result = await executor.invoke({\n * input: 'What are the required parameters in the request body to the /completions endpoint?'\n * });\n * ```\n */\nexport class JsonToolkit extends BaseToolkit {\n tools: ToolInterface[];\n\n constructor(public jsonSpec: JsonSpec) {\n super();\n this.tools = [\n new JsonListKeysTool(jsonSpec),\n new JsonGetValueTool(jsonSpec),\n ];\n }\n}\n\n/**\n * Creates a JSON agent using a language model, a JSON toolkit, and\n * optional prompt arguments. It creates a prompt for the agent using the\n * JSON tools and the provided prefix and suffix. It then creates a\n * ZeroShotAgent with the prompt and the JSON tools, and returns an\n * AgentExecutor for executing the agent with the tools.\n * @param llm The language model used to create the JSON agent.\n * @param toolkit The JSON toolkit used to create the JSON agent.\n * @param args Optional prompt arguments used to create the JSON agent.\n * @returns An AgentExecutor for executing the created JSON agent with the tools.\n */\nexport function createJsonAgent(\n llm: BaseLanguageModelInterface,\n toolkit: JsonToolkit,\n args?: ZeroShotCreatePromptArgs\n) {\n const {\n prefix = JSON_PREFIX,\n suffix = JSON_SUFFIX,\n inputVariables = [\"input\", \"agent_scratchpad\"],\n } = args ?? {};\n const { tools } = toolkit;\n const prompt = ZeroShotAgent.createPrompt(tools, {\n prefix,\n suffix,\n inputVariables,\n });\n const chain = new LLMChain({ prompt, llm });\n const agent = new ZeroShotAgent({\n llmChain: chain,\n allowedTools: tools.map((t) => t.name),\n });\n return AgentExecutor.fromAgentAndTools({\n agent,\n tools,\n returnIntermediateSteps: true,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAwBA,IAAa,cAAb,cAAiCA,sBAAAA,YAAY;CAC3C;CAEA,YAAY,UAA2B;AACrC,SAAO;AADU,OAAA,WAAA;AAEjB,OAAK,QAAQ,CACX,IAAIC,aAAAA,iBAAiB,SAAS,EAC9B,IAAIC,aAAAA,iBAAiB,SAAS,CAC/B;;;;;;;;;;;;;;AAeL,SAAgB,gBACd,KACA,SACA,MACA;CACA,MAAM,EACJ,SAASC,eAAAA,aACT,SAASC,eAAAA,aACT,iBAAiB,CAAC,SAAS,mBAAmB,KAC5C,QAAQ,EAAE;CACd,MAAM,EAAE,UAAU;CAOlB,MAAM,QAAQ,IAAIC,cAAAA,cAAc;EAC9B,
|
|
1
|
+
{"version":3,"file":"json.cjs","names":["BaseToolkit","JsonListKeysTool","JsonGetValueTool","JSON_PREFIX","JSON_SUFFIX","ZeroShotAgent","LLMChain","AgentExecutor"],"sources":["../../../../src/agents/toolkits/json/json.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { type ToolInterface, BaseToolkit } from \"@langchain/core/tools\";\nimport {\n JsonGetValueTool,\n JsonListKeysTool,\n JsonSpec,\n} from \"../../../tools/json.js\";\nimport { JSON_PREFIX, JSON_SUFFIX } from \"./prompt.js\";\nimport { LLMChain } from \"../../../chains/llm_chain.js\";\nimport { ZeroShotCreatePromptArgs, ZeroShotAgent } from \"../../mrkl/index.js\";\nimport { AgentExecutor } from \"../../executor.js\";\n\n/**\n * Represents a toolkit for working with JSON data. It initializes the\n * JSON tools based on the provided JSON specification.\n * @example\n * ```typescript\n * const toolkit = new JsonToolkit(new JsonSpec());\n * const executor = createJsonAgent(model, toolkit);\n * const result = await executor.invoke({\n * input: 'What are the required parameters in the request body to the /completions endpoint?'\n * });\n * ```\n */\nexport class JsonToolkit extends BaseToolkit {\n tools: ToolInterface[];\n\n constructor(public jsonSpec: JsonSpec) {\n super();\n this.tools = [\n new JsonListKeysTool(jsonSpec),\n new JsonGetValueTool(jsonSpec),\n ];\n }\n}\n\n/**\n * Creates a JSON agent using a language model, a JSON toolkit, and\n * optional prompt arguments. It creates a prompt for the agent using the\n * JSON tools and the provided prefix and suffix. It then creates a\n * ZeroShotAgent with the prompt and the JSON tools, and returns an\n * AgentExecutor for executing the agent with the tools.\n * @param llm The language model used to create the JSON agent.\n * @param toolkit The JSON toolkit used to create the JSON agent.\n * @param args Optional prompt arguments used to create the JSON agent.\n * @returns An AgentExecutor for executing the created JSON agent with the tools.\n */\nexport function createJsonAgent(\n llm: BaseLanguageModelInterface,\n toolkit: JsonToolkit,\n args?: ZeroShotCreatePromptArgs\n) {\n const {\n prefix = JSON_PREFIX,\n suffix = JSON_SUFFIX,\n inputVariables = [\"input\", \"agent_scratchpad\"],\n } = args ?? {};\n const { tools } = toolkit;\n const prompt = ZeroShotAgent.createPrompt(tools, {\n prefix,\n suffix,\n inputVariables,\n });\n const chain = new LLMChain({ prompt, llm });\n const agent = new ZeroShotAgent({\n llmChain: chain,\n allowedTools: tools.map((t) => t.name),\n });\n return AgentExecutor.fromAgentAndTools({\n agent,\n tools,\n returnIntermediateSteps: true,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAwBA,IAAa,cAAb,cAAiCA,sBAAAA,YAAY;CAC3C;CAEA,YAAY,UAA2B;AACrC,SAAO;AADU,OAAA,WAAA;AAEjB,OAAK,QAAQ,CACX,IAAIC,aAAAA,iBAAiB,SAAS,EAC9B,IAAIC,aAAAA,iBAAiB,SAAS,CAC/B;;;;;;;;;;;;;;AAeL,SAAgB,gBACd,KACA,SACA,MACA;CACA,MAAM,EACJ,SAASC,eAAAA,aACT,SAASC,eAAAA,aACT,iBAAiB,CAAC,SAAS,mBAAmB,KAC5C,QAAQ,EAAE;CACd,MAAM,EAAE,UAAU;CAOlB,MAAM,QAAQ,IAAIC,cAAAA,cAAc;EAC9B,UAAU,IAFMC,kBAAAA,SAAS;GAAE,QALdD,cAAAA,cAAc,aAAa,OAAO;IAC/C;IACA;IACA;IACD,CACkC;GAAE;GAAK,CAEzB;EACf,cAAc,MAAM,KAAK,MAAM,EAAE,KAAK;EACvC,CAAC;AACF,QAAOE,iBAAAA,cAAc,kBAAkB;EACrC;EACA;EACA,yBAAyB;EAC1B,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json.js","names":[],"sources":["../../../../src/agents/toolkits/json/json.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { type ToolInterface, BaseToolkit } from \"@langchain/core/tools\";\nimport {\n JsonGetValueTool,\n JsonListKeysTool,\n JsonSpec,\n} from \"../../../tools/json.js\";\nimport { JSON_PREFIX, JSON_SUFFIX } from \"./prompt.js\";\nimport { LLMChain } from \"../../../chains/llm_chain.js\";\nimport { ZeroShotCreatePromptArgs, ZeroShotAgent } from \"../../mrkl/index.js\";\nimport { AgentExecutor } from \"../../executor.js\";\n\n/**\n * Represents a toolkit for working with JSON data. It initializes the\n * JSON tools based on the provided JSON specification.\n * @example\n * ```typescript\n * const toolkit = new JsonToolkit(new JsonSpec());\n * const executor = createJsonAgent(model, toolkit);\n * const result = await executor.invoke({\n * input: 'What are the required parameters in the request body to the /completions endpoint?'\n * });\n * ```\n */\nexport class JsonToolkit extends BaseToolkit {\n tools: ToolInterface[];\n\n constructor(public jsonSpec: JsonSpec) {\n super();\n this.tools = [\n new JsonListKeysTool(jsonSpec),\n new JsonGetValueTool(jsonSpec),\n ];\n }\n}\n\n/**\n * Creates a JSON agent using a language model, a JSON toolkit, and\n * optional prompt arguments. It creates a prompt for the agent using the\n * JSON tools and the provided prefix and suffix. It then creates a\n * ZeroShotAgent with the prompt and the JSON tools, and returns an\n * AgentExecutor for executing the agent with the tools.\n * @param llm The language model used to create the JSON agent.\n * @param toolkit The JSON toolkit used to create the JSON agent.\n * @param args Optional prompt arguments used to create the JSON agent.\n * @returns An AgentExecutor for executing the created JSON agent with the tools.\n */\nexport function createJsonAgent(\n llm: BaseLanguageModelInterface,\n toolkit: JsonToolkit,\n args?: ZeroShotCreatePromptArgs\n) {\n const {\n prefix = JSON_PREFIX,\n suffix = JSON_SUFFIX,\n inputVariables = [\"input\", \"agent_scratchpad\"],\n } = args ?? {};\n const { tools } = toolkit;\n const prompt = ZeroShotAgent.createPrompt(tools, {\n prefix,\n suffix,\n inputVariables,\n });\n const chain = new LLMChain({ prompt, llm });\n const agent = new ZeroShotAgent({\n llmChain: chain,\n allowedTools: tools.map((t) => t.name),\n });\n return AgentExecutor.fromAgentAndTools({\n agent,\n tools,\n returnIntermediateSteps: true,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAwBA,IAAa,cAAb,cAAiC,YAAY;CAC3C;CAEA,YAAY,UAA2B;AACrC,SAAO;AADU,OAAA,WAAA;AAEjB,OAAK,QAAQ,CACX,IAAI,iBAAiB,SAAS,EAC9B,IAAI,iBAAiB,SAAS,CAC/B;;;;;;;;;;;;;;AAeL,SAAgB,gBACd,KACA,SACA,MACA;CACA,MAAM,EACJ,SAAS,aACT,SAAS,aACT,iBAAiB,CAAC,SAAS,mBAAmB,KAC5C,QAAQ,EAAE;CACd,MAAM,EAAE,UAAU;CAOlB,MAAM,QAAQ,IAAI,cAAc;EAC9B,
|
|
1
|
+
{"version":3,"file":"json.js","names":[],"sources":["../../../../src/agents/toolkits/json/json.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { type ToolInterface, BaseToolkit } from \"@langchain/core/tools\";\nimport {\n JsonGetValueTool,\n JsonListKeysTool,\n JsonSpec,\n} from \"../../../tools/json.js\";\nimport { JSON_PREFIX, JSON_SUFFIX } from \"./prompt.js\";\nimport { LLMChain } from \"../../../chains/llm_chain.js\";\nimport { ZeroShotCreatePromptArgs, ZeroShotAgent } from \"../../mrkl/index.js\";\nimport { AgentExecutor } from \"../../executor.js\";\n\n/**\n * Represents a toolkit for working with JSON data. It initializes the\n * JSON tools based on the provided JSON specification.\n * @example\n * ```typescript\n * const toolkit = new JsonToolkit(new JsonSpec());\n * const executor = createJsonAgent(model, toolkit);\n * const result = await executor.invoke({\n * input: 'What are the required parameters in the request body to the /completions endpoint?'\n * });\n * ```\n */\nexport class JsonToolkit extends BaseToolkit {\n tools: ToolInterface[];\n\n constructor(public jsonSpec: JsonSpec) {\n super();\n this.tools = [\n new JsonListKeysTool(jsonSpec),\n new JsonGetValueTool(jsonSpec),\n ];\n }\n}\n\n/**\n * Creates a JSON agent using a language model, a JSON toolkit, and\n * optional prompt arguments. It creates a prompt for the agent using the\n * JSON tools and the provided prefix and suffix. It then creates a\n * ZeroShotAgent with the prompt and the JSON tools, and returns an\n * AgentExecutor for executing the agent with the tools.\n * @param llm The language model used to create the JSON agent.\n * @param toolkit The JSON toolkit used to create the JSON agent.\n * @param args Optional prompt arguments used to create the JSON agent.\n * @returns An AgentExecutor for executing the created JSON agent with the tools.\n */\nexport function createJsonAgent(\n llm: BaseLanguageModelInterface,\n toolkit: JsonToolkit,\n args?: ZeroShotCreatePromptArgs\n) {\n const {\n prefix = JSON_PREFIX,\n suffix = JSON_SUFFIX,\n inputVariables = [\"input\", \"agent_scratchpad\"],\n } = args ?? {};\n const { tools } = toolkit;\n const prompt = ZeroShotAgent.createPrompt(tools, {\n prefix,\n suffix,\n inputVariables,\n });\n const chain = new LLMChain({ prompt, llm });\n const agent = new ZeroShotAgent({\n llmChain: chain,\n allowedTools: tools.map((t) => t.name),\n });\n return AgentExecutor.fromAgentAndTools({\n agent,\n tools,\n returnIntermediateSteps: true,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAwBA,IAAa,cAAb,cAAiC,YAAY;CAC3C;CAEA,YAAY,UAA2B;AACrC,SAAO;AADU,OAAA,WAAA;AAEjB,OAAK,QAAQ,CACX,IAAI,iBAAiB,SAAS,EAC9B,IAAI,iBAAiB,SAAS,CAC/B;;;;;;;;;;;;;;AAeL,SAAgB,gBACd,KACA,SACA,MACA;CACA,MAAM,EACJ,SAAS,aACT,SAAS,aACT,iBAAiB,CAAC,SAAS,mBAAmB,KAC5C,QAAQ,EAAE;CACd,MAAM,EAAE,UAAU;CAOlB,MAAM,QAAQ,IAAI,cAAc;EAC9B,UAAU,IAFM,SAAS;GAAE,QALd,cAAc,aAAa,OAAO;IAC/C;IACA;IACA;IACD,CACkC;GAAE;GAAK,CAEzB;EACf,cAAc,MAAM,KAAK,MAAM,EAAE,KAAK;EACvC,CAAC;AACF,QAAO,cAAc,kBAAkB;EACrC;EACA;EACA,yBAAyB;EAC1B,CAAC"}
|