{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## References\n", "\n", "[RAG](https://python.langchain.com/docs/expression_language/cookbook/retrieval) \n", "\n", "[runnanbles - API](https://api.python.langchain.com/en/latest/core_api_reference.html#module-langchain_core.runnables) \n", "[RunnableParallel](https://python.langchain.com/docs/expression_language/how_to/map) \n", "[RunnablePassthrough](https://python.langchain.com/docs/expression_language/how_to/passthrough) \n", "\n", "[memory - API](https://api.python.langchain.com/en/latest/langchain_api_reference.html#module-langchain.memory) \n", "[Chat with history](https://python.langchain.com/docs/use_cases/question_answering/chat_history) \n", "[]() \n", "[]() \n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import os\n", "import gradio as gr\n", "\n", "from operator import itemgetter\n", "\n", "# Langchain\n", "from langchain.chains import RetrievalQA\n", "from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder, PromptTemplate\n", "from langchain_core.runnables import RunnableParallel,RunnablePassthrough,RunnableLambda\n", "from langchain_core.output_parsers import StrOutputParser\n", "from langchain_core.messages import AIMessage, HumanMessage, get_buffer_string\n", "from langchain.schema import format_document\n", "\n", "# Conversation memory\n", "from langchain.memory.buffer_window import ConversationBufferWindowMemory\n", "from langchain.memory import ConversationBufferMemory\n", "\n", "\n", "# HuggingFace\n", "from langchain_community.embeddings import HuggingFaceEmbeddings\n", "\n", "# GeminiPro\n", "from langchain_google_genai import ChatGoogleGenerativeAI\n", "\n", "# Groq\n", "from langchain_groq import ChatGroq\n", "\n", "# Pinecone vector database\n", "from pinecone import Pinecone, ServerlessSpec\n", "from langchain_pinecone import PineconeVectorStore\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Select an LLM model" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "# ChatGPT\n", "# model = ChatOpenAI(temperature=0.0)\n", "\n", "# Gemini\n", "# model = ChatGoogleGenerativeAI(\n", "# model=\"gemini-pro\", temperature=0.1, convert_system_message_to_human=True\n", "# )\n", "\n", "# Groq\n", "# llama2-70b-4096 (4k), mixtral-8x7b-32768 (32k)\n", "model = ChatGroq(model_name='mixtral-8x7b-32768')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Embeddings and vector store" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "\n", "setid = \"global\"\n", "\n", "embeddings = HuggingFaceEmbeddings(model_name=os.getenv(\"EMBEDDINGS_MODEL\"))\n", " \n", "pc = Pinecone( api_key=os.getenv(\"PINECONE_API_KEY\") )\n", "index = pc.Index(setid)\n", "vectorstore = PineconeVectorStore(index, embeddings, \"text\")\n", "retriever = vectorstore.as_retriever(kwargs={\"k\":5}) # Find 5 documents\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Prompts" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "template_no_history = \"\"\"Answer the question based only on the following context:\n", "{context}\n", "\n", "Question: {question}\n", "\"\"\"\n", "PROMPT_NH = ChatPromptTemplate.from_template(template_no_history)\n", "\n", "template_with_history = \"\"\"Given the following conversation history, answer the follow up question:\n", "Chat History:\n", "{chat_history}\n", "\n", "Question: {question}\n", "\"\"\"\n", "PROMPT_WH = ChatPromptTemplate.from_template(template_with_history)\n" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "content='Based on the provided document, a blockchain is a type of distributed ledger technology that implements a decentralized, fully replicated append-only ledger in a peer-to-peer network. It consists of a chain of blocks, where each block contains a list of validated and timestamped transactions. Blockchain technology is known for its secure and immutable record-keeping of digital transactions, as well as its resistance to tampering and censorship due to its decentralized nature. In a blockchain network, multiple participants, or nodes, maintain copies of the ledger, and processing and verifying transactions are the responsibility of every node. Blockchain technology can be classified as public, private/permissioned, or hybrid.' response_metadata={'token_usage': {'completion_time': 0.269, 'completion_tokens': 151, 'prompt_time': 1.5510000000000002, 'prompt_tokens': 1712, 'queue_time': None, 'total_time': 1.8200000000000003, 'total_tokens': 1863}, 'model_name': 'mixtral-8x7b-32768', 'system_fingerprint': 'fp_13a4b82d64', 'finish_reason': 'stop', 'logprobs': None}\n" ] } ], "source": [ "question = \"What is a blockchain?\"\n", "\n", "# chain = (\n", "# pipeLog \n", "# | { \"context\": vectorstore.as_retriever(kwargs={\"k\":5}), \"question\": RunnablePassthrough() }\n", "# | PROMPT_NH \n", "# | pipeLog \n", "# | model\n", "# )\n", "\n", "\n", "chain = (\n", " { \"context\": vectorstore.as_retriever(kwargs={\"k\": 5}), \"question\": RunnablePassthrough() }\n", " | PROMPT_NH\n", " | model\n", ")\n", "\n", "\n", "response = chain.invoke(question)\n", "print(response)\n" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Que es blockchain? : Blockchain es una cadena de bloques\\nPara que se usa : Para registrar transacciones\\n'" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "history = [ \n", " [\"Que es blockchain?\", \"Blockchain es una cadena de bloques\"],\n", " [\"Para que se usa\", \"Para registrar transacciones\"]\n", "]\n", "\n", "chat_history = \"\"\n", "for l in history:\n", " chat_history += \" : \".join(l)\n", " chat_history += \"\\n\"\n", "\n", "chat_history" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "AIMessage(content='En la tecnología de blockchain, \"consenso\" se refiere al mecanismo por el cual se llega a un acuerdo sobre el estado del registro distribuido. Hay varios algoritmos de consenso, como Proof of Work (PoW) y Proof of Stake (PoS), que se utilizan para asegurar la exactitud y la validez de las transacciones en la red blockchain. El algoritmo de consenso ayuda a evitar la duplicación de entradas y garantiza que las transacciones sean seguras y verificables.\\n\\nEn resumen, consenso en blockchain es el proceso de llegar a un acuerdo sobre el estado del registro distribuido, usando algoritmos para asegurar la exactitud y validez de las transacciones.', response_metadata={'token_usage': {'completion_time': 0.355, 'completion_tokens': 195, 'prompt_time': 0.063, 'prompt_tokens': 68, 'queue_time': None, 'total_time': 0.418, 'total_tokens': 263}, 'model_name': 'mixtral-8x7b-32768', 'system_fingerprint': 'fp_1cc6d039b0', 'finish_reason': 'stop', 'logprobs': None})" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "chain = (\n", " { \"chat_history\": itemgetter('chat_history'), \"question\": itemgetter('question') }\n", " | PROMPT_WH \n", " | model\n", ")\n", "response = chain.invoke({ \"chat_history\": chat_history, \"question\": \"Que es consenso?\"})\n", "response\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using parallel runnable jobs" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "def format_docs(docs):\n", " return \"\\n\\n\".join(doc.page_content for doc in docs)\n", "\n", "rag_chain_from_docs = (\n", " RunnablePassthrough.assign(context=(lambda x: format_docs(x[\"context\"])))\n", " | PROMPT_NH\n", " | model\n", " | StrOutputParser()\n", ")\n", "\n", "rag_chain_with_source = RunnableParallel(\n", " {\"context\": retriever, \"question\": RunnablePassthrough()}\n", ").assign(answer=rag_chain_from_docs)\n" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'context': [Document(page_content='2\\n\\nBackground\\n\\n2.1\\n\\nBlockchain technology\\n\\nThe blockchain technology implements a decentralized fully replicated append-only ledger in a\\npeer-to-peer network, originally employed for the Bitcoin cryptocurrency [7]. All participating\\nnodes maintain a full local copy of the blockchain. The blockchain consists of a sequence\\nof blocks containing the transactions of the ledger. Transactions inside blocks are sorted\\nchronologically and each block contains a cryptographic hash of the previous block in the\\nchain. Nodes create new blocks as they receives transactions, which are broadcast in the\\nnetwork. Once a block is complete, they start the consensus process to convince other nodes\\nto include it in the blockchain. In the original blockchain technology employed in Bitcoin\\nthe consensus process is based on Proof-of-Work (PoW) [7]. With PoW nodes compete with\\neach other in confirming transactions and creating new blocks by solving a mathematical\\npuzzle. While solving a block is a computational intensive task, verifying its validity is easy.\\nTo incentivize such mechanism, solving a block also results in mining a certain amount of\\n\\n\\x0cS. Bonomi, M. Casini, and C. Ciccotelli\\n\\n12:3', metadata={'chunk': 4.0, 'source': 'B-CoC-2020.txt'}),\n", " Document(page_content='2\\n\\nBackground\\n\\n2.1\\n\\nBlockchain technology\\n\\nThe blockchain technology implements a decentralized fully replicated append-only ledger in a\\npeer-to-peer network, originally employed for the Bitcoin cryptocurrency [7]. All participating\\nnodes maintain a full local copy of the blockchain. The blockchain consists of a sequence\\nof blocks containing the transactions of the ledger. Transactions inside blocks are sorted\\nchronologically and each block contains a cryptographic hash of the previous block in the\\nchain. Nodes create new blocks as they receives transactions, which are broadcast in the\\nnetwork. Once a block is complete, they start the consensus process to convince other nodes\\nto include it in the blockchain. In the original blockchain technology employed in Bitcoin\\nthe consensus process is based on Proof-of-Work (PoW) [7]. With PoW nodes compete with\\neach other in confirming transactions and creating new blocks by solving a mathematical\\npuzzle. While solving a block is a computational intensive task, verifying its validity is easy.\\nTo incentivize such mechanism, solving a block also results in mining a certain amount of\\n\\n\\x0cS. Bonomi, M. Casini, and C. Ciccotelli\\n\\n12:3', metadata={'chunk': 4.0, 'source': 'OASIcs-Tokenomics-2019-12.txt'}),\n", " Document(page_content='2.5. Components in blockchain technology\\nThe structure of a blockchain is a decentralized database consisting\\nof a chain of blocks that contain transactions, with each block linked to\\nthe previous one through cryptographic hashes, creating an immutable\\nand secure ledger of transactions as shown in Fig. 1. This structure en\\xad\\nables trust and transparency in the network by allowing participants to\\nverify and validate transactions without the need for intermediaries. The\\ncomponent used for blockchain technology are as follows:\\n(a) Node: A node in a blockchain network is a system, or it can be a\\nrouter or switch. It’s possible to create a dispersed network of\\nnodes with equal rights by using a P2P network. Processing and\\nverifying transactions are the exclusive responsibility of every\\nnode in the network [33].\\n(b) Transactions: Transactions are the smallest and most funda\\xad\\nmental part of the Blockchain. In blockchain technology, a record\\nacts as a transaction for payment history that includes the sender\\nand recipient address and a timestamp of the occurrence of a\\ntransaction. In a blockchain network, the storage, analysis, and\\nretrieval of completed transactions are important aspects of\\nmaintaining the integrity and transparency of the network [34].\\n(c) Block: The procedures for block validation are depicted by the\\nblock version number given to each block in the Blockchain. A\\ntimestamp value indicates when the particular block was\\n\\n2.4. Blockchain technology\\nBlockchain technology is a distributed ledger that is immutable,\\n4\\n\\n\\x0cSakshi et al.\\n\\nJournal of Information Security and Applications 77 (2023) 103579\\n\\nFig. 1. Blockchain Structure.', metadata={'chunk': 19.0, 'source': 'BlockchainBased-2023.txt'}),\n", " Document(page_content='The review was based on resources from four established scientific databases. A total\\nof 72 resources were found in these databases, of which 26 resources were fully analyzed\\nand provided evidence of the status of the research of blockchain-based solutions to solve\\nproblems related to the chain of custody of physical evidence and of how the current\\nliterature relates to the concept of physical evidence. The final selected resources (37%)\\nsufficiently represented a diverse range of perspectives and findings, enabling this article\\nto draw relevant conclusions and to contribute to the existing knowledge on the topic.\\nThe other sections of this paper are organized as follows. Section 2 provides the main\\nconcepts discussed in this paper, and Section 3 highlights current literature reviews focusing\\non the use of blockchain in the forensic field. Section 4 explains the research methodology.\\nSection 5 provides the results, and Section 6 the discussion. Finally, Section 7 presents the\\nlimitations and proposed future research and Section 8 concludes the paper.\\n2. Background\\nBlockchain technology has emerged as a disruptive innovation, providing a decentralized and transparent environment across various domains. Blockchain can be understood\\nas a distributed ledger technology that enables secure and immutable record-keeping of\\ndigital transactions. It comprises a chain of blocks, each containing a list of validated and\\ntime-stamped transactions. An interesting feature of blockchain is its decentralized nature,\\nwhere multiple participants, or nodes, maintain copies of the ledger. This distributed\\nconsensus mechanism ensures that no single entity has control over the entire network,\\nmaking it resistant to tampering and censorship. Thus, blockchain is ripe for contexts\\ninvolving multiple parties with a need for a reliable and trustworthy ambiance in the\\nregistering of sensitive information, since it can “allow for an audit trail of all operations\\ncarried out between peers without the need for a centralized authority” (Grima et al. 2021).\\nBlockchains can be classified as public, private/permissioned, or hybrid. Public\\nblockchain allows any interested party to be a node in the network and to participate in\\nthe consensus. Registered data can be viewed by members or non-members. In its turn,', metadata={'chunk': 3.0, 'source': 'ExploringBC-2023.txt'})],\n", " 'question': 'What is a blockchain?',\n", " 'answer': 'A blockchain is a decentralized fully replicated append-only ledger in a peer-to-peer network, consisting of a chain of blocks containing transactions of the ledger. Each block contains a cryptographic hash of the previous block in the chain, creating an immutable and secure ledger of transactions. The structure enables trust and transparency in the network by allowing participants to verify and validate transactions without the need for intermediaries. It comprises components such as nodes, transactions, and blocks. Nodes maintain a full local copy of the blockchain and are responsible for processing and verifying transactions. Transactions are the smallest and most fundamental part of the blockchain, while blocks are linked to the previous one through cryptographic hashes. The procedures for block validation are depicted by the block version number given to each block in the blockchain. A timestamp value indicates when the particular block was created.'}" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "response = rag_chain_with_source.invoke(\"What is a blockchain?\")\n", "response\n" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('What is a blockchain?',\n", " 'A blockchain is a decentralized fully replicated append-only ledger in a peer-to-peer network, consisting of a chain of blocks containing transactions of the ledger. Each block contains a cryptographic hash of the previous block in the chain, creating an immutable and secure ledger of transactions. The structure enables trust and transparency in the network by allowing participants to verify and validate transactions without the need for intermediaries. It comprises components such as nodes, transactions, and blocks. Nodes maintain a full local copy of the blockchain and are responsible for processing and verifying transactions. Transactions are the smallest and most fundamental part of the blockchain, while blocks are linked to the previous one through cryptographic hashes. The procedures for block validation are depicted by the block version number given to each block in the blockchain. A timestamp value indicates when the particular block was created.')" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "response['question'], response['answer']" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "B-CoC-2020.txt\n", "OASIcs-Tokenomics-2019-12.txt\n", "BlockchainBased-2023.txt\n", "ExploringBC-2023.txt\n" ] } ], "source": [ "for doc in response['context']:\n", " print( doc.metadata['source'] )" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['B-CoC-2020.txt',\n", " 'OASIcs-Tokenomics-2019-12.txt',\n", " 'BlockchainBased-2023.txt',\n", " 'ExploringBC-2023.txt']" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sources = [ doc.metadata['source'] for doc in response['context'] ]\n", "sources" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Examples from the documentation" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "rml_rag_prompt = \"\"\"HUMAN\n", "You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.\n", "Context: {context} \n", "Question: {question} \n", "Answer:\n", "\"\"\"\n", "RLM_RAG_PROMPT = ChatPromptTemplate.from_template(rml_rag_prompt)\n" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "def format_docs(docs):\n", " return \"\\n\\n\".join(doc.page_content for doc in docs)\n", "\n", "rag_chain = (\n", " {\"context\": retriever | format_docs, \"question\": RunnablePassthrough()}\n", " | RLM_RAG_PROMPT\n", " | model\n", " | StrOutputParser()\n", ")" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Data governance is the process of managing the availability, usability, integrity, and security of data in enterprise systems, based on internal data standards and policies. It ensures data is consistent, trustworthy, and not misused, and is critical for organizations due to increasing data privacy regulations and reliance on data analytics. A well-designed data governance program includes teams, a steering committee, and data stewards that create and enforce data standards. Effective data governance focuses on expected business benefits.'" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "rag_chain.invoke(\"What is Data Governance?\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Prompt with context" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'In the context of language models, \"large\" generally refers to a model that has a larger number of parameters, as compared to smaller models. This size typically allows the model to have a better understanding of complex language patterns and a wider range of topics, at the cost of increased computational requirements.'" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "contextualize_q_system_prompt = \"\"\"Given a chat history and the latest user question \\\n", "which might reference context in the chat history, formulate a standalone question \\\n", "which can be understood without the chat history. Do NOT answer the question, \\\n", "just reformulate it if needed and otherwise return it as is.\"\"\"\n", "\n", "contextualize_q_prompt = ChatPromptTemplate.from_messages(\n", " [\n", " (\"system\", contextualize_q_system_prompt),\n", " MessagesPlaceholder(variable_name=\"chat_history\"),\n", " (\"human\", \"{question}\"),\n", " ]\n", ")\n", "\n", "contextualize_q_chain = contextualize_q_prompt | model | StrOutputParser()\n", "\n", "contextualize_q_chain.invoke(\n", " {\n", " \"chat_history\": [\n", " HumanMessage(content=\"What does LLM stand for?\"),\n", " AIMessage(content=\"Large language model\"),\n", " ],\n", " \"question\": \"What is meant by large\",\n", " }\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Chain with chat history" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "qa_system_prompt = \"\"\"You are an assistant for question-answering tasks.\n", "Use the following pieces of retrieved context to answer the question.\n", "If you don't know the answer, just say that you don't know.\n", "Use three sentences maximum and keep the answer concise.\n", "\n", "{context}\"\"\"\n", "qa_prompt = ChatPromptTemplate.from_messages(\n", " [\n", " (\"system\", qa_system_prompt),\n", " MessagesPlaceholder(variable_name=\"chat_history\"),\n", " (\"human\", \"{question}\"),\n", " ]\n", ")\n", "\n", "\n", "def contextualized_question(input: dict):\n", " if input.get(\"chat_history\"):\n", " return contextualize_q_chain\n", " else:\n", " return input[\"question\"]\n", "\n", "\n", "rag_chain = (\n", " RunnablePassthrough.assign(\n", " context=contextualized_question | retriever | format_docs\n", " )\n", " | qa_prompt\n", " | model\n", ")" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "chat_history = []\n", "\n", "question = \"What is a Blockchain?\"\n", "ai_msg = rag_chain.invoke({\"question\": question, \"chat_history\": chat_history})\n", "chat_history.extend([HumanMessage(content=question), ai_msg])\n", "\n", "question = \"What are its benefits?\"\n", "ai_msg = rag_chain.invoke({\"question\": question, \"chat_history\": chat_history})\n", "chat_history.extend([HumanMessage(content=question), ai_msg])\n" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[HumanMessage(content='What is a Blockchain?'),\n", " AIMessage(content='A blockchain is a type of distributed ledger technology that consists of a chain of blocks, where each block contains a list of validated and time-stamped transactions. It is a decentralized system with a consensus mechanism, allowing multiple participants to maintain copies of the ledger, ensuring security, immutability, and transparency of recorded data. Blockchains can be classified as public, private/permissioned, or hybrid, each with different data access levels. The original blockchain technology was employed for the Bitcoin cryptocurrency and uses a consensus process based on Proof-of-Work (PoW).'),\n", " HumanMessage(content='What are its benefits?'),\n", " AIMessage(content=\"Blockchain technology offers several benefits, including:\\n\\n1. Transparency: Blockchain's public nature allows members and non-members to view and verify transactions, enhancing trust and accountability.\\n2. Immutability: Once data is recorded on the blockchain, it cannot be altered retroactively, ensuring data integrity and reliability.\\n3. Security: Advanced cryptographic algorithms protect the confidentiality and integrity of data, making it resistant to tampering and unauthorized access.\\n4. Decentralization: Blockchain eliminates the need for intermediaries, reducing costs and enhancing trust among participants.\\n5. Disintermediation: By removing central authorities, blockchain enables direct peer-to-peer interactions, streamlining processes and reducing costs.\\n6. Auditability: Blockchain provides a tamper-proof and time-stamped record of all transactions, facilitating auditing and compliance.\\n7. Programmability: Smart contracts, self-executing agreements with the terms directly written into code, can be deployed on blockchain, automating and streamlining complex processes.\\n\\nThese benefits make blockchain technology appealing for various applications, such as supply chain management, financial services, digital identity, and IoT solutions.\")]" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "chat_history" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Working with Runnable" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A> {'x': 'hola'}\n" ] }, { "data": { "text/plain": [ "{'x': 'hola'}" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def pipeLog(s:str, x):\n", " print(s, x)\n", " return x\n", "\n", "pipe_a = RunnableLambda(lambda x: pipeLog(\"A>\",x))\n", "pipe_b = RunnableLambda(lambda x: pipeLog(\"B>\",x))\n", "\n", "pipe_a.invoke({'x':\"hola\"})" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "rag_chain_with_source = RunnableParallel(\n", " {\"context\": itemgetter(\"question\")|retriever, \"question\": itemgetter(\"question\"), \"chat_history\": itemgetter(\"chat_history\") }\n", ").assign(answer=rag_chain)\n" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'context': [Document(page_content='the nodes present on the chain maintain a complete local copy of the blockchain. The\\nblockchain is an indigenous technology that has emerged for decentralized applications\\nas the outcome of complication, privacy, and security issues present in the applications\\nover half a century [3,4]. It is a peer-to-peer system that authorizes the users to maintain a\\nledger for various transactions that are reproduced, and remains identical in more than\\none location over multiple user servers [5].\\nA blockchain is essentially a block of chains, with the growing list of records referred\\nto as blocks that are joined with cryptography [4]. Each blockchain contains a hash of a\\nprevious block, and a timestamp that keeps track of the creation and modification time of', metadata={'chunk': 3.0, 'source': 'CustodyBlock-2021.txt'}),\n", " Document(page_content='customer information [14]. Blockchain is the core strength of IoT so\\xad\\nlutions to build a system with cryptographically protected records that\\nare reluctant to change and inaccuracy. Additionally, Blockchain faces\\nseveral crucial issues intrinsic to the Internet of Things, such as a large\\nnumber of IoT devices, a non-homogeneous network topology, limited\\ncomputational capacity, poor communication bandwidth, etc.', metadata={'chunk': 24.0, 'source': 'BlockchainBased-2023.txt'}),\n", " Document(page_content='as a distributed ledger technology that enables secure and immutable record-keeping of\\ndigital transactions. It comprises a chain of blocks, each containing a list of validated and\\ntime-stamped transactions. An interesting feature of blockchain is its decentralized nature,\\nwhere multiple participants, or nodes, maintain copies of the ledger. This distributed\\nconsensus mechanism ensures that no single entity has control over the entire network,\\nmaking it resistant to tampering and censorship. Thus, blockchain is ripe for contexts\\ninvolving multiple parties with a need for a reliable and trustworthy ambiance in the\\nregistering of sensitive information, since it can “allow for an audit trail of all operations\\ncarried out between peers without the need for a centralized authority” (Grima et al. 2021).\\nBlockchains can be classified as public, private/permissioned, or hybrid. Public\\nblockchain allows any interested party to be a node in the network and to participate in\\nthe consensus. Registered data can be viewed by members or non-members. In its turn,\\nprivate or permissioned blockchains only allow the participation of authorized members,\\nlimiting data access to such participants. Lastly, hybrid blockchains embed characteristics\\nof both public and private blockchains.\\nThe key features of blockchain include transparency, immutability, security, and decentralization of recorded data in the ledger data. In public blockchains, transparency is\\nachieved by its public nature, allowing members and non-members to view and verify', metadata={'chunk': 6.0, 'source': 'ExploringBC-2023.txt'}),\n", " Document(page_content='2\\n\\nBackground\\n\\n2.1\\n\\nBlockchain technology\\n\\nThe blockchain technology implements a decentralized fully replicated append-only ledger in a\\npeer-to-peer network, originally employed for the Bitcoin cryptocurrency [7]. All participating\\nnodes maintain a full local copy of the blockchain. The blockchain consists of a sequence\\nof blocks containing the transactions of the ledger. Transactions inside blocks are sorted\\nchronologically and each block contains a cryptographic hash of the previous block in the\\nchain. Nodes create new blocks as they receives transactions, which are broadcast in the\\nnetwork. Once a block is complete, they start the consensus process to convince other nodes\\nto include it in the blockchain. In the original blockchain technology employed in Bitcoin\\nthe consensus process is based on Proof-of-Work (PoW) [7]. With PoW nodes compete with\\neach other in confirming transactions and creating new blocks by solving a mathematical\\npuzzle. While solving a block is a computational intensive task, verifying its validity is easy.\\nTo incentivize such mechanism, solving a block also results in mining a certain amount of\\n\\n\\x0cS. Bonomi, M. Casini, and C. Ciccotelli\\n\\n12:3', metadata={'chunk': 5.0, 'source': 'B-CoC-2020.txt'})],\n", " 'question': 'What is a Blockchain?',\n", " 'chat_history': [],\n", " 'answer': AIMessage(content='A blockchain is a type of distributed ledger technology that consists of a chain of blocks, where each block contains a list of validated and time-stamped transactions. It is a decentralized system with a consensus mechanism, allowing multiple participants to maintain copies of the ledger, ensuring security, immutability, and transparency of recorded data. Blockchains can be classified as public, private/permissioned, or hybrid, each with different data access levels. The original blockchain technology was employed for the Bitcoin cryptocurrency and uses a consensus process based on Proof-of-Work (PoW).')}" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "chat_history = []\n", "\n", "question = \"What is a Blockchain?\"\n", "ai_msg = rag_chain_with_source.invoke({\"question\": question, \"chat_history\": chat_history})\n", "ai_msg\n" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A> {'question': 'Is this a question?', 'chat_history': []}\n" ] }, { "data": { "text/plain": [ "{'input': {'question': 'Is this a question?', 'chat_history': []},\n", " 'context': [Document(page_content='6 | Page', metadata={'chunk': 21.0, 'source': 'Gaia_X_Federation_Services_White_Paper_1_December_2021.txt'}),\n", " Document(page_content='in the general population of consumers.\\nIn conclusion, this is clearly at present merely the beginnings of a modest academic\\nproposal with, as can be seen, many details still to be worked out. However, we need to\\nstart thinking seriously about alternatives to the current stalemate in the legal debate\\nbetween the advocates of principled but impractical European data protection law versus\\nthe defenders of ineffective (and likely to stay that way) US privacy protection. We also', metadata={'chunk': 101.0, 'source': 'SSRN_id1857536.txt'}),\n", " Document(page_content='5 | Page', metadata={'chunk': 17.0, 'source': 'Gaia_X_Federation_Services_White_Paper_1_December_2021.txt'}),\n", " Document(page_content='Electronic copy available at: https://ssrn.com/abstract=1857536\\n\\n\\x0cAuthor queries\\n\\nInternational Review of Law Computers and Technology Vol. 18, No 3, paper 1\\n\\nThe Problem with Privacy: A Modest Proposal\\n\\nLilian Edwards\\n\\nQuery number\\n\\nQuery\\n\\n1\\n\\nPlease give MP3 in full.\\n\\n2\\n\\nIs European Community correct for EC?\\n\\n3\\n\\nChange to this sentence OK (to answer query HM1)?\\n\\n4\\n\\nPlease see comment HM2.\\n\\n5\\n\\nPlease see comment HM4.\\n\\n6\\n\\nPlease see comment HM6.\\n\\n7\\n\\nPlease give APACS in full.\\n\\n8\\n\\nChange to this sentence OK (to answer query HM8)?\\n\\n9\\n\\nChange of willing to unwilling correct? Also, please check that the end\\nof this sentence reads correctly.\\n\\n10\\n\\nPlease see comment HM9.\\n\\n11\\n\\nPlease define Art 25.\\n\\n12\\n\\nThere is a mixture of self regulation and self-regulation in this quote.\\nPlease check against the original.\\n\\n13\\n\\nPlease give MP3 in full.\\n\\n14\\n\\nPlease see comment HM10.\\n\\ndc-386881\\n\\n1\\nElectronic copy available at: https://ssrn.com/abstract=1857536\\n\\n\\x0c15\\n\\nPlease see comment HM11.\\n\\n16\\n\\nPlease give IP in full.\\n\\n17\\n\\nPlease see comment HM12.\\n\\n18\\n\\nPlease see comment HM13.\\n\\n19\\n\\nPlease see comment HM14.\\n\\n20\\n\\nPlease see comment HM15.\\n\\n21\\n\\nPlease give IP in full.\\n\\n22\\n\\nPlease give ICSTIS in full.\\n\\n23\\n\\nOnly 5 professors listed here. Please check.\\n\\n24\\n\\nPlease give GPA in full.\\n\\n25\\n\\nPlease give PRIME in full.\\n\\ndc-386881\\n\\n2\\nElectronic copy available at: https://ssrn.com/abstract=1857536', metadata={'chunk': 137.0, 'source': 'SSRN_id1857536.txt'})],\n", " 'question': 'Is this a question?'}" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "rp = RunnableParallel(\n", " {\"input\": pipe_a, \"context\": itemgetter(\"question\")|retriever, \"question\": itemgetter(\"question\") }\n", ")\n", "rp.invoke({ 'question': \"Is this a question?\", \"chat_history\": [] })" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'context': [Document(page_content='Tipo de activo', metadata={'chunk': 42.0, 'source': 'articles_237907_maestro_mspi.txt'}),\n", " Document(page_content='personales realizado por él mismo o por su cuenta. En particular, el responsable debe estar obligado a aplicar medidas oportunas\\ny eficaces y ha de poder demostrar la conformidad de las actividades de tratamiento con el presente Reglamento, incluida la eficacia\\nde las medidas. Dichas medidas deben tener en cuenta la naturaleza, el ámbito, el contexto y los fines del tratamiento, así como\\nel riesgo para los derechos y libertades de las personas físicas.”\\nPágina: 50 de 160', metadata={'chunk': 129.0, 'source': 'gestion_riesgo_y_evaluacion_impacto_en_tratamientos_datos_personales.txt'}),\n", " Document(page_content='de conseguir generar más datos, pues actualmente la generación de datos es muy escasa. Frente al\\nocéano que tenemos delante, solo estamos viendo el 6%. Además, faltan bases de datos estructuradas\\ny con unos datos estandarizados.\\nEstamos ante un sector muy heterogéneo, donde en algunas empresas falta digitalización, antes de\\npoder empezar con la generación de datos. Otra barrera que poco a poco se va superando es la falta\\nde confianza del sector, y el miedo a perder la ventaja competitiva que podría suponer el compartir\\nlos datos. Esto lleva a que actualmente se generen pocos datos agregados.\\n7.2.2.4 DSES Sanidad Animal\\nLa sanidad animal se considera un factor clave, tanto en el mantenimiento del bienestar de los\\nanimales de compañía, como para el desarrollo de la ganadería, y es de vital transcendencia tanto para\\nla economía nacional como para la salud pública, así como para el mantenimiento y conservación de\\nla diversidad de especies animales. Para la salud pública, por la posible transmisión de enfermedades\\nde los animales al hombre, y por los efectos nocivos que para éste puede provocar la utilización de\\ndeterminados productos con el fin de aumentar la productividad animal.', metadata={'chunk': 159.0, 'source': 'Interplataformas21_WhitePaper_DataSpaces.txt'}),\n", " Document(page_content='101\\n\\n\\x0cLanzar en un Grupo Reducido de Clientes\\nEs similar a los lanzamientos de productos en versión \"beta\" para que algunos clientes hagan comentarios al\\nrespecto. Un pequeño grupo de clientes debe ser el público objetivo. Esto no solo limita la exposición del\\nproyecto, sino que también brinda un resultado práctico de lo que puede ser la retroalimentación.\\nEsto también funciona perfectamente si la empresa tiene una buena base de seguidores que están dispuestos a\\nprobar productos nuevos. Y en la mayoría de los casos, todas las empresas tienen consumidores dedicados a\\neste tipo de prácticas.', metadata={'chunk': 204.0, 'source': 'Guia Referencia Proyectos Blockchain - MinTIC.txt'})],\n", " 'question': 'hola mundo'}" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "rag_chain_with_source = RunnableParallel(\n", " {\"context\": retriever, \"question\": RunnablePassthrough() }\n", ")\n", "rag_chain_with_source.invoke(\"hola mundo\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Handle Chat History\n", "\n", "[BaseChatMessageHistory](https://api.python.langchain.com/en/latest/chat_history/langchain_core.chat_history.BaseChatMessageHistory.html#langchain_core.chat_history.BaseChatMessageHistory) \n", "[]() \n", "[]() \n", "[]() \n" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "# chat_history = []\n", "# memory = ConversationBufferWindowMemory(k=10, input_key='question', output_key='answer')\n", "memory = ConversationBufferMemory(return_messages=True, input_key=\"question\", output_key=\"answer\")" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [], "source": [ "memory.clear()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Chains" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [], "source": [ "qa_system_prompt = \"\"\"You are an assistant for question-answering tasks.\n", "Use the following pieces of retrieved context to answer the question.\n", "If you don't know the answer, just say that you don't know.\n", "Keep the answer as concise and precise as possible.\n", "\n", "{context}\"\"\"\n", "qa_prompt = ChatPromptTemplate.from_messages(\n", " [\n", " (\"system\", qa_system_prompt),\n", " MessagesPlaceholder(variable_name=\"chat_history\"),\n", " (\"human\", \"{question}\"),\n", " ]\n", ")\n", "\n", "\n", "def contextualized_question(input: dict):\n", " if input.get(\"chat_history\"):\n", " return contextualize_q_chain\n", " else:\n", " return input[\"question\"]\n", "\n", "\n", "rag_chain = (\n", " RunnablePassthrough.assign(\n", " context=contextualized_question | retriever | format_docs\n", " )\n", " | qa_prompt\n", " | model\n", ")\n", "\n", "rag_chain_with_source = RunnableParallel(\n", " {\"context\": itemgetter(\"question\")|retriever, \"question\": itemgetter(\"question\"), \"chat_history\": itemgetter(\"chat_history\") }\n", ").assign(answer=rag_chain)\n" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "def run_query(question: str):\n", " ai_msg = rag_chain_with_source.invoke({\"question\": question, \"chat_history\": RunnableLambda(memory.load_memory_variables)})\n", " # chat_history.extend([ HumanMessage(content=question), ai_msg['answer'] ])\n", " memory.save_context(inputs=question, outputs={\"answer\": ai_msg[\"answer\"].content})\n", " print(ai_msg['answer'].content)\n", "\n" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "ename": "ValueError", "evalue": "variable chat_history should be a list of base messages, got {'history': []}", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[32], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43mrun_query\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mWhat is a Blockchain?\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n", "Cell \u001b[0;32mIn[31], line 2\u001b[0m, in \u001b[0;36mrun_query\u001b[0;34m(question)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mrun_query\u001b[39m(question: \u001b[38;5;28mstr\u001b[39m):\n\u001b[0;32m----> 2\u001b[0m ai_msg \u001b[38;5;241m=\u001b[39m \u001b[43mrag_chain_with_source\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43minvoke\u001b[49m\u001b[43m(\u001b[49m\u001b[43m{\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mquestion\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mquestion\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mchat_history\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mRunnableLambda\u001b[49m\u001b[43m(\u001b[49m\u001b[43mmemory\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mload_memory_variables\u001b[49m\u001b[43m)\u001b[49m\u001b[43m}\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 3\u001b[0m \u001b[38;5;66;03m# chat_history.extend([ HumanMessage(content=question), ai_msg['answer'] ])\u001b[39;00m\n\u001b[1;32m 4\u001b[0m memory\u001b[38;5;241m.\u001b[39msave_context(inputs\u001b[38;5;241m=\u001b[39mquestion, outputs\u001b[38;5;241m=\u001b[39m{\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124manswer\u001b[39m\u001b[38;5;124m\"\u001b[39m: ai_msg[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124manswer\u001b[39m\u001b[38;5;124m\"\u001b[39m]\u001b[38;5;241m.\u001b[39mcontent})\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/runnables/base.py:2056\u001b[0m, in \u001b[0;36mRunnableSequence.invoke\u001b[0;34m(self, input, config)\u001b[0m\n\u001b[1;32m 2054\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m 2055\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m i, step \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28menumerate\u001b[39m(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msteps):\n\u001b[0;32m-> 2056\u001b[0m \u001b[38;5;28minput\u001b[39m \u001b[38;5;241m=\u001b[39m \u001b[43mstep\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43minvoke\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 2057\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2058\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;66;43;03m# mark each step as a child run\u001b[39;49;00m\n\u001b[1;32m 2059\u001b[0m \u001b[43m \u001b[49m\u001b[43mpatch_config\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 2060\u001b[0m \u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mcallbacks\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mrun_manager\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mget_child\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43mf\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mseq:step:\u001b[39;49m\u001b[38;5;132;43;01m{\u001b[39;49;00m\u001b[43mi\u001b[49m\u001b[38;5;241;43m+\u001b[39;49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[38;5;132;43;01m}\u001b[39;49;00m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n\u001b[1;32m 2061\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2062\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 2063\u001b[0m \u001b[38;5;66;03m# finish the root run\u001b[39;00m\n\u001b[1;32m 2064\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/runnables/passthrough.py:419\u001b[0m, in \u001b[0;36mRunnableAssign.invoke\u001b[0;34m(self, input, config, **kwargs)\u001b[0m\n\u001b[1;32m 413\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21minvoke\u001b[39m(\n\u001b[1;32m 414\u001b[0m \u001b[38;5;28mself\u001b[39m,\n\u001b[1;32m 415\u001b[0m \u001b[38;5;28minput\u001b[39m: Dict[\u001b[38;5;28mstr\u001b[39m, Any],\n\u001b[1;32m 416\u001b[0m config: Optional[RunnableConfig] \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mNone\u001b[39;00m,\n\u001b[1;32m 417\u001b[0m \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs: Any,\n\u001b[1;32m 418\u001b[0m ) \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m>\u001b[39m Dict[\u001b[38;5;28mstr\u001b[39m, Any]:\n\u001b[0;32m--> 419\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_call_with_config\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_invoke\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/runnables/base.py:1243\u001b[0m, in \u001b[0;36mRunnable._call_with_config\u001b[0;34m(self, func, input, config, run_type, **kwargs)\u001b[0m\n\u001b[1;32m 1239\u001b[0m context \u001b[38;5;241m=\u001b[39m copy_context()\n\u001b[1;32m 1240\u001b[0m context\u001b[38;5;241m.\u001b[39mrun(var_child_runnable_config\u001b[38;5;241m.\u001b[39mset, child_config)\n\u001b[1;32m 1241\u001b[0m output \u001b[38;5;241m=\u001b[39m cast(\n\u001b[1;32m 1242\u001b[0m Output,\n\u001b[0;32m-> 1243\u001b[0m \u001b[43mcontext\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrun\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 1244\u001b[0m \u001b[43m \u001b[49m\u001b[43mcall_func_with_variable_args\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1245\u001b[0m \u001b[43m \u001b[49m\u001b[43mfunc\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;66;43;03m# type: ignore[arg-type]\u001b[39;49;00m\n\u001b[1;32m 1246\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;66;43;03m# type: ignore[arg-type]\u001b[39;49;00m\n\u001b[1;32m 1247\u001b[0m \u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1248\u001b[0m \u001b[43m \u001b[49m\u001b[43mrun_manager\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1249\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1250\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m,\n\u001b[1;32m 1251\u001b[0m )\n\u001b[1;32m 1252\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[1;32m 1253\u001b[0m run_manager\u001b[38;5;241m.\u001b[39mon_chain_error(e)\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/runnables/config.py:326\u001b[0m, in \u001b[0;36mcall_func_with_variable_args\u001b[0;34m(func, input, config, run_manager, **kwargs)\u001b[0m\n\u001b[1;32m 324\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m run_manager \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m accepts_run_manager(func):\n\u001b[1;32m 325\u001b[0m kwargs[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mrun_manager\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;241m=\u001b[39m run_manager\n\u001b[0;32m--> 326\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mfunc\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/runnables/passthrough.py:406\u001b[0m, in \u001b[0;36mRunnableAssign._invoke\u001b[0;34m(self, input, run_manager, config, **kwargs)\u001b[0m\n\u001b[1;32m 393\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21m_invoke\u001b[39m(\n\u001b[1;32m 394\u001b[0m \u001b[38;5;28mself\u001b[39m,\n\u001b[1;32m 395\u001b[0m \u001b[38;5;28minput\u001b[39m: Dict[\u001b[38;5;28mstr\u001b[39m, Any],\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 398\u001b[0m \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs: Any,\n\u001b[1;32m 399\u001b[0m ) \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m>\u001b[39m Dict[\u001b[38;5;28mstr\u001b[39m, Any]:\n\u001b[1;32m 400\u001b[0m \u001b[38;5;28;01massert\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(\n\u001b[1;32m 401\u001b[0m \u001b[38;5;28minput\u001b[39m, \u001b[38;5;28mdict\u001b[39m\n\u001b[1;32m 402\u001b[0m ), \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mThe input to RunnablePassthrough.assign() must be a dict.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 404\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m {\n\u001b[1;32m 405\u001b[0m \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39m\u001b[38;5;28minput\u001b[39m,\n\u001b[0;32m--> 406\u001b[0m \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mmapper\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43minvoke\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 407\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 408\u001b[0m \u001b[43m \u001b[49m\u001b[43mpatch_config\u001b[49m\u001b[43m(\u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mcallbacks\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mrun_manager\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mget_child\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 409\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 410\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m,\n\u001b[1;32m 411\u001b[0m }\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/runnables/base.py:2693\u001b[0m, in \u001b[0;36mRunnableParallel.invoke\u001b[0;34m(self, input, config)\u001b[0m\n\u001b[1;32m 2680\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m get_executor_for_config(config) \u001b[38;5;28;01mas\u001b[39;00m executor:\n\u001b[1;32m 2681\u001b[0m futures \u001b[38;5;241m=\u001b[39m [\n\u001b[1;32m 2682\u001b[0m executor\u001b[38;5;241m.\u001b[39msubmit(\n\u001b[1;32m 2683\u001b[0m step\u001b[38;5;241m.\u001b[39minvoke,\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 2691\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m key, step \u001b[38;5;129;01min\u001b[39;00m steps\u001b[38;5;241m.\u001b[39mitems()\n\u001b[1;32m 2692\u001b[0m ]\n\u001b[0;32m-> 2693\u001b[0m output \u001b[38;5;241m=\u001b[39m {key: future\u001b[38;5;241m.\u001b[39mresult() \u001b[38;5;28;01mfor\u001b[39;00m key, future \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mzip\u001b[39m(steps, futures)}\n\u001b[1;32m 2694\u001b[0m \u001b[38;5;66;03m# finish the root run\u001b[39;00m\n\u001b[1;32m 2695\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/runnables/base.py:2693\u001b[0m, in \u001b[0;36m\u001b[0;34m(.0)\u001b[0m\n\u001b[1;32m 2680\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m get_executor_for_config(config) \u001b[38;5;28;01mas\u001b[39;00m executor:\n\u001b[1;32m 2681\u001b[0m futures \u001b[38;5;241m=\u001b[39m [\n\u001b[1;32m 2682\u001b[0m executor\u001b[38;5;241m.\u001b[39msubmit(\n\u001b[1;32m 2683\u001b[0m step\u001b[38;5;241m.\u001b[39minvoke,\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 2691\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m key, step \u001b[38;5;129;01min\u001b[39;00m steps\u001b[38;5;241m.\u001b[39mitems()\n\u001b[1;32m 2692\u001b[0m ]\n\u001b[0;32m-> 2693\u001b[0m output \u001b[38;5;241m=\u001b[39m {key: \u001b[43mfuture\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mresult\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m \u001b[38;5;28;01mfor\u001b[39;00m key, future \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mzip\u001b[39m(steps, futures)}\n\u001b[1;32m 2694\u001b[0m \u001b[38;5;66;03m# finish the root run\u001b[39;00m\n\u001b[1;32m 2695\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n", "File \u001b[0;32m/usr/lib/python3.10/concurrent/futures/_base.py:458\u001b[0m, in \u001b[0;36mFuture.result\u001b[0;34m(self, timeout)\u001b[0m\n\u001b[1;32m 456\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m CancelledError()\n\u001b[1;32m 457\u001b[0m \u001b[38;5;28;01melif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_state \u001b[38;5;241m==\u001b[39m FINISHED:\n\u001b[0;32m--> 458\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m__get_result\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 459\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m 460\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mTimeoutError\u001b[39;00m()\n", "File \u001b[0;32m/usr/lib/python3.10/concurrent/futures/_base.py:403\u001b[0m, in \u001b[0;36mFuture.__get_result\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m 401\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_exception:\n\u001b[1;32m 402\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m--> 403\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_exception\n\u001b[1;32m 404\u001b[0m \u001b[38;5;28;01mfinally\u001b[39;00m:\n\u001b[1;32m 405\u001b[0m \u001b[38;5;66;03m# Break a reference cycle with the exception in self._exception\u001b[39;00m\n\u001b[1;32m 406\u001b[0m \u001b[38;5;28mself\u001b[39m \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mNone\u001b[39;00m\n", "File \u001b[0;32m/usr/lib/python3.10/concurrent/futures/thread.py:58\u001b[0m, in \u001b[0;36m_WorkItem.run\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m 55\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m\n\u001b[1;32m 57\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m---> 58\u001b[0m result \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfn\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 59\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m exc:\n\u001b[1;32m 60\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mfuture\u001b[38;5;241m.\u001b[39mset_exception(exc)\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/runnables/base.py:2056\u001b[0m, in \u001b[0;36mRunnableSequence.invoke\u001b[0;34m(self, input, config)\u001b[0m\n\u001b[1;32m 2054\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m 2055\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m i, step \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28menumerate\u001b[39m(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msteps):\n\u001b[0;32m-> 2056\u001b[0m \u001b[38;5;28minput\u001b[39m \u001b[38;5;241m=\u001b[39m \u001b[43mstep\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43minvoke\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 2057\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2058\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;66;43;03m# mark each step as a child run\u001b[39;49;00m\n\u001b[1;32m 2059\u001b[0m \u001b[43m \u001b[49m\u001b[43mpatch_config\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 2060\u001b[0m \u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mcallbacks\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mrun_manager\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mget_child\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43mf\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mseq:step:\u001b[39;49m\u001b[38;5;132;43;01m{\u001b[39;49;00m\u001b[43mi\u001b[49m\u001b[38;5;241;43m+\u001b[39;49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[38;5;132;43;01m}\u001b[39;49;00m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n\u001b[1;32m 2061\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2062\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 2063\u001b[0m \u001b[38;5;66;03m# finish the root run\u001b[39;00m\n\u001b[1;32m 2064\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/runnables/passthrough.py:419\u001b[0m, in \u001b[0;36mRunnableAssign.invoke\u001b[0;34m(self, input, config, **kwargs)\u001b[0m\n\u001b[1;32m 413\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21minvoke\u001b[39m(\n\u001b[1;32m 414\u001b[0m \u001b[38;5;28mself\u001b[39m,\n\u001b[1;32m 415\u001b[0m \u001b[38;5;28minput\u001b[39m: Dict[\u001b[38;5;28mstr\u001b[39m, Any],\n\u001b[1;32m 416\u001b[0m config: Optional[RunnableConfig] \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mNone\u001b[39;00m,\n\u001b[1;32m 417\u001b[0m \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs: Any,\n\u001b[1;32m 418\u001b[0m ) \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m>\u001b[39m Dict[\u001b[38;5;28mstr\u001b[39m, Any]:\n\u001b[0;32m--> 419\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_call_with_config\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_invoke\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/runnables/base.py:1243\u001b[0m, in \u001b[0;36mRunnable._call_with_config\u001b[0;34m(self, func, input, config, run_type, **kwargs)\u001b[0m\n\u001b[1;32m 1239\u001b[0m context \u001b[38;5;241m=\u001b[39m copy_context()\n\u001b[1;32m 1240\u001b[0m context\u001b[38;5;241m.\u001b[39mrun(var_child_runnable_config\u001b[38;5;241m.\u001b[39mset, child_config)\n\u001b[1;32m 1241\u001b[0m output \u001b[38;5;241m=\u001b[39m cast(\n\u001b[1;32m 1242\u001b[0m Output,\n\u001b[0;32m-> 1243\u001b[0m \u001b[43mcontext\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrun\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 1244\u001b[0m \u001b[43m \u001b[49m\u001b[43mcall_func_with_variable_args\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1245\u001b[0m \u001b[43m \u001b[49m\u001b[43mfunc\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;66;43;03m# type: ignore[arg-type]\u001b[39;49;00m\n\u001b[1;32m 1246\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;66;43;03m# type: ignore[arg-type]\u001b[39;49;00m\n\u001b[1;32m 1247\u001b[0m \u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1248\u001b[0m \u001b[43m \u001b[49m\u001b[43mrun_manager\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1249\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1250\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m,\n\u001b[1;32m 1251\u001b[0m )\n\u001b[1;32m 1252\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[1;32m 1253\u001b[0m run_manager\u001b[38;5;241m.\u001b[39mon_chain_error(e)\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/runnables/config.py:326\u001b[0m, in \u001b[0;36mcall_func_with_variable_args\u001b[0;34m(func, input, config, run_manager, **kwargs)\u001b[0m\n\u001b[1;32m 324\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m run_manager \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m accepts_run_manager(func):\n\u001b[1;32m 325\u001b[0m kwargs[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mrun_manager\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;241m=\u001b[39m run_manager\n\u001b[0;32m--> 326\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mfunc\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/runnables/passthrough.py:406\u001b[0m, in \u001b[0;36mRunnableAssign._invoke\u001b[0;34m(self, input, run_manager, config, **kwargs)\u001b[0m\n\u001b[1;32m 393\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21m_invoke\u001b[39m(\n\u001b[1;32m 394\u001b[0m \u001b[38;5;28mself\u001b[39m,\n\u001b[1;32m 395\u001b[0m \u001b[38;5;28minput\u001b[39m: Dict[\u001b[38;5;28mstr\u001b[39m, Any],\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 398\u001b[0m \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs: Any,\n\u001b[1;32m 399\u001b[0m ) \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m>\u001b[39m Dict[\u001b[38;5;28mstr\u001b[39m, Any]:\n\u001b[1;32m 400\u001b[0m \u001b[38;5;28;01massert\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(\n\u001b[1;32m 401\u001b[0m \u001b[38;5;28minput\u001b[39m, \u001b[38;5;28mdict\u001b[39m\n\u001b[1;32m 402\u001b[0m ), \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mThe input to RunnablePassthrough.assign() must be a dict.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 404\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m {\n\u001b[1;32m 405\u001b[0m \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39m\u001b[38;5;28minput\u001b[39m,\n\u001b[0;32m--> 406\u001b[0m \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mmapper\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43minvoke\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 407\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 408\u001b[0m \u001b[43m \u001b[49m\u001b[43mpatch_config\u001b[49m\u001b[43m(\u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mcallbacks\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mrun_manager\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mget_child\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 409\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 410\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m,\n\u001b[1;32m 411\u001b[0m }\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/runnables/base.py:2693\u001b[0m, in \u001b[0;36mRunnableParallel.invoke\u001b[0;34m(self, input, config)\u001b[0m\n\u001b[1;32m 2680\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m get_executor_for_config(config) \u001b[38;5;28;01mas\u001b[39;00m executor:\n\u001b[1;32m 2681\u001b[0m futures \u001b[38;5;241m=\u001b[39m [\n\u001b[1;32m 2682\u001b[0m executor\u001b[38;5;241m.\u001b[39msubmit(\n\u001b[1;32m 2683\u001b[0m step\u001b[38;5;241m.\u001b[39minvoke,\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 2691\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m key, step \u001b[38;5;129;01min\u001b[39;00m steps\u001b[38;5;241m.\u001b[39mitems()\n\u001b[1;32m 2692\u001b[0m ]\n\u001b[0;32m-> 2693\u001b[0m output \u001b[38;5;241m=\u001b[39m {key: future\u001b[38;5;241m.\u001b[39mresult() \u001b[38;5;28;01mfor\u001b[39;00m key, future \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mzip\u001b[39m(steps, futures)}\n\u001b[1;32m 2694\u001b[0m \u001b[38;5;66;03m# finish the root run\u001b[39;00m\n\u001b[1;32m 2695\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/runnables/base.py:2693\u001b[0m, in \u001b[0;36m\u001b[0;34m(.0)\u001b[0m\n\u001b[1;32m 2680\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m get_executor_for_config(config) \u001b[38;5;28;01mas\u001b[39;00m executor:\n\u001b[1;32m 2681\u001b[0m futures \u001b[38;5;241m=\u001b[39m [\n\u001b[1;32m 2682\u001b[0m executor\u001b[38;5;241m.\u001b[39msubmit(\n\u001b[1;32m 2683\u001b[0m step\u001b[38;5;241m.\u001b[39minvoke,\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 2691\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m key, step \u001b[38;5;129;01min\u001b[39;00m steps\u001b[38;5;241m.\u001b[39mitems()\n\u001b[1;32m 2692\u001b[0m ]\n\u001b[0;32m-> 2693\u001b[0m output \u001b[38;5;241m=\u001b[39m {key: \u001b[43mfuture\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mresult\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m \u001b[38;5;28;01mfor\u001b[39;00m key, future \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mzip\u001b[39m(steps, futures)}\n\u001b[1;32m 2694\u001b[0m \u001b[38;5;66;03m# finish the root run\u001b[39;00m\n\u001b[1;32m 2695\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n", "File \u001b[0;32m/usr/lib/python3.10/concurrent/futures/_base.py:458\u001b[0m, in \u001b[0;36mFuture.result\u001b[0;34m(self, timeout)\u001b[0m\n\u001b[1;32m 456\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m CancelledError()\n\u001b[1;32m 457\u001b[0m \u001b[38;5;28;01melif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_state \u001b[38;5;241m==\u001b[39m FINISHED:\n\u001b[0;32m--> 458\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m__get_result\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 459\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m 460\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mTimeoutError\u001b[39;00m()\n", "File \u001b[0;32m/usr/lib/python3.10/concurrent/futures/_base.py:403\u001b[0m, in \u001b[0;36mFuture.__get_result\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m 401\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_exception:\n\u001b[1;32m 402\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m--> 403\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_exception\n\u001b[1;32m 404\u001b[0m \u001b[38;5;28;01mfinally\u001b[39;00m:\n\u001b[1;32m 405\u001b[0m \u001b[38;5;66;03m# Break a reference cycle with the exception in self._exception\u001b[39;00m\n\u001b[1;32m 406\u001b[0m \u001b[38;5;28mself\u001b[39m \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mNone\u001b[39;00m\n", "File \u001b[0;32m/usr/lib/python3.10/concurrent/futures/thread.py:58\u001b[0m, in \u001b[0;36m_WorkItem.run\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m 55\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m\n\u001b[1;32m 57\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m---> 58\u001b[0m result \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfn\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 59\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m exc:\n\u001b[1;32m 60\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mfuture\u001b[38;5;241m.\u001b[39mset_exception(exc)\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/runnables/base.py:2056\u001b[0m, in \u001b[0;36mRunnableSequence.invoke\u001b[0;34m(self, input, config)\u001b[0m\n\u001b[1;32m 2054\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m 2055\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m i, step \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28menumerate\u001b[39m(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msteps):\n\u001b[0;32m-> 2056\u001b[0m \u001b[38;5;28minput\u001b[39m \u001b[38;5;241m=\u001b[39m \u001b[43mstep\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43minvoke\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 2057\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2058\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;66;43;03m# mark each step as a child run\u001b[39;49;00m\n\u001b[1;32m 2059\u001b[0m \u001b[43m \u001b[49m\u001b[43mpatch_config\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 2060\u001b[0m \u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mcallbacks\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mrun_manager\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mget_child\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43mf\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mseq:step:\u001b[39;49m\u001b[38;5;132;43;01m{\u001b[39;49;00m\u001b[43mi\u001b[49m\u001b[38;5;241;43m+\u001b[39;49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[38;5;132;43;01m}\u001b[39;49;00m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n\u001b[1;32m 2061\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2062\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 2063\u001b[0m \u001b[38;5;66;03m# finish the root run\u001b[39;00m\n\u001b[1;32m 2064\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/runnables/base.py:3507\u001b[0m, in \u001b[0;36mRunnableLambda.invoke\u001b[0;34m(self, input, config, **kwargs)\u001b[0m\n\u001b[1;32m 3505\u001b[0m \u001b[38;5;250m\u001b[39m\u001b[38;5;124;03m\"\"\"Invoke this runnable synchronously.\"\"\"\u001b[39;00m\n\u001b[1;32m 3506\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mhasattr\u001b[39m(\u001b[38;5;28mself\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mfunc\u001b[39m\u001b[38;5;124m\"\u001b[39m):\n\u001b[0;32m-> 3507\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_call_with_config\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 3508\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_invoke\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 3509\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 3510\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_config\u001b[49m\u001b[43m(\u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfunc\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 3511\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 3512\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 3513\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m 3514\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mTypeError\u001b[39;00m(\n\u001b[1;32m 3515\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mCannot invoke a coroutine function synchronously.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 3516\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mUse `ainvoke` instead.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 3517\u001b[0m )\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/runnables/base.py:1243\u001b[0m, in \u001b[0;36mRunnable._call_with_config\u001b[0;34m(self, func, input, config, run_type, **kwargs)\u001b[0m\n\u001b[1;32m 1239\u001b[0m context \u001b[38;5;241m=\u001b[39m copy_context()\n\u001b[1;32m 1240\u001b[0m context\u001b[38;5;241m.\u001b[39mrun(var_child_runnable_config\u001b[38;5;241m.\u001b[39mset, child_config)\n\u001b[1;32m 1241\u001b[0m output \u001b[38;5;241m=\u001b[39m cast(\n\u001b[1;32m 1242\u001b[0m Output,\n\u001b[0;32m-> 1243\u001b[0m \u001b[43mcontext\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrun\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 1244\u001b[0m \u001b[43m \u001b[49m\u001b[43mcall_func_with_variable_args\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1245\u001b[0m \u001b[43m \u001b[49m\u001b[43mfunc\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;66;43;03m# type: ignore[arg-type]\u001b[39;49;00m\n\u001b[1;32m 1246\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;66;43;03m# type: ignore[arg-type]\u001b[39;49;00m\n\u001b[1;32m 1247\u001b[0m \u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1248\u001b[0m \u001b[43m \u001b[49m\u001b[43mrun_manager\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1249\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1250\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m,\n\u001b[1;32m 1251\u001b[0m )\n\u001b[1;32m 1252\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[1;32m 1253\u001b[0m run_manager\u001b[38;5;241m.\u001b[39mon_chain_error(e)\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/runnables/config.py:326\u001b[0m, in \u001b[0;36mcall_func_with_variable_args\u001b[0;34m(func, input, config, run_manager, **kwargs)\u001b[0m\n\u001b[1;32m 324\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m run_manager \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m accepts_run_manager(func):\n\u001b[1;32m 325\u001b[0m kwargs[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mrun_manager\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;241m=\u001b[39m run_manager\n\u001b[0;32m--> 326\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mfunc\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/runnables/base.py:3391\u001b[0m, in \u001b[0;36mRunnableLambda._invoke\u001b[0;34m(self, input, run_manager, config, **kwargs)\u001b[0m\n\u001b[1;32m 3387\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m recursion_limit \u001b[38;5;241m<\u001b[39m\u001b[38;5;241m=\u001b[39m \u001b[38;5;241m0\u001b[39m:\n\u001b[1;32m 3388\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mRecursionError\u001b[39;00m(\n\u001b[1;32m 3389\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mRecursion limit reached when invoking \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mself\u001b[39m\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m with input \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28minput\u001b[39m\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 3390\u001b[0m )\n\u001b[0;32m-> 3391\u001b[0m output \u001b[38;5;241m=\u001b[39m \u001b[43moutput\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43minvoke\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 3392\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 3393\u001b[0m \u001b[43m \u001b[49m\u001b[43mpatch_config\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 3394\u001b[0m \u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 3395\u001b[0m \u001b[43m \u001b[49m\u001b[43mcallbacks\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mrun_manager\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mget_child\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 3396\u001b[0m \u001b[43m \u001b[49m\u001b[43mrecursion_limit\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mrecursion_limit\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m-\u001b[39;49m\u001b[43m \u001b[49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 3397\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 3398\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 3399\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m cast(Output, output)\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/runnables/base.py:2056\u001b[0m, in \u001b[0;36mRunnableSequence.invoke\u001b[0;34m(self, input, config)\u001b[0m\n\u001b[1;32m 2054\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m 2055\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m i, step \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28menumerate\u001b[39m(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msteps):\n\u001b[0;32m-> 2056\u001b[0m \u001b[38;5;28minput\u001b[39m \u001b[38;5;241m=\u001b[39m \u001b[43mstep\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43minvoke\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 2057\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2058\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;66;43;03m# mark each step as a child run\u001b[39;49;00m\n\u001b[1;32m 2059\u001b[0m \u001b[43m \u001b[49m\u001b[43mpatch_config\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 2060\u001b[0m \u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mcallbacks\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mrun_manager\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mget_child\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43mf\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mseq:step:\u001b[39;49m\u001b[38;5;132;43;01m{\u001b[39;49;00m\u001b[43mi\u001b[49m\u001b[38;5;241;43m+\u001b[39;49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[38;5;132;43;01m}\u001b[39;49;00m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n\u001b[1;32m 2061\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2062\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 2063\u001b[0m \u001b[38;5;66;03m# finish the root run\u001b[39;00m\n\u001b[1;32m 2064\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/prompts/base.py:113\u001b[0m, in \u001b[0;36mBasePromptTemplate.invoke\u001b[0;34m(self, input, config)\u001b[0m\n\u001b[1;32m 111\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mtags:\n\u001b[1;32m 112\u001b[0m config[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mtags\u001b[39m\u001b[38;5;124m\"\u001b[39m]\u001b[38;5;241m.\u001b[39mextend(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mtags)\n\u001b[0;32m--> 113\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_call_with_config\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 114\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_format_prompt_with_error_handling\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 115\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 116\u001b[0m \u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 117\u001b[0m \u001b[43m \u001b[49m\u001b[43mrun_type\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mprompt\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 118\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/runnables/base.py:1243\u001b[0m, in \u001b[0;36mRunnable._call_with_config\u001b[0;34m(self, func, input, config, run_type, **kwargs)\u001b[0m\n\u001b[1;32m 1239\u001b[0m context \u001b[38;5;241m=\u001b[39m copy_context()\n\u001b[1;32m 1240\u001b[0m context\u001b[38;5;241m.\u001b[39mrun(var_child_runnable_config\u001b[38;5;241m.\u001b[39mset, child_config)\n\u001b[1;32m 1241\u001b[0m output \u001b[38;5;241m=\u001b[39m cast(\n\u001b[1;32m 1242\u001b[0m Output,\n\u001b[0;32m-> 1243\u001b[0m \u001b[43mcontext\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrun\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 1244\u001b[0m \u001b[43m \u001b[49m\u001b[43mcall_func_with_variable_args\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1245\u001b[0m \u001b[43m \u001b[49m\u001b[43mfunc\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;66;43;03m# type: ignore[arg-type]\u001b[39;49;00m\n\u001b[1;32m 1246\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;66;43;03m# type: ignore[arg-type]\u001b[39;49;00m\n\u001b[1;32m 1247\u001b[0m \u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1248\u001b[0m \u001b[43m \u001b[49m\u001b[43mrun_manager\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1249\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1250\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m,\n\u001b[1;32m 1251\u001b[0m )\n\u001b[1;32m 1252\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[1;32m 1253\u001b[0m run_manager\u001b[38;5;241m.\u001b[39mon_chain_error(e)\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/runnables/config.py:326\u001b[0m, in \u001b[0;36mcall_func_with_variable_args\u001b[0;34m(func, input, config, run_manager, **kwargs)\u001b[0m\n\u001b[1;32m 324\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m run_manager \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m accepts_run_manager(func):\n\u001b[1;32m 325\u001b[0m kwargs[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mrun_manager\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;241m=\u001b[39m run_manager\n\u001b[0;32m--> 326\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mfunc\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/prompts/base.py:103\u001b[0m, in \u001b[0;36mBasePromptTemplate._format_prompt_with_error_handling\u001b[0;34m(self, inner_input)\u001b[0m\n\u001b[1;32m 97\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m missing:\n\u001b[1;32m 98\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mKeyError\u001b[39;00m(\n\u001b[1;32m 99\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mInput to \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m\u001b[38;5;18m__class__\u001b[39m\u001b[38;5;241m.\u001b[39m\u001b[38;5;18m__name__\u001b[39m\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m is missing variables \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mmissing\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m. \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 100\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m Expected: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39minput_variables\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 101\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m Received: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mlist\u001b[39m(inner_input\u001b[38;5;241m.\u001b[39mkeys())\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 102\u001b[0m )\n\u001b[0;32m--> 103\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mformat_prompt\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43minner_input\u001b[49m\u001b[43m)\u001b[49m\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/prompts/chat.py:535\u001b[0m, in \u001b[0;36mBaseChatPromptTemplate.format_prompt\u001b[0;34m(self, **kwargs)\u001b[0m\n\u001b[1;32m 526\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mformat_prompt\u001b[39m(\u001b[38;5;28mself\u001b[39m, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs: Any) \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m>\u001b[39m PromptValue:\n\u001b[1;32m 527\u001b[0m \u001b[38;5;250m \u001b[39m\u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[1;32m 528\u001b[0m \u001b[38;5;124;03m Format prompt. Should return a PromptValue.\u001b[39;00m\n\u001b[1;32m 529\u001b[0m \u001b[38;5;124;03m Args:\u001b[39;00m\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 533\u001b[0m \u001b[38;5;124;03m PromptValue.\u001b[39;00m\n\u001b[1;32m 534\u001b[0m \u001b[38;5;124;03m \"\"\"\u001b[39;00m\n\u001b[0;32m--> 535\u001b[0m messages \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mformat_messages\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 536\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m ChatPromptValue(messages\u001b[38;5;241m=\u001b[39mmessages)\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/prompts/chat.py:797\u001b[0m, in \u001b[0;36mChatPromptTemplate.format_messages\u001b[0;34m(self, **kwargs)\u001b[0m\n\u001b[1;32m 793\u001b[0m result\u001b[38;5;241m.\u001b[39mextend([message_template])\n\u001b[1;32m 794\u001b[0m \u001b[38;5;28;01melif\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(\n\u001b[1;32m 795\u001b[0m message_template, (BaseMessagePromptTemplate, BaseChatPromptTemplate)\n\u001b[1;32m 796\u001b[0m ):\n\u001b[0;32m--> 797\u001b[0m message \u001b[38;5;241m=\u001b[39m \u001b[43mmessage_template\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mformat_messages\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 798\u001b[0m result\u001b[38;5;241m.\u001b[39mextend(message)\n\u001b[1;32m 799\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n", "File \u001b[0;32m~/HF/DemoRag/.venv/lib/python3.10/site-packages/langchain_core/prompts/chat.py:129\u001b[0m, in \u001b[0;36mMessagesPlaceholder.format_messages\u001b[0;34m(self, **kwargs)\u001b[0m\n\u001b[1;32m 123\u001b[0m value \u001b[38;5;241m=\u001b[39m (\n\u001b[1;32m 124\u001b[0m kwargs\u001b[38;5;241m.\u001b[39mget(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mvariable_name, [])\n\u001b[1;32m 125\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39moptional\n\u001b[1;32m 126\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m kwargs[\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mvariable_name]\n\u001b[1;32m 127\u001b[0m )\n\u001b[1;32m 128\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(value, \u001b[38;5;28mlist\u001b[39m):\n\u001b[0;32m--> 129\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\n\u001b[1;32m 130\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mvariable \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mvariable_name\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m should be a list of base messages, \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 131\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mgot \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mvalue\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 132\u001b[0m )\n\u001b[1;32m 133\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m convert_to_messages(value)\n", "\u001b[0;31mValueError\u001b[0m: variable chat_history should be a list of base messages, got {'history': []}" ] } ], "source": [ "run_query(\"What is a Blockchain?\")" ] }, { "cell_type": "code", "execution_count": 93, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Blockchain technology can be helpful for data governance by providing a distributed and transparent administration of data. It can enhance trustworthy data sharing by promoting data quality, assessing input data sets, effectively managing access control, and presenting data provenance and activity monitoring. The use of an assessment model that includes reputation, endorsement, and confidence factors can further evaluate data quality. Additionally, blockchain technology can support data use while aligning technology development with personal, ethical, and democratic values. It can also provide an infrastructure for data trust, which is essential for creating economic and social value from data analysis.\n" ] } ], "source": [ "run_query(\"How is it helpful for data governance?\", chat_history)" ] }, { "cell_type": "code", "execution_count": 94, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[HumanMessage(content='What is a Blockchain?'),\n", " AIMessage(content='A blockchain is a series of linked data structures, called blocks, that store and monitor the status of distributed systems on a peer-to-peer network. Each block contains a hash of a previous block and a timestamp, and is connected to a previous block. It is a decentralized and transparent technology, where multiple participants maintain copies of the ledger, providing secure and immutable record-keeping of digital transactions.'),\n", " HumanMessage(content='How is it helpful for data governance?'),\n", " AIMessage(content='Blockchain technology can be helpful for data governance by providing a distributed and transparent administration of data. It can enhance trustworthy data sharing by promoting data quality, assessing input data sets, effectively managing access control, and presenting data provenance and activity monitoring. The use of an assessment model that includes reputation, endorsement, and confidence factors can further evaluate data quality. Additionally, blockchain technology can support data use while aligning technology development with personal, ethical, and democratic values. It can also provide an infrastructure for data trust, which is essential for creating economic and social value from data analysis.')]" ] }, "execution_count": 94, "metadata": {}, "output_type": "execute_result" } ], "source": [ "chat_history" ] }, { "cell_type": "code", "execution_count": 133, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'history': ['aaa', 'bbb'], 'chat_history': ''}" ] }, "execution_count": 133, "metadata": {}, "output_type": "execute_result" } ], "source": [ "loaded_memory.invoke({ 'history': ['aaa','bbb'] })" ] }, { "cell_type": "code", "execution_count": 159, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['history']" ] }, "execution_count": 159, "metadata": {}, "output_type": "execute_result" } ], "source": [ "memory.memory_variables" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Another implementation Conversation+Memery+RAG" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [], "source": [ "memory.clear()" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [], "source": [ "DEFAULT_DOCUMENT_PROMPT = PromptTemplate.from_template(template=\"{page_content}\")\n", "\n", "def _combine_documents(\n", " docs, document_prompt=DEFAULT_DOCUMENT_PROMPT, document_separator=\"\\n\\n\"\n", "):\n", " doc_strings = [format_document(doc, document_prompt) for doc in docs]\n", " return document_separator.join(doc_strings)" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [], "source": [ "_template = \"\"\"Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question, in its original language.\n", "\n", "Chat History:\n", "{chat_history}\n", "Follow Up Input: {question}\n", "Standalone question:\"\"\"\n", "CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(_template)\n", "\n", "template = \"\"\"Answer the question based only on the following context:\n", "{context}\n", "\n", "Question: {question}\n", "\"\"\"\n", "ANSWER_PROMPT = ChatPromptTemplate.from_template(template)" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [], "source": [ "loaded_memory = RunnablePassthrough.assign(\n", " chat_history=RunnableLambda(memory.load_memory_variables) | itemgetter(\"history\"),\n", ")\n", "\n", "standalone_question = {\n", " \"standalone_question\": {\n", " \"question\": lambda x: x[\"question\"],\n", " \"chat_history\": lambda x: get_buffer_string(x[\"chat_history\"]),\n", " }\n", " | CONDENSE_QUESTION_PROMPT\n", " | model\n", " | StrOutputParser()\n", "}\n", "\n", "# Now we retrieve the documents\n", "retrieved_documents = {\n", " \"docs\": itemgetter(\"standalone_question\") | retriever,\n", " \"question\": lambda x: x[\"standalone_question\"],\n", "}\n", "\n", "# Now we construct the inputs for the final prompt\n", "final_inputs = {\n", " \"context\": lambda x: _combine_documents(x[\"docs\"]),\n", " \"question\": itemgetter(\"question\"),\n", "}\n", "\n", "# And finally, we do the part that returns the answers\n", "answer = {\n", " \"answer\": final_inputs | ANSWER_PROMPT | model,\n", " \"docs\": itemgetter(\"docs\"),\n", "}\n", "\n", "# And now we put it all together!\n", "final_chain = loaded_memory | standalone_question | retrieved_documents | answer\n" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'answer': AIMessage(content='Blockchain is a distributed ledger technology that enables secure and immutable record-keeping of digital transactions. It comprises a chain of blocks, each containing a list of validated and time-stamped transactions. The decentralized nature of blockchain ensures that multiple participants, or nodes, maintain copies of the ledger, making it resistant to tampering and censorship. This allows for a trustworthy environment in the registering of sensitive information, as it can provide an audit trail of all operations carried out between peers without the need for a centralized authority. Public blockchains are characterized by their transparency, allowing members and non-members to view and verify the transactions.'),\n", " 'docs': [Document(page_content='Does this work mention which blockchain platform was used?\\nDoes this work use smart contracts as part of the solution?\\nDoes this work describe the motivation for using blockchain as a technological solution?\\nDoes this work describe the motivation for using the specific blockchain platform?\\nIs the blockchain platform still in use?\\nDoes this work propose a framework for a blockchain-based solution for the chain of\\ncustody context?\\nDoes this work use a(n) standard/established chain of custody framework for\\nthe solution?\\nDoes the solution proposed in this work apply to the material evidence use cases?\\nAre the components of the solution specified in this work?\\nDoes this work present an illustration of the solution?', metadata={'chunk': 28.0, 'source': 'ExploringBC-2023.txt'}),\n", " Document(page_content='customer information [14]. Blockchain is the core strength of IoT so\\xad\\nlutions to build a system with cryptographically protected records that\\nare reluctant to change and inaccuracy. Additionally, Blockchain faces\\nseveral crucial issues intrinsic to the Internet of Things, such as a large\\nnumber of IoT devices, a non-homogeneous network topology, limited\\ncomputational capacity, poor communication bandwidth, etc.', metadata={'chunk': 24.0, 'source': 'BlockchainBased-2023.txt'}),\n", " Document(page_content='the nodes present on the chain maintain a complete local copy of the blockchain. The\\nblockchain is an indigenous technology that has emerged for decentralized applications\\nas the outcome of complication, privacy, and security issues present in the applications\\nover half a century [3,4]. It is a peer-to-peer system that authorizes the users to maintain a\\nledger for various transactions that are reproduced, and remains identical in more than\\none location over multiple user servers [5].\\nA blockchain is essentially a block of chains, with the growing list of records referred\\nto as blocks that are joined with cryptography [4]. Each blockchain contains a hash of a\\nprevious block, and a timestamp that keeps track of the creation and modification time of', metadata={'chunk': 3.0, 'source': 'CustodyBlock-2021.txt'}),\n", " Document(page_content='as a distributed ledger technology that enables secure and immutable record-keeping of\\ndigital transactions. It comprises a chain of blocks, each containing a list of validated and\\ntime-stamped transactions. An interesting feature of blockchain is its decentralized nature,\\nwhere multiple participants, or nodes, maintain copies of the ledger. This distributed\\nconsensus mechanism ensures that no single entity has control over the entire network,\\nmaking it resistant to tampering and censorship. Thus, blockchain is ripe for contexts\\ninvolving multiple parties with a need for a reliable and trustworthy ambiance in the\\nregistering of sensitive information, since it can “allow for an audit trail of all operations\\ncarried out between peers without the need for a centralized authority” (Grima et al. 2021).\\nBlockchains can be classified as public, private/permissioned, or hybrid. Public\\nblockchain allows any interested party to be a node in the network and to participate in\\nthe consensus. Registered data can be viewed by members or non-members. In its turn,\\nprivate or permissioned blockchains only allow the participation of authorized members,\\nlimiting data access to such participants. Lastly, hybrid blockchains embed characteristics\\nof both public and private blockchains.\\nThe key features of blockchain include transparency, immutability, security, and decentralization of recorded data in the ledger data. In public blockchains, transparency is\\nachieved by its public nature, allowing members and non-members to view and verify', metadata={'chunk': 6.0, 'source': 'ExploringBC-2023.txt'})]}" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "inputs = { 'question': 'What is a blockchain?' }\n", "result = final_chain.invoke(inputs)\n", "# memory.save_context(inputs={'question':HumanMessage(inputs['question'])}, outputs={'answer': result[\"answer\"]})\n", "memory.save_context(inputs, {\"answer\": result[\"answer\"].content})\n", "result" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'What is a blockchain?'" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# memory.memory_variables\n", "inputs['question']" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'history': [HumanMessage(content='What is a blockchain?'),\n", " AIMessage(content='Blockchain is a distributed ledger technology that enables secure and immutable record-keeping of digital transactions. It comprises a chain of blocks, each containing a list of validated and time-stamped transactions. The decentralized nature of blockchain ensures that multiple participants, or nodes, maintain copies of the ledger, making it resistant to tampering and censorship. This allows for a trustworthy environment in the registering of sensitive information, as it can provide an audit trail of all operations carried out between peers without the need for a centralized authority. Public blockchains are characterized by their transparency, allowing members and non-members to view and verify the transactions.')]}" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "memory.load_memory_variables({})" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'answer': AIMessage(content=\"Based on the provided context, blockchain technology contributes to data governance in several ways. First, it can provide a decentralized and transparent method for data circulation, allowing for traceability and accountability in data handling. This is achieved through blockchain's ability to maintain a tamper-proof record of data transactions, which can promote data quality by assessing input data sets and presenting data provenance and activity monitoring.\\n\\nFurthermore, blockchain technology can effectively manage access control in data governance. By utilizing smart contracts, data access and permissions can be automatically enforced and audited, ensuring that only authorized parties can access specific data. This can be particularly useful in multi-stakeholder scenarios, such as genomic data sharing, where transparent and participatory access control is essential.\\n\\nHowever, it is important to note that the governance design of blockchain systems can be complex and may still face challenges in areas such as decision-making mechanisms and compliance with data protection and other laws. As Werbach (2020) points out, blockchain governance must become more robust to gain broader trust and move past its current limited applications.\\n\\nIn summary, blockchain technology contributes to data governance by providing a decentralized, transparent, and secure method for data circulation, access control, and management. Its implementation, however, should consider the complexities and challenges in its governance design to ensure broader trust and effectiveness.\"),\n", " 'docs': [Document(page_content='privacy with data utility. The article also recommends that key technologies be explored to\\nprovide (1) privacy protected data release, (2) blockchain technology to trace data circulation,\\nand (3) privacy-protected federated learning). For an explanation of how a data trust could\\nincorporate blockchain that “promotes data quality by assessing input data sets, effectively\\nmanages access control, and presents data provenance and activity monitoring,” see Sara\\nRouhani & Ralph Deters, Data Trust Framework Using Blockchain Technology and Adaptive\\nTransaction\\nValidation,\\n9\\nIEEE\\nACCESS\\n90379\\n(2021),\\nhttps://ieeexplore.ieee.org/ielx7/6287639/9312710/09461755.pdf?tp=&arnumber=9461755&isnu\\nmber=9312710&ref=aHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS8=. But c.f. Kevin Werbach, The\\nSiren Song: Algorithmic Governance By Blockchain, AFTER THE DIGITAL TORNADO: NETWORKS,\\nALGORITHMS, HUMANITY (Jul. 2020) (opining “to the extent blockchain is a governance\\ntechnology, it is immature, without the flexibility or capacity to correct for errors or unforeseen\\nsituations. In order to garner broader trust and move past its current limited applications,\\nblockchain governance must become more robust.”).\\n230 There is some disagreement in the literature as to whether compensating data subjects who', metadata={'chunk': 135.0, 'source': 'HOUSER__BAGBY_2022.txt'}),\n", " Document(page_content='Democratising the digital revolution:\\nthe role of data governance\\nSylvie Delacroix1 2, Joelle Pineau3, and Jessica Montgomery1\\n1\\n\\n1\\n\\nUniversity of Birmingham, Birmingham, B15 2TT, UK\\n2\\nThe Alan Turing Institute, London, W1 2DB, UK\\n3\\nMcGill University, Quebec, H3A0G4, Canada\\n\\nIntroduction', metadata={'chunk': 0.0, 'source': 'SSRN_id3720208.txt'}),\n", " Document(page_content='Emerging technologies may provide new ways of building trust in data, ensuring trustworthiness of\\nproviders and users, enforcing terms of data use and disincentivising rule-breaking, without the\\nneed for a central authority. For example, smart contracts, which allow data sharing and use\\ncontracts to be completed and verified via a distributed ledger, could be used both to incentivise\\nparticipants to pursue the trust’s goal of safe data use and provide transparency and enforcement\\nfunctions.13 Auditing techniques can help demonstrate that only uses consistent with the trust’s\\npurposes and rules have been allowed.14\\nHowever, platforms based on distributed trust still need governance, for example to establish the\\ncriteria for which technical solutions optimise, and to establish sanctions for breaches. Indeed, the\\ndesign of blockchain governance is turning out to be as complex and multidimensional as for any\\nother institution. For example, voting does not become inherently less problematic as a decisionmaking mechanism on blockchains,15 and may even be worse in some respects.16\\nFinally, as the General Legal Report on these pilots points out, technological solutions are still\\nsubject to data protection and other law, and governance structures will be required to ensure\\ncompliance and establish liability.\\n12 Botsman, R., Who Can You Trust?: How Technology Brought Us Together and Why It Might Drive Us Apart, Cambridge,', metadata={'chunk': 25.0, 'source': 'General_decision_making_report_Apr_19.txt'}),\n", " Document(page_content='firms and agencies to enable low-risk access to data for compliance reporting (Young et al., 2019). The data trusts generate synthetic datasets\\nthat provide privacy, prevent competitive advantage, and remove biases\\nthat could strengthen discriminatory policies, all while maintaining the\\ntrustworthiness of the original data.\\nSpecific to genomic data sharing among multi-parties, blockchain\\nhas been chosen to offer solutions for technical and governance challenges (Shabani, 2019). Previously, data sharing techniques hinge on\\ncentralized data access control services. However, data custodians are\\nincreasingly facing scrutiny on data access management control mechanisms. Also, such centralized architectures do not offer transparent oversight on compliance of data sharing, hence multiple stakeholder participation in data sharing governance is limited. As a result, blockchains,\\nwhich are inherently distributed by design, are seen as a platform that\\ncan support data stewardship and participatory access control among\\nmultiple stakeholders (Jain, Dash, Kumar & Luthra, 2021; Mittal, Gupta,\\nChaturvedi, Chansarkar & Gupta, 2021; Shabani, 2019). Also, policies', metadata={'chunk': 18.0, 'source': '1_s20_S2667096822000180_main.txt'})]}" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "inputs = { 'question': 'How does it help data governance?' }\n", "result = final_chain.invoke(inputs)\n", "memory.save_context(inputs, {\"answer\": result[\"answer\"].content})\n", "# memory.save_context(inputs={'question':inputs['question']}, outputs={'answer': result[\"answer\"].content})\n", "result" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A> {'question': 'How does it help transparency?'}\n", "B> {'question': 'How does it help transparency?', 'chat_history': [HumanMessage(content='What is a blockchain?'), AIMessage(content='Blockchain is a distributed ledger technology that enables secure and immutable record-keeping of digital transactions. It comprises a chain of blocks, each containing a list of validated and time-stamped transactions. The decentralized nature of blockchain ensures that multiple participants, or nodes, maintain copies of the ledger, making it resistant to tampering and censorship. This allows for a trustworthy environment in the registering of sensitive information, as it can provide an audit trail of all operations carried out between peers without the need for a centralized authority. Public blockchains are characterized by their transparency, allowing members and non-members to view and verify the transactions.'), HumanMessage(content='How does it help data governance?'), AIMessage(content=\"Based on the provided context, blockchain technology contributes to data governance in several ways. First, it can provide a decentralized and transparent method for data circulation, allowing for traceability and accountability in data handling. This is achieved through blockchain's ability to maintain a tamper-proof record of data transactions, which can promote data quality by assessing input data sets and presenting data provenance and activity monitoring.\\n\\nFurthermore, blockchain technology can effectively manage access control in data governance. By utilizing smart contracts, data access and permissions can be automatically enforced and audited, ensuring that only authorized parties can access specific data. This can be particularly useful in multi-stakeholder scenarios, such as genomic data sharing, where transparent and participatory access control is essential.\\n\\nHowever, it is important to note that the governance design of blockchain systems can be complex and may still face challenges in areas such as decision-making mechanisms and compliance with data protection and other laws. As Werbach (2020) points out, blockchain governance must become more robust to gain broader trust and move past its current limited applications.\\n\\nIn summary, blockchain technology contributes to data governance by providing a decentralized, transparent, and secure method for data circulation, access control, and management. Its implementation, however, should consider the complexities and challenges in its governance design to ensure broader trust and effectiveness.\")]}\n", "C> {'standalone_question': 'How does blockchain technology help with transparency?'}\n" ] }, { "data": { "text/plain": [ "{'standalone_question': 'How does blockchain technology help with transparency?'}" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pipe_a = RunnableLambda(lambda x: pipeLog(\"A>\",x))\n", "pipe_b = RunnableLambda(lambda x: pipeLog(\"B>\",x))\n", "pipe_c = RunnableLambda(lambda x: pipeLog(\"C>\",x))\n", "\n", "test_chain = pipe_a | loaded_memory | pipe_b | standalone_question | pipe_c\n", "test_chain.invoke({'question' : 'How does it help transparency?'})" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'The consensus mechanism in blockchain technology is responsible for the orderly creation of a unique sequence of transactions in a blockchain network. It enables the network to agree on the validity and arrangement of transactions in a decentralized manner. The consensus algorithm orders transactions into blocks, and once a block is consensusly accepted and added to the blockchain, it becomes immutable and unalterable. This ensures the security, transparency, and integrity of the recorded data in the ledger.'" ] }, "execution_count": 44, "metadata": {}, "output_type": "execute_result" } ], "source": [ "inputs = { 'question': 'What purpose may the consensus mechanism serve?' }\n", "result = final_chain.invoke(inputs)\n", "memory.save_context(inputs, {\"answer\": result[\"answer\"].content})\n", "result['answer'].content" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"Consensus mechanisms in blockchain technology can contribute to data governance by providing a distributed and transparent administration that ensures data quality, manages access control, and monitors data provenance. The consensus mechanism in blockchain technology enables multiple parties to maintain consensus on an immutable ledger, which can be used to assess input data sets, promote data quality, and handle a large number of transactions with low latency. Additionally, consensus mechanisms can be used to establish an adaptive solution for determining the number of transaction validators based on the computed trust value. This can help ensure the trustworthiness and quality of the data at origin and ethical and secure usage of the data at the end, addressing both data owners' and data users' concerns. However, consensus mechanisms in blockchain technology still require governance structures to establish compliance with data protection and other laws and to establish liability.\"" ] }, "execution_count": 45, "metadata": {}, "output_type": "execute_result" } ], "source": [ "inputs = { 'question': 'Can it help with data governance?' }\n", "result = final_chain.invoke(inputs)\n", "memory.save_context(inputs, {\"answer\": result[\"answer\"].content})\n", "result['answer'].content" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.8" } }, "nbformat": 4, "nbformat_minor": 2 }