diff --git a/content/LangChain for LLM Application Development/3.存储 Memory.ipynb b/content/LangChain for LLM Application Development/3.存储 Memory.ipynb
index 31b123f..6efeba6 100644
--- a/content/LangChain for LLM Application Development/3.存储 Memory.ipynb
+++ b/content/LangChain for LLM Application Development/3.存储 Memory.ipynb
@@ -1 +1 @@
-{"cells": [{"cell_type": "markdown", "id": "a786c77c", "metadata": {"jp-MarkdownHeadingCollapsed": true, "tags": []}, "source": ["# \u7b2c\u4e09\u7ae0 \u50a8\u5b58\n", "\n", " - [\u4e00\u3001\u8bbe\u7f6eOpenAI API Key](#\u4e00\u3001\u8bbe\u7f6eOpenAI-API-Key)\n", " - [\u4e8c\u3001\u5bf9\u8bdd\u7f13\u5b58\u50a8\u5b58 ](#\u4e8c\u3001\u5bf9\u8bdd\u7f13\u5b58\u50a8\u5b58--)\n", " - [2.1 \u5f00\u59cb\u5bf9\u8bdd\uff0c\u7b2c\u4e00\u8f6e](#2.1-\u5f00\u59cb\u5bf9\u8bdd\uff0c\u7b2c\u4e00\u8f6e)\n", " - [2.2 \u7b2c\u4e8c\u8f6e\u5bf9\u8bdd](#2.2-\u7b2c\u4e8c\u8f6e\u5bf9\u8bdd)\n", " - [2.3 \u7b2c\u4e09\u8f6e\u5bf9\u8bdd](#2.3-\u7b2c\u4e09\u8f6e\u5bf9\u8bdd)\n", " - [2.4 .memory.buffer\u5b58\u50a8\u4e86\u5f53\u524d\u4e3a\u6b62\u6240\u6709\u7684\u5bf9\u8bdd\u4fe1\u606f](#2.4-.memory.buffer\u5b58\u50a8\u4e86\u5f53\u524d\u4e3a\u6b62\u6240\u6709\u7684\u5bf9\u8bdd\u4fe1\u606f)\n", " - [2.5 \u4e5f\u53ef\u4ee5\u901a\u8fc7memory.load_memory_variables({})\u6253\u5370\u5386\u53f2\u6d88\u606f](#2.5-\u4e5f\u53ef\u4ee5\u901a\u8fc7memory.load_memory_variables({})\u6253\u5370\u5386\u53f2\u6d88\u606f)\n", " - [2.6 \u6dfb\u52a0\u6307\u5b9a\u7684\u8f93\u5165\u8f93\u51fa\u5185\u5bb9\u5230\u8bb0\u5fc6\u7f13\u5b58\u533a](#2.6-\u6dfb\u52a0\u6307\u5b9a\u7684\u8f93\u5165\u8f93\u51fa\u5185\u5bb9\u5230\u8bb0\u5fc6\u7f13\u5b58\u533a)\n", " - [\u4e09\u3001\u5bf9\u8bdd\u7f13\u5b58\u7a97\u53e3\u50a8\u5b58](#\u4e09\u3001\u5bf9\u8bdd\u7f13\u5b58\u7a97\u53e3\u50a8\u5b58)\n", " - [3.1 \u5411memory\u6dfb\u52a0\u4e24\u8f6e\u5bf9\u8bdd\uff0c\u5e76\u67e5\u770b\u8bb0\u5fc6\u53d8\u91cf\u5f53\u524d\u7684\u8bb0\u5f55](#3.1-\u5411memory\u6dfb\u52a0\u4e24\u8f6e\u5bf9\u8bdd\uff0c\u5e76\u67e5\u770b\u8bb0\u5fc6\u53d8\u91cf\u5f53\u524d\u7684\u8bb0\u5f55)\n", " - [3.2 \u5728\u770b\u4e00\u4e2a\u4f8b\u5b50\uff0c\u53d1\u73b0\u548c\u4e0a\u9762\u7684\u7ed3\u679c\u4e00\u6837\uff0c\u53ea\u4fdd\u7559\u4e86\u4e00\u8f6e\u5bf9\u8bdd\u8bb0\u5fc6](#3.2-\u5728\u770b\u4e00\u4e2a\u4f8b\u5b50\uff0c\u53d1\u73b0\u548c\u4e0a\u9762\u7684\u7ed3\u679c\u4e00\u6837\uff0c\u53ea\u4fdd\u7559\u4e86\u4e00\u8f6e\u5bf9\u8bdd\u8bb0\u5fc6)\n", " - [3.3 \u5c06\u5bf9\u8bdd\u7f13\u5b58\u7a97\u53e3\u8bb0\u5fc6\u5e94\u7528\u5230\u5bf9\u8bdd\u94fe\u4e2d](#3.3-\u5c06\u5bf9\u8bdd\u7f13\u5b58\u7a97\u53e3\u8bb0\u5fc6\u5e94\u7528\u5230\u5bf9\u8bdd\u94fe\u4e2d)\n", " - [\u56db\u3001\u5bf9\u8bddtoken\u7f13\u5b58\u50a8\u5b58](#\u56db\u3001\u5bf9\u8bddtoken\u7f13\u5b58\u50a8\u5b58)\n", " - [4.1 \u5bfc\u5165\u76f8\u5173\u5305\u548cAPI\u5bc6\u94a5](#4.1-\u5bfc\u5165\u76f8\u5173\u5305\u548cAPI\u5bc6\u94a5)\n", " - [4.2 \u9650\u5236token\u6570\u91cf\uff0c\u8fdb\u884c\u6d4b\u8bd5](#4.2-\u9650\u5236token\u6570\u91cf\uff0c\u8fdb\u884c\u6d4b\u8bd5)\n", " - [4.3 \u4e2d\u6587\u4f8b\u5b50](#4.3-\u4e2d\u6587\u4f8b\u5b50)\n", " - [\u4e94\u3001\u5bf9\u8bdd\u6458\u8981\u7f13\u5b58\u50a8\u5b58](#\u4e94\u3001\u5bf9\u8bdd\u6458\u8981\u7f13\u5b58\u50a8\u5b58)\n", " - [5.1 \u521b\u5efa\u4e00\u4e2a\u957f\u5b57\u7b26\u4e32\uff0c\u5176\u4e2d\u5305\u542b\u67d0\u4eba\u7684\u65e5\u7a0b\u5b89\u6392](#5.1-\u521b\u5efa\u4e00\u4e2a\u957f\u5b57\u7b26\u4e32\uff0c\u5176\u4e2d\u5305\u542b\u67d0\u4eba\u7684\u65e5\u7a0b\u5b89\u6392)\n", " - [5.2 \u57fa\u4e8e\u4e0a\u9762\u7684memory\uff0c\u65b0\u5efa\u4e00\u4e2a\u5bf9\u8bdd\u94fe](#5.2-\u57fa\u4e8e\u4e0a\u9762\u7684memory\uff0c\u65b0\u5efa\u4e00\u4e2a\u5bf9\u8bdd\u94fe)\n", " - [5.3 \u4e2d\u6587\u4f8b\u5b50](#5.3-\u4e2d\u6587\u4f8b\u5b50)\n"]}, {"cell_type": "markdown", "id": "7e10db6f", "metadata": {}, "source": ["\u5f53\u4f60\u4e0e\u90a3\u4e9b\u8bed\u8a00\u6a21\u578b\u8fdb\u884c\u4ea4\u4e92\u7684\u65f6\u5019\uff0c\u4ed6\u4eec\u4e0d\u4f1a\u8bb0\u5f97\u4f60\u4e4b\u524d\u548c\u4ed6\u8fdb\u884c\u7684\u4ea4\u6d41\u5185\u5bb9\uff0c\u8fd9\u5728\u6211\u4eec\u6784\u5efa\u4e00\u4e9b\u5e94\u7528\u7a0b\u5e8f\uff08\u5982\u804a\u5929\u673a\u5668\u4eba\uff09\u7684\u65f6\u5019\uff0c\u662f\u4e00\u4e2a\u5f88\u5927\u7684\u95ee\u9898---\u663e\u5f97\u4e0d\u591f\u667a\u80fd\uff01\u56e0\u6b64\uff0c\u5728\u672c\u8282\u4e2d\u6211\u4eec\u5c06\u4ecb\u7ecd LangChain \u4e2d\u7684\u50a8\u5b58\u6a21\u5757\uff0c\u5373\u5982\u4f55\u5c06\u5148\u524d\u7684\u5bf9\u8bdd\u5d4c\u5165\u5230\u8bed\u8a00\u6a21\u578b\u4e2d\u7684\uff0c\u4f7f\u5176\u5177\u6709\u8fde\u7eed\u5bf9\u8bdd\u7684\u80fd\u529b\u3002\n", "\n", "\u5f53\u4f7f\u7528 LangChain \u4e2d\u7684\u50a8\u5b58\u6a21\u5757\u65f6\uff0c\u5b83\u53ef\u4ee5\u5e2e\u52a9\u4fdd\u5b58\u548c\u7ba1\u7406\u5386\u53f2\u804a\u5929\u6d88\u606f\uff0c\u4ee5\u53ca\u6784\u5efa\u5173\u4e8e\u7279\u5b9a\u5b9e\u4f53\u7684\u77e5\u8bc6\u3002\u8fd9\u4e9b\u7ec4\u4ef6\u53ef\u4ee5\u8de8\u591a\u8f6e\u5bf9\u8bdd\u5b58\u50a8\u4fe1\u606f\uff0c\u5e76\u5141\u8bb8\u5728\u5bf9\u8bdd\u671f\u95f4\u8ddf\u8e2a\u7279\u5b9a\u4fe1\u606f\u548c\u4e0a\u4e0b\u6587\u3002LangChain \u63d0\u4f9b\u4e86\u591a\u79cd\u50a8\u5b58\u7c7b\u578b\u3002\u5176\u4e2d\uff0c\u7f13\u51b2\u533a\u50a8\u5b58\u5141\u8bb8\u4fdd\u7559\u6700\u8fd1\u7684\u804a\u5929\u6d88\u606f\uff0c\u6458\u8981\u50a8\u5b58\u5219\u63d0\u4f9b\u4e86\u5bf9\u6574\u4e2a\u5bf9\u8bdd\u7684\u6458\u8981\u3002\u5b9e\u4f53\u50a8\u5b58\u5219\u5141\u8bb8\u5728\u591a\u8f6e\u5bf9\u8bdd\u4e2d\u4fdd\u7559\u6709\u5173\u7279\u5b9a\u5b9e\u4f53\u7684\u4fe1\u606f\u3002\u8fd9\u4e9b\u8bb0\u5fc6\u7ec4\u4ef6\u90fd\u662f\u6a21\u5757\u5316\u7684\uff0c\u53ef\u4e0e\u5176\u4ed6\u7ec4\u4ef6\u7ec4\u5408\u4f7f\u7528\uff0c\u4ece\u800c\u589e\u5f3a\u673a\u5668\u4eba\u7684\u5bf9\u8bdd\u7ba1\u7406\u80fd\u529b\u3002\u50a8\u5b58\u6a21\u5757\u53ef\u4ee5\u901a\u8fc7\u7b80\u5355\u7684API\u8c03\u7528\u6765\u8bbf\u95ee\u548c\u66f4\u65b0\uff0c\u5141\u8bb8\u5f00\u53d1\u4eba\u5458\u66f4\u8f7b\u677e\u5730\u5b9e\u73b0\u5bf9\u8bdd\u5386\u53f2\u8bb0\u5f55\u7684\u7ba1\u7406\u548c\u7ef4\u62a4\u3002\n", "\n", "\u6b64\u6b21\u8bfe\u7a0b\u4e3b\u8981\u4ecb\u7ecd\u5176\u4e2d\u56db\u79cd\u8bb0\u5fc6\u6a21\u5757\uff0c\u5176\u4ed6\u6a21\u5757\u53ef\u67e5\u770b\u6587\u6863\u5b66\u4e60\u3002\n", "- \u5bf9\u8bdd\u7f13\u5b58\u8bb0\u5fc6 (ConversationBufferMemory\uff09\n", "- \u5bf9\u8bdd\u7f13\u5b58\u7a97\u53e3\u8bb0\u5fc6 (ConversationBufferWindowMemory\uff09\n", "- \u5bf9\u8bdd\u4ee4\u724c\u7f13\u5b58\u8bb0\u5fc6 (ConversationTokenBufferMemory\uff09\n", "- \u5bf9\u8bdd\u6458\u8981\u7f13\u5b58\u8bb0\u5fc6 (ConversationSummaryBufferMemory\uff09\n", "\n", "\u5728LangChain\u4e2d\uff0cMemory\u6307\u7684\u662f\u5927\u8bed\u8a00\u6a21\u578b\uff08LLM\uff09\u7684\u77ed\u671f\u8bb0\u5fc6\u3002\u4e3a\u4ec0\u4e48\u662f\u77ed\u671f\u8bb0\u5fc6\uff1f\u90a3\u662f\u56e0\u4e3aLLM\u8bad\u7ec3\u597d\u4e4b\u540e\uff08\u83b7\u5f97\u4e86\u4e00\u4e9b\u957f\u671f\u8bb0\u5fc6\uff09\uff0c\u5b83\u7684\u53c2\u6570\u4fbf\u4e0d\u4f1a\u56e0\u4e3a\u7528\u6237\u7684\u8f93\u5165\u800c\u53d1\u751f\u6539\u53d8\u3002\u5f53\u7528\u6237\u4e0e\u8bad\u7ec3\u597d\u7684LLM\u8fdb\u884c\u5bf9\u8bdd\u65f6\uff0cLLM\u4f1a\u6682\u65f6\u8bb0\u4f4f\u7528\u6237\u7684\u8f93\u5165\u548c\u5b83\u5df2\u7ecf\u751f\u6210\u7684\u8f93\u51fa\uff0c\u4ee5\u4fbf\u9884\u6d4b\u4e4b\u540e\u7684\u8f93\u51fa\uff0c\u800c\u6a21\u578b\u8f93\u51fa\u5b8c\u6bd5\u540e\uff0c\u5b83\u4fbf\u4f1a\u201c\u9057\u5fd8\u201d\u4e4b\u524d\u7528\u6237\u7684\u8f93\u5165\u548c\u5b83\u7684\u8f93\u51fa\u3002\u56e0\u6b64\uff0c\u4e4b\u524d\u7684\u8fd9\u4e9b\u4fe1\u606f\u53ea\u80fd\u79f0\u4f5c\u4e3aLLM\u7684\u77ed\u671f\u8bb0\u5fc6\u3002 \n", " \n", "\u4e3a\u4e86\u5ef6\u957fLLM\u77ed\u671f\u8bb0\u5fc6\u7684\u4fdd\u7559\u65f6\u95f4\uff0c\u5219\u9700\u8981\u501f\u52a9\u4e00\u4e9b\u5916\u90e8\u5b58\u50a8\u65b9\u5f0f\u6765\u8fdb\u884c\u8bb0\u5fc6\uff0c\u4ee5\u4fbf\u5728\u7528\u6237\u4e0eLLM\u5bf9\u8bdd\u4e2d\uff0cLLM\u80fd\u591f\u5c3d\u53ef\u80fd\u7684\u77e5\u9053\u7528\u6237\u4e0e\u5b83\u6240\u8fdb\u884c\u7684\u5386\u53f2\u5bf9\u8bdd\u4fe1\u606f\u3002 "]}, {"cell_type": "markdown", "id": "1ca56e6b-1e07-4405-a1ca-f4237f20fa75", "metadata": {"tags": []}, "source": ["## \u4e00\u3001\u8bbe\u7f6eOpenAI API Key\n", "\n", "\u767b\u9646 [OpenAI \u8d26\u6237](https://platform.openai.com/account/api-keys) \u83b7\u53d6API Key\uff0c\u7136\u540e\u5c06\u5176\u8bbe\u7f6e\u4e3a\u73af\u5883\u53d8\u91cf\u3002\n", "\n", "- \u5982\u679c\u4f60\u60f3\u8981\u8bbe\u7f6e\u4e3a\u5168\u5c40\u73af\u5883\u53d8\u91cf\uff0c\u53ef\u4ee5\u53c2\u8003[\u77e5\u4e4e\u6587\u7ae0](https://zhuanlan.zhihu.com/p/627665725)\u3002\n", "- \u5982\u679c\u4f60\u60f3\u8981\u8bbe\u7f6e\u4e3a\u672c\u5730/\u9879\u76ee\u73af\u5883\u53d8\u91cf\uff0c\u5728\u672c\u6587\u4ef6\u76ee\u5f55\u4e0b\u521b\u5efa`.env`\u6587\u4ef6, \u6253\u5f00\u6587\u4ef6\u8f93\u5165\u4ee5\u4e0b\u5185\u5bb9\u3002\n", "\n", "
\n", " OPENAI_API_KEY=\"your_api_key\" \n", "
\n", " \n", " \u66ff\u6362\"your_api_key\"\u4e3a\u4f60\u81ea\u5df1\u7684 API Key"]}, {"cell_type": "code", "execution_count": null, "id": "6932bd47-c6d5-4794-8102-a12b84412a93", "metadata": {}, "outputs": [], "source": ["# \u4e0b\u8f7d\u9700\u8981\u7684\u5305python-dotenv\u548copenai\n", "# \u5982\u679c\u4f60\u9700\u8981\u67e5\u770b\u5b89\u88c5\u8fc7\u7a0b\u65e5\u5fd7\uff0c\u53ef\u5220\u9664 -q \n", "!pip install -q python-dotenv\n", "!pip install -q openai"]}, {"cell_type": "code", "execution_count": null, "id": "10446712-9fa6-4d71-94ce-2ea4cf197e54", "metadata": {}, "outputs": [], "source": ["import os\n", "import openai\n", "from dotenv import load_dotenv, find_dotenv\n", "\n", "# \u8bfb\u53d6\u672c\u5730/\u9879\u76ee\u7684\u73af\u5883\u53d8\u91cf\u3002\n", "\n", "# find_dotenv()\u5bfb\u627e\u5e76\u5b9a\u4f4d.env\u6587\u4ef6\u7684\u8def\u5f84\n", "# load_dotenv()\u8bfb\u53d6\u8be5.env\u6587\u4ef6\uff0c\u5e76\u5c06\u5176\u4e2d\u7684\u73af\u5883\u53d8\u91cf\u52a0\u8f7d\u5230\u5f53\u524d\u7684\u8fd0\u884c\u73af\u5883\u4e2d \n", "# \u5982\u679c\u4f60\u8bbe\u7f6e\u7684\u662f\u5168\u5c40\u7684\u73af\u5883\u53d8\u91cf\uff0c\u8fd9\u884c\u4ee3\u7801\u5219\u6ca1\u6709\u4efb\u4f55\u4f5c\u7528\u3002\n", "_ = load_dotenv(find_dotenv())\n", "\n", "# \u83b7\u53d6\u73af\u5883\u53d8\u91cf OPENAI_API_KEY\n", "openai.api_key = os.environ['OPENAI_API_KEY'] "]}, {"cell_type": "markdown", "id": "1297dcd5", "metadata": {}, "source": ["## \u4e8c\u3001\u5bf9\u8bdd\u7f13\u5b58\u50a8\u5b58 \n", " \n", "\u8fd9\u79cd\u8bb0\u5fc6\u5141\u8bb8\u5b58\u50a8\u6d88\u606f\uff0c\u7136\u540e\u4ece\u53d8\u91cf\u4e2d\u63d0\u53d6\u6d88\u606f\u3002"]}, {"cell_type": "code", "execution_count": null, "id": "20ad6fe2", "metadata": {"height": 98}, "outputs": [], "source": ["from langchain.chat_models import ChatOpenAI\n", "from langchain.chains import ConversationChain\n", "from langchain.memory import ConversationBufferMemory"]}, {"cell_type": "code", "execution_count": null, "id": "88bdf13d", "metadata": {"height": 133}, "outputs": [], "source": ["OPENAI_API_KEY = \"********\" #\"\u586b\u5165\u4f60\u7684\u4e13\u5c5e\u7684API key\"\n", "llm = ChatOpenAI(temperature=0.0,openai_api_key=OPENAI_API_KEY) #temperature\uff1a\u9884\u6d4b\u4e0b\u4e00\u4e2atoken\u65f6\uff0c\u6982\u7387\u8d8a\u5927\u7684\u503c\u5c31\u8d8a\u5e73\u6ed1(\u5e73\u6ed1\u4e5f\u5c31\u662f\u8ba9\u5dee\u5f02\u5927\u7684\u503c\u4e4b\u95f4\u7684\u5dee\u5f02\u53d8\u5f97\u6ca1\u90a3\u4e48\u5927)\uff0ctemperature\u503c\u8d8a\u5c0f\u5219\u751f\u6210\u7684\u5185\u5bb9\u8d8a\u7a33\u5b9a\n", "memory = ConversationBufferMemory()\n", "conversation = ConversationChain( #\u65b0\u5efa\u4e00\u4e2a\u5bf9\u8bdd\u94fe\uff08\u5173\u4e8e\u94fe\u540e\u9762\u4f1a\u63d0\u5230\u66f4\u591a\u7684\u7ec6\u8282\uff09\n", " llm=llm, \n", " memory = memory,\n", " verbose=True #\u67e5\u770bLangchain\u5b9e\u9645\u4e0a\u5728\u505a\u4ec0\u4e48\uff0c\u8bbe\u4e3aFALSE\u7684\u8bdd\u53ea\u7ed9\u51fa\u56de\u7b54\uff0c\u770b\u5230\u4e0d\u5230\u4e0b\u9762\u7eff\u8272\u7684\u5185\u5bb9\n", ")"]}, {"cell_type": "markdown", "id": "dea83837", "metadata": {}, "source": ["### 2.1 \u5f00\u59cb\u5bf9\u8bdd\uff0c\u7b2c\u4e00\u8f6e"]}, {"cell_type": "markdown", "id": "1a3b4c42", "metadata": {}, "source": ["\u5f53\u6211\u4eec\u8fd0\u884cpredict\u65f6\uff0c\u751f\u6210\u4e86\u4e00\u4e9b\u63d0\u793a\uff0c\u5982\u4e0b\u6240\u89c1\uff0c\u4ed6\u8bf4\u201c\u4ee5\u4e0b\u662f\u4eba\u7c7b\u548cAI\u4e4b\u95f4\u53cb\u597d\u7684\u5bf9\u8bdd\uff0cAI\u5065\u8c08\u201c\u7b49\u7b49\uff0c\u8fd9\u5b9e\u9645\u4e0a\u662fLangChain\u751f\u6210\u7684\u63d0\u793a\uff0c\u4ee5\u4f7f\u7cfb\u7edf\u8fdb\u884c\u5e0c\u671b\u548c\u53cb\u597d\u7684\u5bf9\u8bdd\uff0c\u5e76\u4e14\u5fc5\u987b\u4fdd\u5b58\u5bf9\u8bdd\uff0c\u5e76\u63d0\u793a\u4e86\u5f53\u524d\u5df2\u5b8c\u6210\u7684\u6a21\u578b\u94fe\u3002"]}, {"cell_type": "code", "execution_count": null, "id": "db24677d", "metadata": {"height": 47}, "outputs": [], "source": ["conversation.predict(input=\"Hi, my name is Andrew\")"]}, {"cell_type": "code", "execution_count": null, "id": "154561c9", "metadata": {}, "outputs": [], "source": ["#\u4e2d\u6587\n", "conversation.predict(input=\"\u4f60\u597d, \u6211\u53eb\u76ae\u76ae\u9c81\")"]}, {"cell_type": "markdown", "id": "e71564ad", "metadata": {}, "source": ["### 2.2 \u7b2c\u4e8c\u8f6e\u5bf9\u8bdd"]}, {"cell_type": "markdown", "id": "54d006bd", "metadata": {}, "source": ["\u5f53\u6211\u4eec\u8fdb\u884c\u4e0b\u4e00\u8f6e\u5bf9\u8bdd\u65f6\uff0c\u4ed6\u4f1a\u4fdd\u7559\u4e0a\u9762\u7684\u63d0\u793a"]}, {"cell_type": "code", "execution_count": null, "id": "cc3ef937", "metadata": {"height": 31}, "outputs": [], "source": ["conversation.predict(input=\"What is 1+1?\")"]}, {"cell_type": "code", "execution_count": null, "id": "63efc1bb", "metadata": {}, "outputs": [], "source": ["#\u4e2d\u6587\n", "conversation.predict(input=\"1+1\u7b49\u4e8e\u591a\u5c11\uff1f\")"]}, {"cell_type": "markdown", "id": "33cb734b", "metadata": {}, "source": ["### 2.3 \u7b2c\u4e09\u8f6e\u5bf9\u8bdd"]}, {"cell_type": "markdown", "id": "0393df3d", "metadata": {}, "source": ["\u4e3a\u4e86\u9a8c\u8bc1\u4ed6\u662f\u5426\u8bb0\u5fc6\u4e86\u524d\u9762\u7684\u5bf9\u8bdd\u5185\u5bb9\uff0c\u6211\u4eec\u8ba9\u4ed6\u56de\u7b54\u524d\u9762\u5df2\u7ecf\u8bf4\u8fc7\u7684\u5185\u5bb9\uff08\u6211\u7684\u540d\u5b57\uff09\uff0c\u53ef\u4ee5\u770b\u5230\u4ed6\u786e\u5b9e\u8f93\u51fa\u4e86\u6b63\u786e\u7684\u540d\u5b57\uff0c\u56e0\u6b64\u8fd9\u4e2a\u5bf9\u8bdd\u94fe\u968f\u7740\u5f80\u4e0b\u8fdb\u884c\u4f1a\u8d8a\u6765\u8d8a\u957f"]}, {"cell_type": "code", "execution_count": null, "id": "acf3339a", "metadata": {"height": 31}, "outputs": [], "source": ["conversation.predict(input=\"What is my name?\")"]}, {"cell_type": "code", "execution_count": null, "id": "2206e5b7", "metadata": {}, "outputs": [], "source": ["#\u4e2d\u6587\n", "conversation.predict(input=\"\u6211\u53eb\u4ec0\u4e48\u540d\u5b57\uff1f\")"]}, {"cell_type": "markdown", "id": "5a96a8d9", "metadata": {}, "source": ["### 2.4 .memory.buffer\u5b58\u50a8\u4e86\u5f53\u524d\u4e3a\u6b62\u6240\u6709\u7684\u5bf9\u8bdd\u4fe1\u606f"]}, {"cell_type": "code", "execution_count": null, "id": "2529400d", "metadata": {"height": 31}, "outputs": [], "source": ["print(memory.buffer) #\u63d0\u53d6\u5386\u53f2\u6d88\u606f"]}, {"cell_type": "code", "execution_count": null, "id": "d948aeb2", "metadata": {}, "outputs": [], "source": ["# \u4e2d\u6587\n", "print(memory.buffer) #\u63d0\u53d6\u5386\u53f2\u6d88\u606f"]}, {"cell_type": "markdown", "id": "6bd222c3", "metadata": {}, "source": ["### 2.5 \u4e5f\u53ef\u4ee5\u901a\u8fc7memory.load_memory_variables({})\u6253\u5370\u5386\u53f2\u6d88\u606f"]}, {"cell_type": "markdown", "id": "0b5de846", "metadata": {}, "source": ["\u8fd9\u91cc\u7684\u82b1\u62ec\u53f7\u5b9e\u9645\u4e0a\u662f\u4e00\u4e2a\u7a7a\u5b57\u5178\uff0c\u6709\u4e00\u4e9b\u66f4\u9ad8\u7ea7\u7684\u529f\u80fd\uff0c\u4f7f\u7528\u6237\u53ef\u4ee5\u4f7f\u7528\u66f4\u590d\u6742\u7684\u8f93\u5165\uff0c\u4f46\u6211\u4eec\u4e0d\u4f1a\u5728\u8fd9\u4e2a\u77ed\u671f\u8bfe\u7a0b\u4e2d\u8ba8\u8bba\u5b83\u4eec\uff0c\u6240\u4ee5\u4e0d\u8981\u62c5\u5fc3\u4e3a\u4ec0\u4e48\u8fd9\u91cc\u6709\u4e00\u4e2a\u7a7a\u7684\u82b1\u62ec\u53f7\u3002"]}, {"cell_type": "code", "execution_count": null, "id": "5018cb0a", "metadata": {"height": 31}, "outputs": [], "source": ["memory.load_memory_variables({})"]}, {"cell_type": "code", "execution_count": null, "id": "af4b8b12", "metadata": {}, "outputs": [], "source": ["# \u4e2d\u6587\n", "memory.load_memory_variables({})"]}, {"cell_type": "markdown", "id": "07d2e892", "metadata": {}, "source": ["### 2.6 \u6dfb\u52a0\u6307\u5b9a\u7684\u8f93\u5165\u8f93\u51fa\u5185\u5bb9\u5230\u8bb0\u5fc6\u7f13\u5b58\u533a"]}, {"cell_type": "code", "execution_count": null, "id": "14219b70", "metadata": {"height": 31}, "outputs": [], "source": ["memory = ConversationBufferMemory() #\u65b0\u5efa\u4e00\u4e2a\u7a7a\u7684\u5bf9\u8bdd\u7f13\u5b58\u8bb0\u5fc6"]}, {"cell_type": "code", "execution_count": null, "id": "a36e9905", "metadata": {"height": 48}, "outputs": [], "source": ["memory.save_context({\"input\": \"Hi\"}, #\u5411\u7f13\u5b58\u533a\u6dfb\u52a0\u6307\u5b9a\u5bf9\u8bdd\u7684\u8f93\u5165\u8f93\u51fa\n", " {\"output\": \"What's up\"})"]}, {"cell_type": "code", "execution_count": null, "id": "61631b1f", "metadata": {"height": 31}, "outputs": [], "source": ["print(memory.buffer) #\u67e5\u770b\u7f13\u5b58\u533a\u7ed3\u679c"]}, {"cell_type": "code", "execution_count": null, "id": "a2fdf9ec", "metadata": {"height": 31}, "outputs": [], "source": ["memory.load_memory_variables({}) #\u518d\u6b21\u52a0\u8f7d\u8bb0\u5fc6\u53d8\u91cf"]}, {"cell_type": "code", "execution_count": null, "id": "27d8dd2f", "metadata": {}, "outputs": [], "source": ["#\u4e2d\u6587\n", "memory = ConversationBufferMemory()\n", "memory.save_context({\"input\": \"\u4f60\u597d\uff0c\u6211\u53eb\u76ae\u76ae\u9c81\"}, \n", " {\"output\": \"\u4f60\u597d\u554a\uff0c\u6211\u53eb\u9c81\u897f\u897f\"})\n", "memory.load_memory_variables({})"]}, {"cell_type": "markdown", "id": "2ac544f2", "metadata": {}, "source": ["\u7ee7\u7eed\u6dfb\u52a0\u65b0\u7684\u5185\u5bb9\uff0c\u5bf9\u8bdd\u5386\u53f2\u90fd\u4fdd\u5b58\u4e0b\u6765\u5728\u4e86\uff01"]}, {"cell_type": "code", "execution_count": null, "id": "7ca79256", "metadata": {"height": 64}, "outputs": [], "source": ["memory.save_context({\"input\": \"Not much, just hanging\"}, \n", " {\"output\": \"Cool\"})"]}, {"cell_type": "code", "execution_count": null, "id": "890a4497", "metadata": {"height": 31}, "outputs": [], "source": ["memory.load_memory_variables({})"]}, {"cell_type": "code", "execution_count": null, "id": "2b614406", "metadata": {}, "outputs": [], "source": ["#\u4e2d\u6587\n", "memory.save_context({\"input\": \"\u5f88\u9ad8\u5174\u548c\u4f60\u6210\u4e3a\u670b\u53cb\uff01\"}, \n", " {\"output\": \"\u662f\u7684\uff0c\u8ba9\u6211\u4eec\u4e00\u8d77\u53bb\u5192\u9669\u5427\uff01\"})\n", "memory.load_memory_variables({})"]}, {"cell_type": "markdown", "id": "8839314a", "metadata": {}, "source": ["\u5f53\u6211\u4eec\u5728\u4f7f\u7528\u5927\u578b\u8bed\u8a00\u6a21\u578b\u8fdb\u884c\u804a\u5929\u5bf9\u8bdd\u65f6\uff0c**\u5927\u578b\u8bed\u8a00\u6a21\u578b\u672c\u8eab\u5b9e\u9645\u4e0a\u662f\u65e0\u72b6\u6001\u7684\u3002\u8bed\u8a00\u6a21\u578b\u672c\u8eab\u5e76\u4e0d\u8bb0\u5f97\u5230\u76ee\u524d\u4e3a\u6b62\u7684\u5386\u53f2\u5bf9\u8bdd**\u3002\u6bcf\u6b21\u8c03\u7528API\u7ed3\u70b9\u90fd\u662f\u72ec\u7acb\u7684\u3002\n", "\n", "\u804a\u5929\u673a\u5668\u4eba\u4f3c\u4e4e\u6709\u8bb0\u5fc6\uff0c\u53ea\u662f\u56e0\u4e3a\u901a\u5e38\u6709\u5feb\u901f\u7684\u4ee3\u7801\u53ef\u4ee5\u5411LLM\u63d0\u4f9b\u8fc4\u4eca\u4e3a\u6b62\u7684\u5b8c\u6574\u5bf9\u8bdd\u4ee5\u53ca\u4e0a\u4e0b\u6587\u3002\u56e0\u6b64\uff0cMemory\u53ef\u4ee5\u660e\u786e\u5730\u5b58\u50a8\u5230\u76ee\u524d\u4e3a\u6b62\u7684\u6240\u6709\u672f\u8bed\u6216\u5bf9\u8bdd\u3002\u8fd9\u4e2aMemory\u5b58\u50a8\u5668\u88ab\u7528\u4f5c\u8f93\u5165\u6216\u9644\u52a0\u4e0a\u4e0b\u6587\u5230LLM\u4e2d\uff0c\u4ee5\u4fbf\u5b83\u53ef\u4ee5\u751f\u6210\u4e00\u4e2a\u8f93\u51fa\uff0c\u5c31\u597d\u50cf\u5b83\u53ea\u6709\u5728\u8fdb\u884c\u4e0b\u4e00\u8f6e\u5bf9\u8bdd\u7684\u65f6\u5019\uff0c\u624d\u77e5\u9053\u4e4b\u524d\u8bf4\u8fc7\u4ec0\u4e48\u3002\n"]}, {"cell_type": "markdown", "id": "cf98e9ff", "metadata": {}, "source": ["## \u4e09\u3001\u5bf9\u8bdd\u7f13\u5b58\u7a97\u53e3\u50a8\u5b58\n", " \n", "\u968f\u7740\u5bf9\u8bdd\u53d8\u5f97\u8d8a\u6765\u8d8a\u957f\uff0c\u6240\u9700\u7684\u5185\u5b58\u91cf\u4e5f\u53d8\u5f97\u975e\u5e38\u957f\u3002\u5c06\u5927\u91cf\u7684tokens\u53d1\u9001\u5230LLM\u7684\u6210\u672c\uff0c\u4e5f\u4f1a\u53d8\u5f97\u66f4\u52a0\u6602\u8d35,\u8fd9\u4e5f\u5c31\u662f\u4e3a\u4ec0\u4e48API\u7684\u8c03\u7528\u8d39\u7528\uff0c\u901a\u5e38\u662f\u57fa\u4e8e\u5b83\u9700\u8981\u5904\u7406\u7684tokens\u6570\u91cf\u800c\u6536\u8d39\u7684\u3002\n", " \n", "\u9488\u5bf9\u4ee5\u4e0a\u95ee\u9898\uff0cLangChain\u4e5f\u63d0\u4f9b\u4e86\u51e0\u79cd\u65b9\u4fbf\u7684memory\u6765\u4fdd\u5b58\u5386\u53f2\u5bf9\u8bdd\u3002\n", "\u5176\u4e2d\uff0c\u5bf9\u8bdd\u7f13\u5b58\u7a97\u53e3\u8bb0\u5fc6\u53ea\u4fdd\u7559\u4e00\u4e2a\u7a97\u53e3\u5927\u5c0f\u7684\u5bf9\u8bdd\u7f13\u5b58\u533a\u7a97\u53e3\u8bb0\u5fc6\u3002\u5b83\u53ea\u4f7f\u7528\u6700\u8fd1\u7684n\u6b21\u4ea4\u4e92\u3002\u8fd9\u53ef\u4ee5\u7528\u4e8e\u4fdd\u6301\u6700\u8fd1\u4ea4\u4e92\u7684\u6ed1\u52a8\u7a97\u53e3\uff0c\u4ee5\u4fbf\u7f13\u51b2\u533a\u4e0d\u4f1a\u8fc7\u5927"]}, {"cell_type": "code", "execution_count": null, "id": "66eeccc3", "metadata": {"height": 47}, "outputs": [], "source": ["from langchain.memory import ConversationBufferWindowMemory"]}, {"cell_type": "markdown", "id": "641477a4", "metadata": {}, "source": ["### 3.1 \u5411memory\u6dfb\u52a0\u4e24\u8f6e\u5bf9\u8bdd\uff0c\u5e76\u67e5\u770b\u8bb0\u5fc6\u53d8\u91cf\u5f53\u524d\u7684\u8bb0\u5f55"]}, {"cell_type": "code", "execution_count": null, "id": "3ea6233e", "metadata": {"height": 47}, "outputs": [], "source": ["memory = ConversationBufferWindowMemory(k=1) # k=1\u8868\u660e\u53ea\u4fdd\u7559\u4e00\u4e2a\u5bf9\u8bdd\u8bb0\u5fc6 "]}, {"cell_type": "code", "execution_count": null, "id": "dc4553fb", "metadata": {"height": 115}, "outputs": [], "source": ["memory.save_context({\"input\": \"Hi\"},\n", " {\"output\": \"What's up\"})\n", "memory.save_context({\"input\": \"Not much, just hanging\"},\n", " {\"output\": \"Cool\"})\n"]}, {"cell_type": "code", "execution_count": null, "id": "6a788403", "metadata": {"height": 31}, "outputs": [], "source": ["memory.load_memory_variables({})"]}, {"cell_type": "markdown", "id": "9b401f0b", "metadata": {}, "source": ["### 3.2 \u5728\u770b\u4e00\u4e2a\u4f8b\u5b50\uff0c\u53d1\u73b0\u548c\u4e0a\u9762\u7684\u7ed3\u679c\u4e00\u6837\uff0c\u53ea\u4fdd\u7559\u4e86\u4e00\u8f6e\u5bf9\u8bdd\u8bb0\u5fc6"]}, {"cell_type": "code", "execution_count": null, "id": "68a2907c", "metadata": {}, "outputs": [], "source": ["#\u4e2d\u6587\n", "memory = ConversationBufferWindowMemory(k=1) # k=1\u8868\u660e\u53ea\u4fdd\u7559\u4e00\u4e2a\u5bf9\u8bdd\u8bb0\u5fc6 \n", "memory.save_context({\"input\": \"\u4f60\u597d\uff0c\u6211\u53eb\u76ae\u76ae\u9c81\"}, \n", " {\"output\": \"\u4f60\u597d\u554a\uff0c\u6211\u53eb\u9c81\u897f\u897f\"})\n", "memory.save_context({\"input\": \"\u5f88\u9ad8\u5174\u548c\u4f60\u6210\u4e3a\u670b\u53cb\uff01\"}, \n", " {\"output\": \"\u662f\u7684\uff0c\u8ba9\u6211\u4eec\u4e00\u8d77\u53bb\u5192\u9669\u5427\uff01\"})\n", "memory.load_memory_variables({})"]}, {"cell_type": "markdown", "id": "63bda148", "metadata": {}, "source": ["### 3.3 \u5c06\u5bf9\u8bdd\u7f13\u5b58\u7a97\u53e3\u8bb0\u5fc6\u5e94\u7528\u5230\u5bf9\u8bdd\u94fe\u4e2d"]}, {"cell_type": "code", "execution_count": null, "id": "4087bc87", "metadata": {"height": 133}, "outputs": [], "source": ["OPENAI_API_KEY = \"********\" #\"\u586b\u5165\u4f60\u7684\u4e13\u5c5e\u7684API key\"\n", "llm = ChatOpenAI(temperature=0.0,openai_api_key=OPENAI_API_KEY)\n", "memory = ConversationBufferWindowMemory(k=1)\n", "conversation = ConversationChain( \n", " llm=llm, \n", " memory = memory,\n", " verbose=False #\u8fd9\u91cc\u6539\u4e3aFALSE\u4e0d\u663e\u793a\u63d0\u793a\uff0c\u4f60\u53ef\u4ee5\u5c1d\u8bd5\u4fee\u6539\u4e3aTRUE\u540e\u7684\u7ed3\u679c\n", ")"]}, {"cell_type": "markdown", "id": "b6d661e3", "metadata": {}, "source": ["\u6ce8\u610f\u6b64\u5904\uff01\u7531\u4e8e\u8fd9\u91cc\u7528\u7684\u662f\u4e00\u4e2a\u7a97\u53e3\u7684\u8bb0\u5fc6\uff0c\u56e0\u6b64\u53ea\u80fd\u4fdd\u5b58\u4e00\u8f6e\u7684\u5386\u53f2\u6d88\u606f\uff0c\u56e0\u6b64AI\u5e76\u4e0d\u80fd\u77e5\u9053\u4f60\u7b2c\u4e00\u8f6e\u5bf9\u8bdd\u4e2d\u63d0\u5230\u7684\u540d\u5b57\uff0c\u4ed6\u6700\u591a\u53ea\u80fd\u8bb0\u4f4f\u4e0a\u4e00\u8f6e\uff08\u7b2c\u4e8c\u8f6e\uff09\u7684\u5bf9\u8bdd\u4fe1\u606f"]}, {"cell_type": "code", "execution_count": null, "id": "4faaa952", "metadata": {"height": 47}, "outputs": [], "source": ["conversation.predict(input=\"Hi, my name is Andrew\")"]}, {"cell_type": "code", "execution_count": null, "id": "bb20ddaa", "metadata": {"height": 31}, "outputs": [], "source": ["conversation.predict(input=\"What is 1+1?\")"]}, {"cell_type": "code", "execution_count": null, "id": "489b2194", "metadata": {"height": 31}, "outputs": [], "source": ["conversation.predict(input=\"What is my name?\")"]}, {"cell_type": "markdown", "id": "a1080168", "metadata": {}, "source": ["\u518d\u770b\u4e00\u4e2a\u4f8b\u5b50\uff0c\u53d1\u73b0\u548c\u4e0a\u9762\u7684\u7ed3\u679c\u4e00\u6837\uff01"]}, {"cell_type": "code", "execution_count": null, "id": "1ee854d9", "metadata": {}, "outputs": [], "source": ["#\u4e2d\u6587\n", "conversation.predict(input=\"\u4f60\u597d, \u6211\u53eb\u76ae\u76ae\u9c81\")\n", "conversation.predict(input=\"1+1\u7b49\u4e8e\u591a\u5c11\uff1f\")\n", "conversation.predict(input=\"\u6211\u53eb\u4ec0\u4e48\u540d\u5b57\uff1f\")"]}, {"cell_type": "markdown", "id": "d2931b92", "metadata": {}, "source": ["## \u56db\u3001\u5bf9\u8bddtoken\u7f13\u5b58\u50a8\u5b58"]}, {"cell_type": "markdown", "id": "dff5b4c7", "metadata": {}, "source": ["\u4f7f\u7528\u5bf9\u8bddtoken\u7f13\u5b58\u8bb0\u5fc6\uff0c\u5185\u5b58\u5c06\u9650\u5236\u4fdd\u5b58\u7684token\u6570\u91cf\u3002\u5982\u679ctoken\u6570\u91cf\u8d85\u51fa\u6307\u5b9a\u6570\u76ee\uff0c\u5b83\u4f1a\u5207\u6389\u8fd9\u4e2a\u5bf9\u8bdd\u7684\u65e9\u671f\u90e8\u5206\n", "\u4ee5\u4fdd\u7559\u4e0e\u6700\u8fd1\u7684\u4ea4\u6d41\u76f8\u5bf9\u5e94\u7684token\u6570\u91cf\uff0c\u4f46\u4e0d\u8d85\u8fc7token\u9650\u5236\u3002"]}, {"cell_type": "code", "execution_count": null, "id": "9f6d063c", "metadata": {"height": 31}, "outputs": [], "source": ["#!pip install tiktoken #\u9700\u8981\u7528\u5230tiktoken\u5305\uff0c\u6ca1\u6709\u7684\u53ef\u4ee5\u5148\u5b89\u88c5\u4e00\u4e0b"]}, {"cell_type": "markdown", "id": "2187cfe6", "metadata": {}, "source": ["### 4.1 \u5bfc\u5165\u76f8\u5173\u5305\u548cAPI\u5bc6\u94a5"]}, {"cell_type": "code", "execution_count": null, "id": "fb9020ed", "metadata": {"height": 81}, "outputs": [], "source": ["from langchain.memory import ConversationTokenBufferMemory\n", "from langchain.llms import OpenAI\n", "\n", "OPENAI_API_KEY = \"********\" #\"\u586b\u5165\u4f60\u7684\u4e13\u5c5e\u7684API key\"\n", "llm = ChatOpenAI(temperature=0.0,openai_api_key=OPENAI_API_KEY)"]}, {"cell_type": "markdown", "id": "f3a84112", "metadata": {}, "source": ["### 4.2 \u9650\u5236token\u6570\u91cf\uff0c\u8fdb\u884c\u6d4b\u8bd5"]}, {"cell_type": "code", "execution_count": null, "id": "43582ee6", "metadata": {"height": 149}, "outputs": [], "source": ["memory = ConversationTokenBufferMemory(llm=llm, max_token_limit=30)\n", "memory.save_context({\"input\": \"AI is what?!\"},\n", " {\"output\": \"Amazing!\"})\n", "memory.save_context({\"input\": \"Backpropagation is what?\"},\n", " {\"output\": \"Beautiful!\"})\n", "memory.save_context({\"input\": \"Chatbots are what?\"}, \n", " {\"output\": \"Charming!\"})"]}, {"cell_type": "markdown", "id": "7b62b2e1", "metadata": {}, "source": ["\u53ef\u4ee5\u770b\u5230\u524d\u9762\u8d85\u51fa\u7684\u7684token\u5df2\u7ecf\u88ab\u820d\u5f03\u4e86\uff01\uff01\uff01"]}, {"cell_type": "code", "execution_count": null, "id": "284288e1", "metadata": {"height": 31}, "outputs": [], "source": ["memory.load_memory_variables({})"]}, {"cell_type": "markdown", "id": "f7f6be43", "metadata": {}, "source": ["### 4.3 \u4e2d\u6587\u4f8b\u5b50"]}, {"cell_type": "code", "execution_count": null, "id": "e9191020", "metadata": {}, "outputs": [], "source": ["memory = ConversationTokenBufferMemory(llm=llm, max_token_limit=30)\n", "memory.save_context({\"input\": \"\u671d\u8f9e\u767d\u5e1d\u5f69\u4e91\u95f4\uff0c\"}, \n", " {\"output\": \"\u5343\u91cc\u6c5f\u9675\u4e00\u65e5\u8fd8\u3002\"})\n", "memory.save_context({\"input\": \"\u4e24\u5cb8\u733f\u58f0\u557c\u4e0d\u4f4f\uff0c\"},\n", " {\"output\": \"\u8f7b\u821f\u5df2\u8fc7\u4e07\u91cd\u5c71\u3002\"})\n", "memory.load_memory_variables({})"]}, {"cell_type": "markdown", "id": "5e4d918b", "metadata": {}, "source": ["\u8865\u5145\uff1a \n", "\n", "ChatGPT\u4f7f\u7528\u4e00\u79cd\u57fa\u4e8e\u5b57\u8282\u5bf9\u7f16\u7801\uff08Byte Pair Encoding\uff0cBPE\uff09\u7684\u65b9\u6cd5\u6765\u8fdb\u884ctokenization\uff08\u5c06\u8f93\u5165\u6587\u672c\u62c6\u5206\u4e3atoken\uff09\u3002 \n", "BPE\u662f\u4e00\u79cd\u5e38\u89c1\u7684tokenization\u6280\u672f\uff0c\u5b83\u5c06\u8f93\u5165\u6587\u672c\u5206\u5272\u6210\u8f83\u5c0f\u7684\u5b50\u8bcd\u5355\u5143\u3002 \n", "\n", "OpenAI\u5728\u5176\u5b98\u65b9GitHub\u4e0a\u516c\u5f00\u4e86\u4e00\u4e2a\u6700\u65b0\u7684\u5f00\u6e90Python\u5e93\uff1atiktoken\uff0c\u8fd9\u4e2a\u5e93\u4e3b\u8981\u662f\u7528\u6765\u8ba1\u7b97tokens\u6570\u91cf\u7684\u3002\u76f8\u6bd4\u8f83Hugging Face\u7684tokenizer\uff0c\u5176\u901f\u5ea6\u63d0\u5347\u4e86\u597d\u51e0\u500d \n", "\n", "\u5177\u4f53token\u8ba1\u7b97\u65b9\u5f0f,\u7279\u522b\u662f\u6c49\u5b57\u548c\u82f1\u6587\u5355\u8bcd\u7684token\u533a\u522b\uff0c\u53c2\u8003 \n"]}, {"cell_type": "markdown", "id": "5ff55d5d", "metadata": {}, "source": ["## \u4e94\u3001\u5bf9\u8bdd\u6458\u8981\u7f13\u5b58\u50a8\u5b58"]}, {"cell_type": "markdown", "id": "7d39b83a", "metadata": {}, "source": ["\u8fd9\u79cdMemory\u7684\u60f3\u6cd5\u662f\uff0c\u4e0d\u662f\u5c06\u5185\u5b58\u9650\u5236\u4e3a\u57fa\u4e8e\u6700\u8fd1\u5bf9\u8bdd\u7684\u56fa\u5b9a\u6570\u91cf\u7684token\u6216\u56fa\u5b9a\u6570\u91cf\u7684\u5bf9\u8bdd\u6b21\u6570\u7a97\u53e3\uff0c\u800c\u662f**\u4f7f\u7528LLM\u7f16\u5199\u5230\u76ee\u524d\u4e3a\u6b62\u5386\u53f2\u5bf9\u8bdd\u7684\u6458\u8981**\uff0c\u5e76\u5c06\u5176\u4fdd\u5b58"]}, {"cell_type": "code", "execution_count": null, "id": "72dcf8b1", "metadata": {"height": 64}, "outputs": [], "source": ["from langchain.memory import ConversationSummaryBufferMemory\n", "from langchain.chat_models import ChatOpenAI\n", "from langchain.chains import ConversationChain"]}, {"cell_type": "code", "execution_count": null, "id": "c11d81c5", "metadata": {}, "outputs": [], "source": ["OPENAI_API_KEY = \"********\" #\"\u586b\u5165\u4f60\u7684\u4e13\u5c5e\u7684API key\"\n", "llm = ChatOpenAI(temperature=0.0,openai_api_key=OPENAI_API_KEY)"]}, {"cell_type": "markdown", "id": "6572ef39", "metadata": {}, "source": ["### 5.1 \u521b\u5efa\u4e00\u4e2a\u957f\u5b57\u7b26\u4e32\uff0c\u5176\u4e2d\u5305\u542b\u67d0\u4eba\u7684\u65e5\u7a0b\u5b89\u6392"]}, {"cell_type": "code", "execution_count": null, "id": "4a5b238f", "metadata": {"height": 285}, "outputs": [], "source": ["# create a long string\n", "schedule = \"There is a meeting at 8am with your product team. \\\n", "You will need your powerpoint presentation prepared. \\\n", "9am-12pm have time to work on your LangChain \\\n", "project which will go quickly because Langchain is such a powerful tool. \\\n", "At Noon, lunch at the italian resturant with a customer who is driving \\\n", "from over an hour away to meet you to understand the latest in AI. \\\n", "Be sure to bring your laptop to show the latest LLM demo.\"\n", "\n", "memory = ConversationSummaryBufferMemory(llm=llm, max_token_limit=100) #\u4f7f\u7528\u5bf9\u8bdd\u6458\u8981\u7f13\u5b58\u8bb0\u5fc6\n", "memory.save_context({\"input\": \"Hello\"}, {\"output\": \"What's up\"})\n", "memory.save_context({\"input\": \"Not much, just hanging\"},\n", " {\"output\": \"Cool\"})\n", "memory.save_context({\"input\": \"What is on the schedule today?\"}, \n", " {\"output\": f\"{schedule}\"})"]}, {"cell_type": "code", "execution_count": null, "id": "2e4ecabe", "metadata": {"height": 31}, "outputs": [], "source": ["memory.load_memory_variables({})"]}, {"cell_type": "markdown", "id": "7ccb97b6", "metadata": {}, "source": ["### 5.2 \u57fa\u4e8e\u4e0a\u9762\u7684memory\uff0c\u65b0\u5efa\u4e00\u4e2a\u5bf9\u8bdd\u94fe"]}, {"cell_type": "code", "execution_count": null, "id": "6728edba", "metadata": {"height": 99}, "outputs": [], "source": ["conversation = ConversationChain( \n", " llm=llm, \n", " memory = memory,\n", " verbose=True\n", ")"]}, {"cell_type": "code", "execution_count": null, "id": "9a221b1d", "metadata": {"height": 47}, "outputs": [], "source": ["conversation.predict(input=\"What would be a good demo to show?\")"]}, {"cell_type": "code", "execution_count": null, "id": "bb582617", "metadata": {"height": 31}, "outputs": [], "source": ["memory.load_memory_variables({}) #\u6458\u8981\u8bb0\u5f55\u66f4\u65b0\u4e86"]}, {"cell_type": "markdown", "id": "4ba827aa", "metadata": {"height": 31}, "source": ["### 5.3 \u4e2d\u6587\u4f8b\u5b50"]}, {"cell_type": "code", "execution_count": null, "id": "2c07922b", "metadata": {"height": 31}, "outputs": [], "source": ["# \u521b\u5efa\u4e00\u4e2a\u957f\u5b57\u7b26\u4e32\n", "schedule = \"\u5728\u516b\u70b9\u4f60\u548c\u4f60\u7684\u4ea7\u54c1\u56e2\u961f\u6709\u4e00\u4e2a\u4f1a\u8bae\u3002 \\\n", "\u4f60\u9700\u8981\u505a\u4e00\u4e2aPPT\u3002 \\\n", "\u4e0a\u53489\u70b9\u523012\u70b9\u4f60\u9700\u8981\u5fd9\u4e8eLangChain\u3002\\\n", "Langchain\u662f\u4e00\u4e2a\u6709\u7528\u7684\u5de5\u5177\uff0c\u56e0\u6b64\u4f60\u7684\u9879\u76ee\u8fdb\u5c55\u7684\u975e\u5e38\u5feb\u3002\\\n", "\u4e2d\u5348\uff0c\u5728\u610f\u5927\u5229\u9910\u5385\u4e0e\u4e00\u4f4d\u5f00\u8f66\u6765\u7684\u987e\u5ba2\u5171\u8fdb\u5348\u9910 \\\n", "\u8d70\u4e86\u4e00\u4e2a\u591a\u5c0f\u65f6\u7684\u8def\u7a0b\u4e0e\u4f60\u89c1\u9762\uff0c\u53ea\u4e3a\u4e86\u89e3\u6700\u65b0\u7684 AI\u3002 \\\n", "\u786e\u4fdd\u4f60\u5e26\u4e86\u7b14\u8bb0\u672c\u7535\u8111\u53ef\u4ee5\u5c55\u793a\u6700\u65b0\u7684 LLM \u6837\u4f8b.\"\n", "\n", "memory = ConversationSummaryBufferMemory(llm=llm, max_token_limit=100)\n", "memory.save_context({\"input\": \"\u4f60\u597d\uff0c\u6211\u53eb\u76ae\u76ae\u9c81\"}, \n", " {\"output\": \"\u4f60\u597d\u554a\uff0c\u6211\u53eb\u9c81\u897f\u897f\"})\n", "memory.save_context({\"input\": \"\u5f88\u9ad8\u5174\u548c\u4f60\u6210\u4e3a\u670b\u53cb\uff01\"}, \n", " {\"output\": \"\u662f\u7684\uff0c\u8ba9\u6211\u4eec\u4e00\u8d77\u53bb\u5192\u9669\u5427\uff01\"})\n", "memory.save_context({\"input\": \"\u4eca\u5929\u7684\u65e5\u7a0b\u5b89\u6392\u662f\u4ec0\u4e48\uff1f\"}, \n", " {\"output\": f\"{schedule}\"})"]}, {"cell_type": "code", "execution_count": null, "id": "52696c8c", "metadata": {"height": 31}, "outputs": [], "source": ["conversation = ConversationChain( \n", " llm=llm, \n", " memory = memory,\n", " verbose=True\n", ")"]}, {"cell_type": "code", "execution_count": null, "id": "48690d13", "metadata": {"height": 31}, "outputs": [], "source": ["conversation.predict(input=\"\u5c55\u793a\u4ec0\u4e48\u6837\u7684\u6837\u4f8b\u6700\u597d\u5462\uff1f\")"]}, {"cell_type": "code", "execution_count": null, "id": "85bba1f8", "metadata": {"height": 31}, "outputs": [], "source": ["memory.load_memory_variables({}) #\u6458\u8981\u8bb0\u5f55\u66f4\u65b0\u4e86"]}], "metadata": {"kernelspec": {"display_name": "Python 3 (ipykernel)", "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.9.12"}, "toc": {"base_numbering": 1, "nav_menu": {}, "number_sections": false, "sideBar": true, "skip_h1_title": false, "title_cell": "", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": true}}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
+{"cells":[{"cell_type":"markdown","id":"a786c77c","metadata":{"jp-MarkdownHeadingCollapsed":true,"tags":[]},"source":["# 第三章 储存\n","\n"," - [一、设置OpenAI API Key](#一、设置OpenAI-API-Key)\n"," - [二、对话缓存储存 ](#二、对话缓存储存--)\n"," - [2.1 开始对话,第一轮](#2.1-开始对话,第一轮)\n"," - [2.2 第二轮对话](#2.2-第二轮对话)\n"," - [2.3 第三轮对话](#2.3-第三轮对话)\n"," - [2.4 .memory.buffer存储了当前为止所有的对话信息](#2.4-.memory.buffer存储了当前为止所有的对话信息)\n"," - [2.5 也可以通过memory.load_memory_variables({})打印历史消息](#2.5-也可以通过memory.load_memory_variables({})打印历史消息)\n"," - [2.6 添加指定的输入输出内容到记忆缓存区](#2.6-添加指定的输入输出内容到记忆缓存区)\n"," - [三、对话缓存窗口储存](#三、对话缓存窗口储存)\n"," - [3.1 向memory添加两轮对话,并查看记忆变量当前的记录](#3.1-向memory添加两轮对话,并查看记忆变量当前的记录)\n"," - [3.2 在看一个例子,发现和上面的结果一样,只保留了一轮对话记忆](#3.2-在看一个例子,发现和上面的结果一样,只保留了一轮对话记忆)\n"," - [3.3 将对话缓存窗口记忆应用到对话链中](#3.3-将对话缓存窗口记忆应用到对话链中)\n"," - [四、对话token缓存储存](#四、对话token缓存储存)\n"," - [4.1 导入相关包和API密钥](#4.1-导入相关包和API密钥)\n"," - [4.2 限制token数量,进行测试](#4.2-限制token数量,进行测试)\n"," - [4.3 中文例子](#4.3-中文例子)\n"," - [五、对话摘要缓存储存](#五、对话摘要缓存储存)\n"," - [5.1 创建一个长字符串,其中包含某人的日程安排](#5.1-创建一个长字符串,其中包含某人的日程安排)\n"," - [5.2 基于上面的memory,新建一个对话链](#5.2-基于上面的memory,新建一个对话链)\n"," - [5.3 中文例子](#5.3-中文例子)\n"]},{"cell_type":"markdown","id":"7e10db6f","metadata":{},"source":["当你与那些语言模型进行交互的时候,他们不会记得你之前和他进行的交流内容,这在我们构建一些应用程序(如聊天机器人)的时候,是一个很大的问题---显得不够智能!因此,在本节中我们将介绍 LangChain 中的储存模块,即如何将先前的对话嵌入到语言模型中的,使其具有连续对话的能力。\n","\n","当使用 LangChain 中的储存模块时,它可以帮助保存和管理历史聊天消息,以及构建关于特定实体的知识。这些组件可以跨多轮对话存储信息,并允许在对话期间跟踪特定信息和上下文。LangChain 提供了多种储存类型。其中,缓冲区储存允许保留最近的聊天消息,摘要储存则提供了对整个对话的摘要。实体储存则允许在多轮对话中保留有关特定实体的信息。这些记忆组件都是模块化的,可与其他组件组合使用,从而增强机器人的对话管理能力。储存模块可以通过简单的API调用来访问和更新,允许开发人员更轻松地实现对话历史记录的管理和维护。\n","\n","此次课程主要介绍其中四种记忆模块,其他模块可查看文档学习。\n","- 对话缓存记忆 (ConversationBufferMemory)\n","- 对话缓存窗口记忆 (ConversationBufferWindowMemory)\n","- 对话令牌缓存记忆 (ConversationTokenBufferMemory)\n","- 对话摘要缓存记忆 (ConversationSummaryBufferMemory)\n","\n","在LangChain中,Memory指的是大语言模型(LLM)的短期记忆。为什么是短期记忆?那是因为LLM训练好之后(获得了一些长期记忆),它的参数便不会因为用户的输入而发生改变。当用户与训练好的LLM进行对话时,LLM会暂时记住用户的输入和它已经生成的输出,以便预测之后的输出,而模型输出完毕后,它便会“遗忘”之前用户的输入和它的输出。因此,之前的这些信息只能称作为LLM的短期记忆。 \n"," \n","为了延长LLM短期记忆的保留时间,则需要借助一些外部存储方式来进行记忆,以便在用户与LLM对话中,LLM能够尽可能的知道用户与它所进行的历史对话信息。 "]},{"cell_type":"markdown","id":"1ca56e6b-1e07-4405-a1ca-f4237f20fa75","metadata":{"tags":[]},"source":["## 一、设置OpenAI API Key\n","\n","登陆 [OpenAI 账户](https://platform.openai.com/account/api-keys) 获取API Key,然后将其设置为环境变量。\n","\n","- 如果你想要设置为全局环境变量,可以参考[知乎文章](https://zhuanlan.zhihu.com/p/627665725)。\n","- 如果你想要设置为本地/项目环境变量,在本文件目录下创建`.env`文件, 打开文件输入以下内容。\n","\n"," \n"," OPENAI_API_KEY=\"your_api_key\" \n","
\n"," \n"," 替换\"your_api_key\"为你自己的 API Key"]},{"cell_type":"code","execution_count":null,"id":"6932bd47-c6d5-4794-8102-a12b84412a93","metadata":{},"outputs":[],"source":["# 下载需要的包python-dotenv和openai\n","# 如果你需要查看安装过程日志,可删除 -q \n","!pip install -q python-dotenv\n","!pip install -q openai"]},{"cell_type":"code","execution_count":6,"id":"10446712-9fa6-4d71-94ce-2ea4cf197e54","metadata":{},"outputs":[],"source":["import os\n","import openai\n","from dotenv import load_dotenv, find_dotenv\n","\n","# 读取本地/项目的环境变量。\n","\n","# find_dotenv()寻找并定位.env文件的路径\n","# load_dotenv()读取该.env文件,并将其中的环境变量加载到当前的运行环境中 \n","# 如果你设置的是全局的环境变量,这行代码则没有任何作用。\n","_ = load_dotenv(find_dotenv())\n","\n","# 获取环境变量 OPENAI_API_KEY\n","openai.api_key = os.environ['OPENAI_API_KEY'] \n"]},{"cell_type":"markdown","id":"1297dcd5","metadata":{},"source":["## 二、对话缓存储存 \n"," \n","这种记忆允许存储消息,然后从变量中提取消息。"]},{"cell_type":"code","execution_count":2,"id":"20ad6fe2","metadata":{"height":98},"outputs":[],"source":["from langchain.chat_models import ChatOpenAI\n","from langchain.chains import ConversationChain\n","from langchain.memory import ConversationBufferMemory"]},{"cell_type":"code","execution_count":31,"id":"88bdf13d","metadata":{"height":133},"outputs":[],"source":["# 英文链\n","llm = ChatOpenAI(temperature=0.0) #temperature:预测下一个token时,概率越大的值就越平滑(平滑也就是让差异大的值之间的差异变得没那么大),temperature值越小则生成的内容越稳定\n","memory = ConversationBufferMemory()\n","conversation = ConversationChain( #新建一个对话链(关于链后面会提到更多的细节)\n"," llm=llm, \n"," memory = memory,\n"," verbose=True #查看Langchain实际上在做什么,设为FALSE的话只给出回答,看到不到下面绿色的内容\n",")"]},{"cell_type":"code","execution_count":32,"id":"bb4968d9","metadata":{},"outputs":[],"source":["# 中文链\n","llm = ChatOpenAI(temperature=0.0) #temperature:预测下一个token时,概率越大的值就越平滑(平滑也就是让差异大的值之间的差异变得没那么大),temperature值越小则生成的内容越稳定\n","memory_zh = ConversationBufferMemory()\n","conversation_zh = ConversationChain( #新建一个对话链(关于链后面会提到更多的细节)\n"," llm=llm, \n"," memory = memory_zh,\n"," verbose=True #查看Langchain实际上在做什么,设为FALSE的话只给出回答,看到不到下面绿色的内容\n",")"]},{"cell_type":"markdown","id":"dea83837","metadata":{},"source":["### 2.1 开始对话,第一轮"]},{"cell_type":"markdown","id":"1a3b4c42","metadata":{},"source":["当我们运行predict时,生成了一些提示,如下所见,他说“以下是人类和AI之间友好的对话,AI健谈“等等,这实际上是LangChain生成的提示,以使系统进行希望和友好的对话,并且必须保存对话,并提示了当前已完成的模型链。"]},{"cell_type":"code","execution_count":33,"id":"db24677d","metadata":{"height":47},"outputs":[{"name":"stdout","output_type":"stream","text":["\n","\n","\u001b[1m> Entering new chain...\u001b[0m\n","Prompt after formatting:\n","\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n","\n","Current conversation:\n","\n","Human: Hi, my name is Andrew\n","AI:\u001b[0m\n","\n","\u001b[1m> Finished chain.\u001b[0m\n"]},{"data":{"text/plain":["\"Hello Andrew! It's nice to meet you. How can I assist you today?\""]},"execution_count":33,"metadata":{},"output_type":"execute_result"}],"source":["conversation.predict(input=\"Hi, my name is Andrew\")"]},{"cell_type":"code","execution_count":34,"id":"154561c9","metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["\n","\n","\u001b[1m> Entering new chain...\u001b[0m\n","Prompt after formatting:\n","\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n","\n","Current conversation:\n","\n","Human: 你好, 我叫皮皮鲁\n","AI:\u001b[0m\n","\n","\u001b[1m> Finished chain.\u001b[0m\n"]},{"data":{"text/plain":["'你好,皮皮鲁!很高兴认识你。我是一个AI助手,可以回答你的问题和提供帮助。有什么我可以帮你的吗?'"]},"execution_count":34,"metadata":{},"output_type":"execute_result"}],"source":["#中文\n","conversation_zh.predict(input=\"你好, 我叫皮皮鲁\")"]},{"cell_type":"markdown","id":"e71564ad","metadata":{},"source":["### 2.2 第二轮对话"]},{"cell_type":"markdown","id":"54d006bd","metadata":{},"source":["当我们进行下一轮对话时,他会保留上面的提示"]},{"cell_type":"code","execution_count":35,"id":"cc3ef937","metadata":{"height":31},"outputs":[{"name":"stdout","output_type":"stream","text":["\n","\n","\u001b[1m> Entering new chain...\u001b[0m\n","Prompt after formatting:\n","\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n","\n","Current conversation:\n","Human: Hi, my name is Andrew\n","AI: Hello Andrew! It's nice to meet you. How can I assist you today?\n","Human: What is 1+1?\n","AI:\u001b[0m\n","\n","\u001b[1m> Finished chain.\u001b[0m\n"]},{"data":{"text/plain":["'1+1 is equal to 2.'"]},"execution_count":35,"metadata":{},"output_type":"execute_result"}],"source":["conversation.predict(input=\"What is 1+1?\")"]},{"cell_type":"code","execution_count":36,"id":"63efc1bb","metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["\n","\n","\u001b[1m> Entering new chain...\u001b[0m\n","Prompt after formatting:\n","\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n","\n","Current conversation:\n","Human: 你好, 我叫皮皮鲁\n","AI: 你好,皮皮鲁!很高兴认识你。我是一个AI助手,可以回答你的问题和提供帮助。有什么我可以帮你的吗?\n","Human: 1+1等于多少?\n","AI:\u001b[0m\n","\n","\u001b[1m> Finished chain.\u001b[0m\n"]},{"data":{"text/plain":["'1+1等于2。'"]},"execution_count":36,"metadata":{},"output_type":"execute_result"}],"source":["#中文\n","conversation_zh.predict(input=\"1+1等于多少?\")"]},{"cell_type":"markdown","id":"33cb734b","metadata":{},"source":["### 2.3 第三轮对话"]},{"cell_type":"markdown","id":"0393df3d","metadata":{},"source":["为了验证他是否记忆了前面的对话内容,我们让他回答前面已经说过的内容(我的名字),可以看到他确实输出了正确的名字,因此这个对话链随着往下进行会越来越长"]},{"cell_type":"code","execution_count":37,"id":"acf3339a","metadata":{"height":31},"outputs":[{"name":"stdout","output_type":"stream","text":["\n","\n","\u001b[1m> Entering new chain...\u001b[0m\n","Prompt after formatting:\n","\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n","\n","Current conversation:\n","Human: Hi, my name is Andrew\n","AI: Hello Andrew! It's nice to meet you. How can I assist you today?\n","Human: What is 1+1?\n","AI: 1+1 is equal to 2.\n","Human: What is my name?\n","AI:\u001b[0m\n","\n","\u001b[1m> Finished chain.\u001b[0m\n"]},{"data":{"text/plain":["'Your name is Andrew.'"]},"execution_count":37,"metadata":{},"output_type":"execute_result"}],"source":["conversation.predict(input=\"What is my name?\")"]},{"cell_type":"code","execution_count":38,"id":"2206e5b7","metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["\n","\n","\u001b[1m> Entering new chain...\u001b[0m\n","Prompt after formatting:\n","\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n","\n","Current conversation:\n","Human: 你好, 我叫皮皮鲁\n","AI: 你好,皮皮鲁!很高兴认识你。我是一个AI助手,可以回答你的问题和提供帮助。有什么我可以帮你的吗?\n","Human: 1+1等于多少?\n","AI: 1+1等于2。\n","Human: 我叫什么名字?\n","AI:\u001b[0m\n","\n","\u001b[1m> Finished chain.\u001b[0m\n"]},{"data":{"text/plain":["'你叫皮皮鲁。'"]},"execution_count":38,"metadata":{},"output_type":"execute_result"}],"source":["#中文\n","conversation_zh.predict(input=\"我叫什么名字?\")"]},{"cell_type":"markdown","id":"5a96a8d9","metadata":{},"source":["### 2.4 .memory.buffer存储了当前为止所有的对话信息"]},{"cell_type":"code","execution_count":39,"id":"2529400d","metadata":{"height":31},"outputs":[{"name":"stdout","output_type":"stream","text":["Human: Hi, my name is Andrew\n","AI: Hello Andrew! It's nice to meet you. How can I assist you today?\n","Human: What is 1+1?\n","AI: 1+1 is equal to 2.\n","Human: What is my name?\n","AI: Your name is Andrew.\n"]}],"source":["print(memory.buffer) #提取历史消息"]},{"cell_type":"code","execution_count":40,"id":"d948aeb2","metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["Human: 你好, 我叫皮皮鲁\n","AI: 你好,皮皮鲁!很高兴认识你。我是一个AI助手,可以回答你的问题和提供帮助。有什么我可以帮你的吗?\n","Human: 1+1等于多少?\n","AI: 1+1等于2。\n","Human: 我叫什么名字?\n","AI: 你叫皮皮鲁。\n"]}],"source":["# 中文\n","print(memory_zh.buffer) #提取历史消息"]},{"cell_type":"markdown","id":"6bd222c3","metadata":{},"source":["### 2.5 也可以通过memory.load_memory_variables({})打印历史消息"]},{"cell_type":"markdown","id":"0b5de846","metadata":{},"source":["这里的花括号实际上是一个空字典,有一些更高级的功能,使用户可以使用更复杂的输入,但我们不会在这个短期课程中讨论它们,所以不要担心为什么这里有一个空的花括号。"]},{"cell_type":"code","execution_count":41,"id":"5018cb0a","metadata":{"height":31},"outputs":[{"data":{"text/plain":["{'history': \"Human: Hi, my name is Andrew\\nAI: Hello Andrew! It's nice to meet you. How can I assist you today?\\nHuman: What is 1+1?\\nAI: 1+1 is equal to 2.\\nHuman: What is my name?\\nAI: Your name is Andrew.\"}"]},"execution_count":41,"metadata":{},"output_type":"execute_result"}],"source":["memory.load_memory_variables({})"]},{"cell_type":"code","execution_count":42,"id":"af4b8b12","metadata":{},"outputs":[{"data":{"text/plain":["{'history': 'Human: 你好, 我叫皮皮鲁\\nAI: 你好,皮皮鲁!很高兴认识你。我是一个AI助手,可以回答你的问题和提供帮助。有什么我可以帮你的吗?\\nHuman: 1+1等于多少?\\nAI: 1+1等于2。\\nHuman: 我叫什么名字?\\nAI: 你叫皮皮鲁。'}"]},"execution_count":42,"metadata":{},"output_type":"execute_result"}],"source":["# 中文\n","memory_zh.load_memory_variables({})"]},{"cell_type":"markdown","id":"07d2e892","metadata":{},"source":["### 2.6 添加指定的输入输出内容到记忆缓存区"]},{"cell_type":"code","execution_count":43,"id":"14219b70","metadata":{"height":31},"outputs":[],"source":["memory = ConversationBufferMemory() #新建一个空的对话缓存记忆"]},{"cell_type":"code","execution_count":45,"id":"a36e9905","metadata":{"height":48},"outputs":[],"source":["memory.save_context({\"input\": \"Hi\"}, #向缓存区添加指定对话的输入输出\n"," {\"output\": \"What's up\"})"]},{"cell_type":"code","execution_count":46,"id":"61631b1f","metadata":{"height":31},"outputs":[{"name":"stdout","output_type":"stream","text":["Human: Hi\n","AI: What's up\n","Human: Hi\n","AI: What's up\n"]}],"source":["print(memory.buffer) #查看缓存区结果"]},{"cell_type":"code","execution_count":47,"id":"a2fdf9ec","metadata":{"height":31},"outputs":[{"data":{"text/plain":["{'history': \"Human: Hi\\nAI: What's up\\nHuman: Hi\\nAI: What's up\"}"]},"execution_count":47,"metadata":{},"output_type":"execute_result"}],"source":["memory.load_memory_variables({}) #再次加载记忆变量"]},{"cell_type":"code","execution_count":48,"id":"27d8dd2f","metadata":{},"outputs":[{"data":{"text/plain":["{'history': 'Human: 你好,我叫皮皮鲁\\nAI: 你好啊,我叫鲁西西'}"]},"execution_count":48,"metadata":{},"output_type":"execute_result"}],"source":["#中文\n","memory = ConversationBufferMemory()\n","memory.save_context({\"input\": \"你好,我叫皮皮鲁\"}, \n"," {\"output\": \"你好啊,我叫鲁西西\"})\n","memory.load_memory_variables({})"]},{"cell_type":"markdown","id":"2ac544f2","metadata":{},"source":["继续添加新的内容,对话历史都保存下来在了!"]},{"cell_type":"code","execution_count":49,"id":"7ca79256","metadata":{"height":64},"outputs":[],"source":["memory.save_context({\"input\": \"Not much, just hanging\"}, \n"," {\"output\": \"Cool\"})"]},{"cell_type":"code","execution_count":50,"id":"890a4497","metadata":{"height":31},"outputs":[{"data":{"text/plain":["{'history': 'Human: 你好,我叫皮皮鲁\\nAI: 你好啊,我叫鲁西西\\nHuman: Not much, just hanging\\nAI: Cool'}"]},"execution_count":50,"metadata":{},"output_type":"execute_result"}],"source":["memory.load_memory_variables({})"]},{"cell_type":"code","execution_count":51,"id":"2b614406","metadata":{},"outputs":[{"data":{"text/plain":["{'history': 'Human: 你好,我叫皮皮鲁\\nAI: 你好啊,我叫鲁西西\\nHuman: Not much, just hanging\\nAI: Cool\\nHuman: 很高兴和你成为朋友!\\nAI: 是的,让我们一起去冒险吧!'}"]},"execution_count":51,"metadata":{},"output_type":"execute_result"}],"source":["#中文\n","memory.save_context({\"input\": \"很高兴和你成为朋友!\"}, \n"," {\"output\": \"是的,让我们一起去冒险吧!\"})\n","memory.load_memory_variables({})"]},{"cell_type":"markdown","id":"8839314a","metadata":{},"source":["当我们在使用大型语言模型进行聊天对话时,**大型语言模型本身实际上是无状态的。语言模型本身并不记得到目前为止的历史对话**。每次调用API结点都是独立的。\n","\n","聊天机器人似乎有记忆,只是因为通常有快速的代码可以向LLM提供迄今为止的完整对话以及上下文。因此,Memory可以明确地存储到目前为止的所有术语或对话。这个Memory存储器被用作输入或附加上下文到LLM中,以便它可以生成一个输出,就好像它只有在进行下一轮对话的时候,才知道之前说过什么。\n"]},{"cell_type":"markdown","id":"cf98e9ff","metadata":{},"source":["## 三、对话缓存窗口储存\n"," \n","随着对话变得越来越长,所需的内存量也变得非常长。将大量的tokens发送到LLM的成本,也会变得更加昂贵,这也就是为什么API的调用费用,通常是基于它需要处理的tokens数量而收费的。\n"," \n","针对以上问题,LangChain也提供了几种方便的memory来保存历史对话。\n","其中,对话缓存窗口记忆只保留一个窗口大小的对话缓存区窗口记忆。它只使用最近的n次交互。这可以用于保持最近交互的滑动窗口,以便缓冲区不会过大"]},{"cell_type":"code","execution_count":52,"id":"66eeccc3","metadata":{"height":47},"outputs":[],"source":["from langchain.memory import ConversationBufferWindowMemory"]},{"cell_type":"markdown","id":"641477a4","metadata":{},"source":["### 3.1 向memory添加两轮对话,并查看记忆变量当前的记录"]},{"cell_type":"code","execution_count":53,"id":"3ea6233e","metadata":{"height":47},"outputs":[],"source":["memory = ConversationBufferWindowMemory(k=1) # k=1表明只保留一个对话记忆 "]},{"cell_type":"code","execution_count":54,"id":"dc4553fb","metadata":{"height":115},"outputs":[],"source":["memory.save_context({\"input\": \"Hi\"},\n"," {\"output\": \"What's up\"})\n","memory.save_context({\"input\": \"Not much, just hanging\"},\n"," {\"output\": \"Cool\"})\n"]},{"cell_type":"code","execution_count":55,"id":"6a788403","metadata":{"height":31},"outputs":[{"data":{"text/plain":["{'history': 'Human: Not much, just hanging\\nAI: Cool'}"]},"execution_count":55,"metadata":{},"output_type":"execute_result"}],"source":["memory.load_memory_variables({})"]},{"cell_type":"markdown","id":"9b401f0b","metadata":{},"source":["### 3.2 在看一个例子,发现和上面的结果一样,只保留了一轮对话记忆"]},{"cell_type":"code","execution_count":56,"id":"68a2907c","metadata":{},"outputs":[{"data":{"text/plain":["{'history': 'Human: 很高兴和你成为朋友!\\nAI: 是的,让我们一起去冒险吧!'}"]},"execution_count":56,"metadata":{},"output_type":"execute_result"}],"source":["#中文\n","memory = ConversationBufferWindowMemory(k=1) # k=1表明只保留一个对话记忆 \n","memory.save_context({\"input\": \"你好,我叫皮皮鲁\"}, \n"," {\"output\": \"你好啊,我叫鲁西西\"})\n","memory.save_context({\"input\": \"很高兴和你成为朋友!\"}, \n"," {\"output\": \"是的,让我们一起去冒险吧!\"})\n","memory.load_memory_variables({})"]},{"cell_type":"markdown","id":"63bda148","metadata":{},"source":["### 3.3 将对话缓存窗口记忆应用到对话链中"]},{"cell_type":"code","execution_count":57,"id":"4087bc87","metadata":{"height":133},"outputs":[],"source":["llm = ChatOpenAI(temperature=0.0)\n","memory = ConversationBufferWindowMemory(k=1)\n","conversation = ConversationChain( \n"," llm=llm, \n"," memory = memory,\n"," verbose=False #这里改为FALSE不显示提示,你可以尝试修改为TRUE后的结果\n",")"]},{"cell_type":"code","execution_count":61,"id":"0c737101","metadata":{},"outputs":[],"source":["# 中文版\n","llm = ChatOpenAI(temperature=0.0)\n","memory_zh = ConversationBufferWindowMemory(k=1)\n","conversation_zh = ConversationChain( \n"," llm=llm, \n"," memory = memory_zh,\n"," verbose=False #这里改为FALSE不显示提示,你可以尝试修改为TRUE后的结果\n",")"]},{"cell_type":"markdown","id":"b6d661e3","metadata":{},"source":["注意此处!由于这里用的是一个窗口的记忆,因此只能保存一轮的历史消息,因此AI并不能知道你第一轮对话中提到的名字,他最多只能记住上一轮(第二轮)的对话信息"]},{"cell_type":"code","execution_count":58,"id":"4faaa952","metadata":{"height":47},"outputs":[{"data":{"text/plain":["\"Hello Andrew! It's nice to meet you. How can I assist you today?\""]},"execution_count":58,"metadata":{},"output_type":"execute_result"}],"source":["conversation.predict(input=\"Hi, my name is Andrew\")"]},{"cell_type":"code","execution_count":63,"id":"b3a941b5","metadata":{},"outputs":[{"data":{"text/plain":["'你好,皮皮鲁!很高兴认识你。我是一个AI助手,可以回答你的问题和提供帮助。有什么我可以帮你的吗?'"]},"execution_count":63,"metadata":{},"output_type":"execute_result"}],"source":["conversation_zh.predict(input=\"你好,我是皮皮鲁\")"]},{"cell_type":"code","execution_count":64,"id":"bb20ddaa","metadata":{"height":31},"outputs":[{"data":{"text/plain":["'1+1 is equal to 2.'"]},"execution_count":64,"metadata":{},"output_type":"execute_result"}],"source":["conversation.predict(input=\"What is 1+1?\")"]},{"cell_type":"code","execution_count":65,"id":"90bf6403","metadata":{},"outputs":[{"data":{"text/plain":["'1+1等于2。'"]},"execution_count":65,"metadata":{},"output_type":"execute_result"}],"source":["conversation_zh.predict(input=\"1+1等于几\")"]},{"cell_type":"code","execution_count":66,"id":"489b2194","metadata":{"height":31},"outputs":[{"data":{"text/plain":["\"I'm sorry, but I don't have access to personal information.\""]},"execution_count":66,"metadata":{},"output_type":"execute_result"}],"source":["conversation.predict(input=\"What is my name?\")"]},{"cell_type":"code","execution_count":67,"id":"932ace4f","metadata":{},"outputs":[{"data":{"text/plain":["'很抱歉,我无法知道您的名字。'"]},"execution_count":67,"metadata":{},"output_type":"execute_result"}],"source":["conversation_zh.predict(input=\"我叫什么名字\")"]},{"cell_type":"markdown","id":"d2931b92","metadata":{},"source":["## 四、对话token缓存储存"]},{"cell_type":"markdown","id":"dff5b4c7","metadata":{},"source":["使用对话token缓存记忆,内存将限制保存的token数量。如果token数量超出指定数目,它会切掉这个对话的早期部分\n","以保留与最近的交流相对应的token数量,但不超过token限制。"]},{"cell_type":"code","execution_count":null,"id":"9f6d063c","metadata":{"height":31},"outputs":[],"source":["#!pip install tiktoken #需要用到tiktoken包,没有的可以先安装一下"]},{"cell_type":"markdown","id":"2187cfe6","metadata":{},"source":["### 4.1 导入相关包和API密钥"]},{"cell_type":"code","execution_count":68,"id":"fb9020ed","metadata":{"height":81},"outputs":[],"source":["from langchain.memory import ConversationTokenBufferMemory\n","from langchain.llms import OpenAI\n","\n","llm = ChatOpenAI(temperature=0.0)"]},{"cell_type":"markdown","id":"f3a84112","metadata":{},"source":["### 4.2 限制token数量,进行测试"]},{"cell_type":"code","execution_count":69,"id":"43582ee6","metadata":{"height":149},"outputs":[],"source":["memory = ConversationTokenBufferMemory(llm=llm, max_token_limit=30)\n","memory.save_context({\"input\": \"AI is what?!\"},\n"," {\"output\": \"Amazing!\"})\n","memory.save_context({\"input\": \"Backpropagation is what?\"},\n"," {\"output\": \"Beautiful!\"})\n","memory.save_context({\"input\": \"Chatbots are what?\"}, \n"," {\"output\": \"Charming!\"})"]},{"cell_type":"markdown","id":"7b62b2e1","metadata":{},"source":["可以看到前面超出的的token已经被舍弃了!!!"]},{"cell_type":"code","execution_count":70,"id":"284288e1","metadata":{"height":31},"outputs":[{"data":{"text/plain":["{'history': 'AI: Beautiful!\\nHuman: Chatbots are what?\\nAI: Charming!'}"]},"execution_count":70,"metadata":{},"output_type":"execute_result"}],"source":["memory.load_memory_variables({})"]},{"cell_type":"markdown","id":"f7f6be43","metadata":{},"source":["### 4.3 中文例子"]},{"cell_type":"code","execution_count":71,"id":"e9191020","metadata":{},"outputs":[{"data":{"text/plain":["{'history': 'AI: 轻舟已过万重山。'}"]},"execution_count":71,"metadata":{},"output_type":"execute_result"}],"source":["memory = ConversationTokenBufferMemory(llm=llm, max_token_limit=30)\n","memory.save_context({\"input\": \"朝辞白帝彩云间,\"}, \n"," {\"output\": \"千里江陵一日还。\"})\n","memory.save_context({\"input\": \"两岸猿声啼不住,\"},\n"," {\"output\": \"轻舟已过万重山。\"})\n","memory.load_memory_variables({})"]},{"cell_type":"markdown","id":"5e4d918b","metadata":{},"source":["补充: \n","\n","ChatGPT使用一种基于字节对编码(Byte Pair Encoding,BPE)的方法来进行tokenization(将输入文本拆分为token)。 \n","BPE是一种常见的tokenization技术,它将输入文本分割成较小的子词单元。 \n","\n","OpenAI在其官方GitHub上公开了一个最新的开源Python库:tiktoken,这个库主要是用来计算tokens数量的。相比较Hugging Face的tokenizer,其速度提升了好几倍 \n","\n","具体token计算方式,特别是汉字和英文单词的token区别,参考 \n"]},{"cell_type":"markdown","id":"5ff55d5d","metadata":{},"source":["## 五、对话摘要缓存储存"]},{"cell_type":"markdown","id":"7d39b83a","metadata":{},"source":["这种Memory的想法是,不是将内存限制为基于最近对话的固定数量的token或固定数量的对话次数窗口,而是**使用LLM编写到目前为止历史对话的摘要**,并将其保存"]},{"cell_type":"code","execution_count":72,"id":"72dcf8b1","metadata":{"height":64},"outputs":[],"source":["from langchain.memory import ConversationSummaryBufferMemory\n","from langchain.chat_models import ChatOpenAI\n","from langchain.chains import ConversationChain"]},{"cell_type":"code","execution_count":73,"id":"c11d81c5","metadata":{},"outputs":[],"source":["llm = ChatOpenAI(temperature=0.0)"]},{"cell_type":"markdown","id":"6572ef39","metadata":{},"source":["### 5.1 创建一个长字符串,其中包含某人的日程安排"]},{"cell_type":"code","execution_count":74,"id":"4a5b238f","metadata":{"height":285},"outputs":[],"source":["# create a long string\n","schedule = \"There is a meeting at 8am with your product team. \\\n","You will need your powerpoint presentation prepared. \\\n","9am-12pm have time to work on your LangChain \\\n","project which will go quickly because Langchain is such a powerful tool. \\\n","At Noon, lunch at the italian resturant with a customer who is driving \\\n","from over an hour away to meet you to understand the latest in AI. \\\n","Be sure to bring your laptop to show the latest LLM demo.\"\n","\n","memory = ConversationSummaryBufferMemory(llm=llm, max_token_limit=100) #使用对话摘要缓存记忆\n","memory.save_context({\"input\": \"Hello\"}, {\"output\": \"What's up\"})\n","memory.save_context({\"input\": \"Not much, just hanging\"},\n"," {\"output\": \"Cool\"})\n","memory.save_context({\"input\": \"What is on the schedule today?\"}, \n"," {\"output\": f\"{schedule}\"})"]},{"cell_type":"code","execution_count":75,"id":"2e4ecabe","metadata":{"height":31},"outputs":[{"data":{"text/plain":["{'history': 'System: The human and AI exchange greetings. The human mentions that they are not doing much. The AI informs the human about their schedule for the day, including a meeting with the product team, working on the LangChain project, and having lunch with a customer to discuss the latest in AI. The AI also reminds the human to bring their laptop to show a demo.'}"]},"execution_count":75,"metadata":{},"output_type":"execute_result"}],"source":["memory.load_memory_variables({})"]},{"cell_type":"markdown","id":"7ccb97b6","metadata":{},"source":["### 5.2 基于上面的memory,新建一个对话链"]},{"cell_type":"code","execution_count":76,"id":"6728edba","metadata":{"height":99},"outputs":[],"source":["conversation = ConversationChain( \n"," llm=llm, \n"," memory = memory,\n"," verbose=True\n",")"]},{"cell_type":"code","execution_count":77,"id":"9a221b1d","metadata":{"height":47},"outputs":[{"name":"stdout","output_type":"stream","text":["\n","\n","\u001b[1m> Entering new chain...\u001b[0m\n","Prompt after formatting:\n","\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n","\n","Current conversation:\n","System: The human and AI exchange greetings. The human mentions that they are not doing much. The AI informs the human about their schedule for the day, including a meeting with the product team, working on the LangChain project, and having lunch with a customer to discuss the latest in AI. The AI also reminds the human to bring their laptop to show a demo.\n","Human: What would be a good demo to show?\n","AI:\u001b[0m\n","\n","\u001b[1m> Finished chain.\u001b[0m\n"]},{"data":{"text/plain":["'A good demo to show would be a live demonstration of the LangChain project. You can showcase the features and functionality of the language translation software, highlighting its accuracy and efficiency. Additionally, you could also demonstrate any recent updates or improvements made to the project. This would give the customer a firsthand experience of the capabilities of the AI technology and its potential benefits for their business.'"]},"execution_count":77,"metadata":{},"output_type":"execute_result"}],"source":["conversation.predict(input=\"What would be a good demo to show?\")"]},{"cell_type":"code","execution_count":78,"id":"bb582617","metadata":{"height":31},"outputs":[{"data":{"text/plain":["{'history': 'System: The human and AI exchange greetings. The human mentions that they are not doing much. The AI informs the human about their schedule for the day, including a meeting with the product team, working on the LangChain project, and having lunch with a customer to discuss the latest in AI. The AI also reminds the human to bring their laptop to show a demo.\\nHuman: What would be a good demo to show?\\nAI: A good demo to show would be a live demonstration of the LangChain project. You can showcase the features and functionality of the language translation software, highlighting its accuracy and efficiency. Additionally, you could also demonstrate any recent updates or improvements made to the project. This would give the customer a firsthand experience of the capabilities of the AI technology and its potential benefits for their business.'}"]},"execution_count":78,"metadata":{},"output_type":"execute_result"}],"source":["memory.load_memory_variables({}) #摘要记录更新了"]},{"cell_type":"markdown","id":"4ba827aa","metadata":{"height":31},"source":["### 5.3 中文例子"]},{"cell_type":"code","execution_count":79,"id":"2c07922b","metadata":{"height":31},"outputs":[],"source":["# 创建一个长字符串\n","schedule = \"在八点你和你的产品团队有一个会议。 \\\n","你需要做一个PPT。 \\\n","上午9点到12点你需要忙于LangChain。\\\n","Langchain是一个有用的工具,因此你的项目进展的非常快。\\\n","中午,在意大利餐厅与一位开车来的顾客共进午餐 \\\n","走了一个多小时的路程与你见面,只为了解最新的 AI。 \\\n","确保你带了笔记本电脑可以展示最新的 LLM 样例.\"\n","\n","memory = ConversationSummaryBufferMemory(llm=llm, max_token_limit=100)\n","memory.save_context({\"input\": \"你好,我叫皮皮鲁\"}, \n"," {\"output\": \"你好啊,我叫鲁西西\"})\n","memory.save_context({\"input\": \"很高兴和你成为朋友!\"}, \n"," {\"output\": \"是的,让我们一起去冒险吧!\"})\n","memory.save_context({\"input\": \"今天的日程安排是什么?\"}, \n"," {\"output\": f\"{schedule}\"})"]},{"cell_type":"code","execution_count":80,"id":"52696c8c","metadata":{"height":31},"outputs":[],"source":["conversation = ConversationChain( \n"," llm=llm, \n"," memory = memory,\n"," verbose=True\n",")"]},{"cell_type":"code","execution_count":81,"id":"48690d13","metadata":{"height":31},"outputs":[{"name":"stdout","output_type":"stream","text":["\n","\n","\u001b[1m> Entering new chain...\u001b[0m\n","Prompt after formatting:\n","\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n","\n","Current conversation:\n","System: The human and AI introduce themselves and become friends. They plan to go on an adventure together. The human asks about their schedule for the day. The AI informs the human about a meeting with their product team at 8 am and the need to prepare a PowerPoint presentation. From 9 am to 12 pm, the human will be busy with LangChain, a useful tool that will help their project progress quickly. At noon, they will have lunch with a customer who has traveled a long way to learn about the latest AI. The AI advises the human to bring their laptop to showcase the latest LLM samples.\n","Human: 展示什么样的样例最好呢?\n","AI:\u001b[0m\n","\n","\u001b[1m> Finished chain.\u001b[0m\n"]},{"data":{"text/plain":["'展示一些具有多样性和创新性的样例可能是最好的选择。你可以展示一些基于图像识别的样例,比如人脸识别、物体识别等。另外,你也可以展示一些自然语言处理方面的样例,比如文本生成、情感分析等。最好选择一些能够展示出你们团队的技术实力和创造力的样例。'"]},"execution_count":81,"metadata":{},"output_type":"execute_result"}],"source":["conversation.predict(input=\"展示什么样的样例最好呢?\")"]},{"cell_type":"code","execution_count":82,"id":"85bba1f8","metadata":{"height":31},"outputs":[{"data":{"text/plain":["{'history': \"System: The human and AI introduce themselves and become friends. They plan to go on an adventure together. The human asks about their schedule for the day. The AI informs the human about a meeting with their product team at 8 am and the need to prepare a PowerPoint presentation. From 9 am to 12 pm, the human will be busy with LangChain, a useful tool that will help their project progress quickly. At noon, they will have lunch with a customer who has traveled a long way to learn about the latest AI. The AI advises the human to bring their laptop to showcase the latest LLM samples. The human asks what kind of samples would be best to showcase. The AI suggests that showcasing diverse and innovative samples would be the best choice. They recommend demonstrating examples based on image recognition, such as face recognition and object recognition. Additionally, they suggest showcasing examples in natural language processing, such as text generation and sentiment analysis. It is important to choose samples that demonstrate the team's technical expertise and creativity.\"}"]},"execution_count":82,"metadata":{},"output_type":"execute_result"}],"source":["memory.load_memory_variables({}) #摘要记录更新了"]}],"metadata":{"kernelspec":{"display_name":"Python 3 (ipykernel)","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.10.11"},"toc":{"base_numbering":1,"nav_menu":{},"number_sections":false,"sideBar":true,"skip_h1_title":false,"title_cell":"","title_sidebar":"Contents","toc_cell":false,"toc_position":{},"toc_section_display":true,"toc_window_display":true}},"nbformat":4,"nbformat_minor":5}
diff --git a/content/LangChain for LLM Application Development/5.基于文档的问答 Question and Answer.ipynb b/content/LangChain for LLM Application Development/5.基于文档的问答 Question and Answer.ipynb
index 8a1097a..f8f9719 100644
--- a/content/LangChain for LLM Application Development/5.基于文档的问答 Question and Answer.ipynb
+++ b/content/LangChain for LLM Application Development/5.基于文档的问答 Question and Answer.ipynb
@@ -1 +1 @@
-{"cells": [{"cell_type": "markdown", "id": "f200ba9a", "metadata": {}, "source": ["# \u7b2c\u4e94\u7ae0 \u57fa\u4e8e\u6587\u6863\u7684\u95ee\u7b54\n", "\n", " - [\u4e00\u3001\u8bbe\u7f6eOpenAI API Key](#\u4e00\u3001\u8bbe\u7f6eOpenAI-API-Key)\n", " - [\u4e00\u3001\u5bfc\u5165embedding\u6a21\u578b\u548c\u5411\u91cf\u5b58\u50a8\u7ec4\u4ef6](#\u4e00\u3001\u5bfc\u5165embedding\u6a21\u578b\u548c\u5411\u91cf\u5b58\u50a8\u7ec4\u4ef6)\n", " - [1.1 \u521b\u5efa\u5411\u91cf\u5b58\u50a8](#1.1-\u521b\u5efa\u5411\u91cf\u5b58\u50a8)\n", " - [1.2 \u4f7f\u7528\u8bed\u8a00\u6a21\u578b\u4e0e\u6587\u6863\u7ed3\u5408\u4f7f\u7528](#1.2-\u4f7f\u7528\u8bed\u8a00\u6a21\u578b\u4e0e\u6587\u6863\u7ed3\u5408\u4f7f\u7528)\n", " - [\u4e8c\u3001 \u5982\u4f55\u56de\u7b54\u6211\u4eec\u6587\u6863\u7684\u76f8\u5173\u95ee\u9898](#\u4e8c\u3001-\u5982\u4f55\u56de\u7b54\u6211\u4eec\u6587\u6863\u7684\u76f8\u5173\u95ee\u9898)\n"]}, {"cell_type": "markdown", "id": "52824b89-532a-4e54-87e9-1410813cd39e", "metadata": {}, "source": ["\n", "\u672c\u7ae0\u5185\u5bb9\u4e3b\u8981\u5229\u7528langchain\u6784\u5efa\u5411\u91cf\u6570\u636e\u5e93\uff0c\u53ef\u4ee5\u5728\u6587\u6863\u4e0a\u65b9\u6216\u5173\u4e8e\u6587\u6863\u56de\u7b54\u95ee\u9898\uff0c\u56e0\u6b64\uff0c\u7ed9\u5b9a\u4ecePDF\u6587\u4ef6\u3001\u7f51\u9875\u6216\u67d0\u4e9b\u516c\u53f8\u7684\u5185\u90e8\u6587\u6863\u6536\u96c6\u4e2d\u63d0\u53d6\u7684\u6587\u672c\uff0c\u4f7f\u7528llm\u56de\u7b54\u6709\u5173\u8fd9\u4e9b\u6587\u6863\u5185\u5bb9\u7684\u95ee\u9898"]}, {"cell_type": "markdown", "id": "42ccf132-cfab-4153-97b5-d545faae4d36", "metadata": {"tags": []}, "source": ["## \u4e00\u3001\u8bbe\u7f6eOpenAI API Key\n", "\n", "\u767b\u9646 [OpenAI \u8d26\u6237](https://platform.openai.com/account/api-keys) \u83b7\u53d6API Key\uff0c\u7136\u540e\u5c06\u5176\u8bbe\u7f6e\u4e3a\u73af\u5883\u53d8\u91cf\u3002\n", "\n", "- \u5982\u679c\u4f60\u60f3\u8981\u8bbe\u7f6e\u4e3a\u5168\u5c40\u73af\u5883\u53d8\u91cf\uff0c\u53ef\u4ee5\u53c2\u8003[\u77e5\u4e4e\u6587\u7ae0](https://zhuanlan.zhihu.com/p/627665725)\u3002\n", "- \u5982\u679c\u4f60\u60f3\u8981\u8bbe\u7f6e\u4e3a\u672c\u5730/\u9879\u76ee\u73af\u5883\u53d8\u91cf\uff0c\u5728\u672c\u6587\u4ef6\u76ee\u5f55\u4e0b\u521b\u5efa`.env`\u6587\u4ef6, \u6253\u5f00\u6587\u4ef6\u8f93\u5165\u4ee5\u4e0b\u5185\u5bb9\u3002\n", "\n", " \n", " OPENAI_API_KEY=\"your_api_key\" \n", "
\n", " \n", " \u66ff\u6362\"your_api_key\"\u4e3a\u4f60\u81ea\u5df1\u7684 API Key"]}, {"cell_type": "code", "execution_count": 1, "id": "cc33ceb1-535f-454d-988c-347a8b14fd72", "metadata": {}, "outputs": [], "source": ["# \u4e0b\u8f7d\u9700\u8981\u7684\u5305python-dotenv\u548copenai\n", "# \u5982\u679c\u4f60\u9700\u8981\u67e5\u770b\u5b89\u88c5\u8fc7\u7a0b\u65e5\u5fd7\uff0c\u53ef\u5220\u9664 -q \n", "!pip install -q python-dotenv\n", "!pip install -q openai"]}, {"cell_type": "code", "execution_count": 2, "id": "e3c97235-f101-47f2-92db-1c37f4bf9845", "metadata": {"tags": []}, "outputs": [], "source": ["import os\n", "import openai\n", "from dotenv import load_dotenv, find_dotenv\n", "\n", "# \u8bfb\u53d6\u672c\u5730/\u9879\u76ee\u7684\u73af\u5883\u53d8\u91cf\u3002\n", "\n", "# find_dotenv()\u5bfb\u627e\u5e76\u5b9a\u4f4d.env\u6587\u4ef6\u7684\u8def\u5f84\n", "# load_dotenv()\u8bfb\u53d6\u8be5.env\u6587\u4ef6\uff0c\u5e76\u5c06\u5176\u4e2d\u7684\u73af\u5883\u53d8\u91cf\u52a0\u8f7d\u5230\u5f53\u524d\u7684\u8fd0\u884c\u73af\u5883\u4e2d \n", "# \u5982\u679c\u4f60\u8bbe\u7f6e\u7684\u662f\u5168\u5c40\u7684\u73af\u5883\u53d8\u91cf\uff0c\u8fd9\u884c\u4ee3\u7801\u5219\u6ca1\u6709\u4efb\u4f55\u4f5c\u7528\u3002\n", "_ = load_dotenv(find_dotenv())\n", "\n", "# \u83b7\u53d6\u73af\u5883\u53d8\u91cf OPENAI_API_KEY\n", "openai.api_key = os.environ['OPENAI_API_KEY'] "]}, {"cell_type": "code", "execution_count": 52, "id": "af8c3c96", "metadata": {}, "outputs": [{"data": {"text/plain": ["'\\n\\n\u4eba\u5de5\u667a\u80fd\u662f\u4e00\u9879\u6781\u5177\u524d\u666f\u7684\u6280\u672f\uff0c\u5b83\u7684\u53d1\u5c55\u6b63\u5728\u6539\u53d8\u4eba\u7c7b\u7684\u751f\u6d3b\u65b9\u5f0f\uff0c\u5e26\u6765\u4e86\u65e0\u6570\u7684\u4fbf\u5229\uff0c\u4e5f\u88ab\u8ba4\u4e3a\u662f\u672a\u6765\u53d1\u5c55\u7684\u91cd\u8981\u6807\u5fd7\u3002\u4eba\u5de5\u667a\u80fd\u7684\u53d1\u5c55\u8ba9\u8bb8\u591a\u590d\u6742\u7684\u4efb\u52a1\u53d8\u5f97\u66f4\u52a0\u5bb9\u6613\uff0c\u66f4\u9ad8\u6548\u7684\u5b8c\u6210\uff0c\u8282\u7701\u4e86\u5927\u91cf\u7684\u65f6\u95f4\u548c\u7cbe\u529b\uff0c\u4e3a\u4eba\u7c7b\u53d1\u5c55\u5e26\u6765\u4e86\u6781\u5927\u7684\u5e2e\u52a9\u3002'"]}, "execution_count": 52, "metadata": {}, "output_type": "execute_result"}], "source": ["from langchain.llms import OpenAI\n", "\n", "llm = OpenAI(model_name=\"text-davinci-003\",max_tokens=1024)\n", "llm(\"\u600e\u4e48\u8bc4\u4ef7\u4eba\u5de5\u667a\u80fd\")"]}, {"cell_type": "markdown", "id": "8cb7a7ec", "metadata": {"height": 30}, "source": ["## \u4e00\u3001\u5bfc\u5165embedding\u6a21\u578b\u548c\u5411\u91cf\u5b58\u50a8\u7ec4\u4ef6\n", "\u4f7f\u7528Dock Array\u5185\u5b58\u641c\u7d22\u5411\u91cf\u5b58\u50a8\uff0c\u4f5c\u4e3a\u4e00\u4e2a\u5185\u5b58\u5411\u91cf\u5b58\u50a8\uff0c\u4e0d\u9700\u8981\u8fde\u63a5\u5916\u90e8\u6570\u636e\u5e93"]}, {"cell_type": "code", "execution_count": 3, "id": "974acf8e-8f88-42de-88f8-40a82cb58e8b", "metadata": {"height": 98}, "outputs": [], "source": ["from langchain.chains import RetrievalQA #\u68c0\u7d22QA\u94fe\uff0c\u5728\u6587\u6863\u4e0a\u8fdb\u884c\u68c0\u7d22\n", "from langchain.chat_models import ChatOpenAI #openai\u6a21\u578b\n", "from langchain.document_loaders import CSVLoader #\u6587\u6863\u52a0\u8f7d\u5668\uff0c\u91c7\u7528csv\u683c\u5f0f\u5b58\u50a8\n", "from langchain.vectorstores import DocArrayInMemorySearch #\u5411\u91cf\u5b58\u50a8\n", "from IPython.display import display, Markdown #\u5728jupyter\u663e\u793a\u4fe1\u606f\u7684\u5de5\u5177"]}, {"cell_type": "code", "execution_count": 4, "id": "7249846e", "metadata": {"height": 75}, "outputs": [], "source": ["#\u8bfb\u53d6\u6587\u4ef6\n", "file = 'OutdoorClothingCatalog_1000.csv'\n", "loader = CSVLoader(file_path=file)"]}, {"cell_type": "code", "execution_count": 24, "id": "7724f00e", "metadata": {"height": 30}, "outputs": [{"data": {"text/html": ["\n", "\n", "
\n", " \n", " \n", " | \n", " 0 | \n", " 1 | \n", " 2 | \n", "
\n", " \n", " \n", " \n", " | 0 | \n", " NaN | \n", " name | \n", " description | \n", "
\n", " \n", " | 1 | \n", " 0.0 | \n", " Women's Campside Oxfords | \n", " This ultracomfortable lace-to-toe Oxford boast... | \n", "
\n", " \n", " | 2 | \n", " 1.0 | \n", " Recycled Waterhog Dog Mat, Chevron Weave | \n", " Protect your floors from spills and splashing ... | \n", "
\n", " \n", " | 3 | \n", " 2.0 | \n", " Infant and Toddler Girls' Coastal Chill Swimsu... | \n", " She'll love the bright colors, ruffles and exc... | \n", "
\n", " \n", " | 4 | \n", " 3.0 | \n", " Refresh Swimwear, V-Neck Tankini Contrasts | \n", " Whether you're going for a swim or heading out... | \n", "
\n", " \n", " | ... | \n", " ... | \n", " ... | \n", " ... | \n", "
\n", " \n", " | 996 | \n", " 995.0 | \n", " Men's Classic Denim, Standard Fit | \n", " Crafted from premium denim that will last wash... | \n", "
\n", " \n", " | 997 | \n", " 996.0 | \n", " CozyPrint Sweater Fleece Pullover | \n", " The ultimate sweater fleece - made from superi... | \n", "
\n", " \n", " | 998 | \n", " 997.0 | \n", " Women's NRS Endurance Spray Paddling Pants | \n", " These comfortable and affordable splash paddli... | \n", "
\n", " \n", " | 999 | \n", " 998.0 | \n", " Women's Stop Flies Hoodie | \n", " This great-looking hoodie uses No Fly Zone Tec... | \n", "
\n", " \n", " | 1000 | \n", " 999.0 | \n", " Modern Utility Bag | \n", " This US-made crossbody bag is built with the s... | \n", "
\n", " \n", "
\n", "
1001 rows \u00d7 3 columns
\n", "
"], "text/plain": [" 0 1 \n", "0 NaN name \\\n", "1 0.0 Women's Campside Oxfords \n", "2 1.0 Recycled Waterhog Dog Mat, Chevron Weave \n", "3 2.0 Infant and Toddler Girls' Coastal Chill Swimsu... \n", "4 3.0 Refresh Swimwear, V-Neck Tankini Contrasts \n", "... ... ... \n", "996 995.0 Men's Classic Denim, Standard Fit \n", "997 996.0 CozyPrint Sweater Fleece Pullover \n", "998 997.0 Women's NRS Endurance Spray Paddling Pants \n", "999 998.0 Women's Stop Flies Hoodie \n", "1000 999.0 Modern Utility Bag \n", "\n", " 2 \n", "0 description \n", "1 This ultracomfortable lace-to-toe Oxford boast... \n", "2 Protect your floors from spills and splashing ... \n", "3 She'll love the bright colors, ruffles and exc... \n", "4 Whether you're going for a swim or heading out... \n", "... ... \n", "996 Crafted from premium denim that will last wash... \n", "997 The ultimate sweater fleece - made from superi... \n", "998 These comfortable and affordable splash paddli... \n", "999 This great-looking hoodie uses No Fly Zone Tec... \n", "1000 This US-made crossbody bag is built with the s... \n", "\n", "[1001 rows x 3 columns]"]}, "execution_count": 24, "metadata": {}, "output_type": "execute_result"}], "source": ["#\u67e5\u770b\u6570\u636e\n", "import pandas as pd\n", "data = pd.read_csv(file,header=None)\n", "data"]}, {"cell_type": "markdown", "id": "3bd6422c", "metadata": {}, "source": ["\u63d0\u4f9b\u4e86\u4e00\u4e2a\u6237\u5916\u670d\u88c5\u7684CSV\u6587\u4ef6\uff0c\u6211\u4eec\u5c06\u4f7f\u7528\u5b83\u4e0e\u8bed\u8a00\u6a21\u578b\u7ed3\u5408\u4f7f\u7528"]}, {"cell_type": "markdown", "id": "2963fc63", "metadata": {}, "source": ["### 1.1 \u521b\u5efa\u5411\u91cf\u5b58\u50a8\n", "\u5c06\u5bfc\u5165\u4e00\u4e2a\u7d22\u5f15\uff0c\u5373\u5411\u91cf\u5b58\u50a8\u7d22\u5f15\u521b\u5efa\u5668"]}, {"cell_type": "code", "execution_count": 25, "id": "5bfaba30", "metadata": {"height": 30}, "outputs": [], "source": ["from langchain.indexes import VectorstoreIndexCreator #\u5bfc\u5165\u5411\u91cf\u5b58\u50a8\u7d22\u5f15\u521b\u5efa\u5668"]}, {"cell_type": "code", "execution_count": null, "id": "9e200726", "metadata": {"height": 64}, "outputs": [], "source": ["'''\n", "\u5c06\u6307\u5b9a\u5411\u91cf\u5b58\u50a8\u7c7b,\u521b\u5efa\u5b8c\u6210\u540e\uff0c\u6211\u4eec\u5c06\u4ece\u52a0\u8f7d\u5668\u4e2d\u8c03\u7528,\u901a\u8fc7\u6587\u6863\u8bb0\u8f7d\u5668\u5217\u8868\u52a0\u8f7d\n", "'''\n", "\n", "index = VectorstoreIndexCreator(\n", " vectorstore_cls=DocArrayInMemorySearch\n", ").from_loaders([loader])"]}, {"cell_type": "code", "execution_count": 9, "id": "34562d81", "metadata": {"height": 47}, "outputs": [], "source": ["query =\"Please list all your shirts with sun protection \\\n", "in a table in markdown and summarize each one.\""]}, {"cell_type": "code", "execution_count": 21, "id": "cfd0cc37", "metadata": {"height": 30}, "outputs": [], "source": ["response = index.query(query)#\u4f7f\u7528\u7d22\u5f15\u67e5\u8be2\u521b\u5efa\u4e00\u4e2a\u54cd\u5e94\uff0c\u5e76\u4f20\u5165\u8fd9\u4e2a\u67e5\u8be2"]}, {"cell_type": "code", "execution_count": 23, "id": "ae21f1ff", "metadata": {"height": 30, "scrolled": true}, "outputs": [{"data": {"text/markdown": ["\n", "\n", "| Name | Description |\n", "| --- | --- |\n", "| Men's Tropical Plaid Short-Sleeve Shirt | UPF 50+ rated, 100% polyester, wrinkle-resistant, front and back cape venting, two front bellows pockets |\n", "| Men's Plaid Tropic Shirt, Short-Sleeve | UPF 50+ rated, 52% polyester and 48% nylon, machine washable and dryable, front and back cape venting, two front bellows pockets |\n", "| Men's TropicVibe Shirt, Short-Sleeve | UPF 50+ rated, 71% Nylon, 29% Polyester, 100% Polyester knit mesh, machine wash and dry, front and back cape venting, two front bellows pockets |\n", "| Sun Shield Shirt by | UPF 50+ rated, 78% nylon, 22% Lycra Xtra Life fiber, handwash, line dry, wicks moisture, fits comfortably over swimsuit, abrasion resistant |\n", "\n", "All four shirts provide UPF 50+ sun protection, blocking 98% of the sun's harmful rays. The Men's Tropical Plaid Short-Sleeve Shirt is made of 100% polyester and is wrinkle-resistant"], "text/plain": [""]}, "metadata": {}, "output_type": "display_data"}], "source": ["display(Markdown(response))#\u67e5\u770b\u67e5\u8be2\u8fd4\u56de\u7684\u5185\u5bb9"]}, {"cell_type": "markdown", "id": "eb74cc79", "metadata": {}, "source": ["\u5f97\u5230\u4e86\u4e00\u4e2aMarkdown\u8868\u683c\uff0c\u5176\u4e2d\u5305\u542b\u6240\u6709\u5e26\u6709\u9632\u6652\u8863\u7684\u886c\u886b\u7684\u540d\u79f0\u548c\u63cf\u8ff0\uff0c\u8fd8\u5f97\u5230\u4e86\u4e00\u4e2a\u8bed\u8a00\u6a21\u578b\u63d0\u4f9b\u7684\u4e0d\u9519\u7684\u5c0f\u603b\u7ed3"]}, {"cell_type": "markdown", "id": "dd34e50e", "metadata": {}, "source": ["### 1.2 \u4f7f\u7528\u8bed\u8a00\u6a21\u578b\u4e0e\u6587\u6863\u7ed3\u5408\u4f7f\u7528\n", "\u60f3\u8981\u4f7f\u7528\u8bed\u8a00\u6a21\u578b\u5e76\u5c06\u5176\u4e0e\u6211\u4eec\u7684\u8bb8\u591a\u6587\u6863\u7ed3\u5408\u4f7f\u7528\uff0c\u4f46\u662f\u8bed\u8a00\u6a21\u578b\u4e00\u6b21\u53ea\u80fd\u68c0\u67e5\u51e0\u5343\u4e2a\u5355\u8bcd\uff0c\u5982\u679c\u6211\u4eec\u6709\u975e\u5e38\u5927\u7684\u6587\u6863\uff0c\u5982\u4f55\u8ba9\u8bed\u8a00\u6a21\u578b\u56de\u7b54\u5173\u4e8e\u5176\u4e2d\u6240\u6709\u5185\u5bb9\u7684\u95ee\u9898\u5462\uff1f\u901a\u8fc7embedding\u548c\u5411\u91cf\u5b58\u50a8\u5b9e\u73b0\n", "* embedding \n", "\u6587\u672c\u7247\u6bb5\u521b\u5efa\u6570\u503c\u8868\u793a\u6587\u672c\u8bed\u4e49\uff0c\u76f8\u4f3c\u5185\u5bb9\u7684\u6587\u672c\u7247\u6bb5\u5c06\u5177\u6709\u76f8\u4f3c\u7684\u5411\u91cf\uff0c\u8fd9\u4f7f\u6211\u4eec\u53ef\u4ee5\u5728\u5411\u91cf\u7a7a\u95f4\u4e2d\u6bd4\u8f83\u6587\u672c\u7247\u6bb5\n", "* \u5411\u91cf\u6570\u636e\u5e93 \n", "\u5411\u91cf\u6570\u636e\u5e93\u662f\u5b58\u50a8\u6211\u4eec\u5728\u4e0a\u4e00\u6b65\u4e2d\u521b\u5efa\u7684\u8fd9\u4e9b\u5411\u91cf\u8868\u793a\u7684\u4e00\u79cd\u65b9\u5f0f\uff0c\u6211\u4eec\u521b\u5efa\u8fd9\u4e2a\u5411\u91cf\u6570\u636e\u5e93\u7684\u65b9\u5f0f\u662f\u7528\u6765\u81ea\u4f20\u5165\u6587\u6863\u7684\u6587\u672c\u5757\u586b\u5145\u5b83\u3002\n", "\u5f53\u6211\u4eec\u83b7\u5f97\u4e00\u4e2a\u5927\u7684\u4f20\u5165\u6587\u6863\u65f6\uff0c\u6211\u4eec\u9996\u5148\u5c06\u5176\u5206\u6210\u8f83\u5c0f\u7684\u5757\uff0c\u56e0\u4e3a\u6211\u4eec\u53ef\u80fd\u65e0\u6cd5\u5c06\u6574\u4e2a\u6587\u6863\u4f20\u9012\u7ed9\u8bed\u8a00\u6a21\u578b\uff0c\u56e0\u6b64\u91c7\u7528\u5206\u5757embedding\u7684\u65b9\u5f0f\u50a8\u5b58\u5230\u5411\u91cf\u6570\u636e\u5e93\u4e2d\u3002\u8fd9\u5c31\u662f\u521b\u5efa\u7d22\u5f15\u7684\u8fc7\u7a0b\u3002\n", "\n", "\u901a\u8fc7\u8fd0\u884c\u65f6\u4f7f\u7528\u7d22\u5f15\u6765\u67e5\u627e\u4e0e\u4f20\u5165\u67e5\u8be2\u6700\u76f8\u5173\u7684\u6587\u672c\u7247\u6bb5\uff0c\u7136\u540e\u6211\u4eec\u5c06\u5176\u4e0e\u5411\u91cf\u6570\u636e\u5e93\u4e2d\u7684\u6240\u6709\u5411\u91cf\u8fdb\u884c\u6bd4\u8f83\uff0c\u5e76\u9009\u62e9\u6700\u76f8\u4f3c\u7684n\u4e2a\uff0c\u8fd4\u56de\u8bed\u8a00\u6a21\u578b\u5f97\u5230\u6700\u7ec8\u7b54\u6848"]}, {"cell_type": "code", "execution_count": 26, "id": "631396c6", "metadata": {"height": 30}, "outputs": [], "source": ["#\u521b\u5efa\u4e00\u4e2a\u6587\u6863\u52a0\u8f7d\u5668\uff0c\u901a\u8fc7csv\u683c\u5f0f\u52a0\u8f7d\n", "loader = CSVLoader(file_path=file)\n", "docs = loader.load()"]}, {"cell_type": "code", "execution_count": 27, "id": "4a977f44", "metadata": {"height": 30}, "outputs": [{"data": {"text/plain": ["Document(page_content=\": 0\\nname: Women's Campside Oxfords\\ndescription: This ultracomfortable lace-to-toe Oxford boasts a super-soft canvas, thick cushioning, and quality construction for a broken-in feel from the first time you put them on. \\n\\nSize & Fit: Order regular shoe size. For half sizes not offered, order up to next whole size. \\n\\nSpecs: Approx. weight: 1 lb.1 oz. per pair. \\n\\nConstruction: Soft canvas material for a broken-in feel and look. Comfortable EVA innersole with Cleansport NXT\u00ae antimicrobial odor control. Vintage hunt, fish and camping motif on innersole. Moderate arch contour of innersole. EVA foam midsole for cushioning and support. Chain-tread-inspired molded rubber outsole with modified chain-tread pattern. Imported. \\n\\nQuestions? Please contact us for any inquiries.\", metadata={'source': 'OutdoorClothingCatalog_1000.csv', 'row': 0})"]}, "execution_count": 27, "metadata": {}, "output_type": "execute_result"}], "source": ["docs[0]#\u67e5\u770b\u5355\u4e2a\u6587\u6863\uff0c\u6211\u4eec\u53ef\u4ee5\u770b\u5230\u6bcf\u4e2a\u6587\u6863\u5bf9\u5e94\u4e8eCSV\u4e2d\u7684\u4e00\u4e2a\u5757"]}, {"cell_type": "code", "execution_count": 31, "id": "e875693a", "metadata": {"height": 47}, "outputs": [], "source": ["'''\n", "\u56e0\u4e3a\u8fd9\u4e9b\u6587\u6863\u5df2\u7ecf\u975e\u5e38\u5c0f\u4e86\uff0c\u6240\u4ee5\u6211\u4eec\u5b9e\u9645\u4e0a\u4e0d\u9700\u8981\u5728\u8fd9\u91cc\u8fdb\u884c\u4efb\u4f55\u5206\u5757,\u53ef\u4ee5\u76f4\u63a5\u8fdb\u884cembedding\n", "'''\n", "\n", "from langchain.embeddings import OpenAIEmbeddings #\u8981\u521b\u5efa\u53ef\u4ee5\u76f4\u63a5\u8fdb\u884cembedding\uff0c\u6211\u4eec\u5c06\u4f7f\u7528OpenAI\u7684\u53ef\u4ee5\u76f4\u63a5\u8fdb\u884cembedding\u7c7b\n", "embeddings = OpenAIEmbeddings() #\u521d\u59cb\u5316"]}, {"cell_type": "code", "execution_count": 32, "id": "779bec75", "metadata": {"height": 30}, "outputs": [], "source": ["embed = embeddings.embed_query(\"Hi my name is Harrison\")#\u8ba9\u6211\u4eec\u4f7f\u7528embedding\u4e0a\u7684\u67e5\u8be2\u65b9\u6cd5\u4e3a\u7279\u5b9a\u6587\u672c\u521b\u5efaembedding"]}, {"cell_type": "code", "execution_count": 33, "id": "699aaaf9", "metadata": {"height": 30}, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["1536\n"]}], "source": ["print(len(embed))#\u67e5\u770b\u8fd9\u4e2aembedding\uff0c\u6211\u4eec\u53ef\u4ee5\u770b\u5230\u6709\u8d85\u8fc7\u4e00\u5343\u4e2a\u4e0d\u540c\u7684\u5143\u7d20"]}, {"cell_type": "code", "execution_count": 34, "id": "9d00d346", "metadata": {"height": 30}, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["[-0.021933607757091522, 0.006697045173496008, -0.01819835603237152, -0.039113257080316544, -0.014060650952160358]\n"]}], "source": ["print(embed[:5])#\u6bcf\u4e2a\u5143\u7d20\u90fd\u662f\u4e0d\u540c\u7684\u6570\u5b57\u503c\uff0c\u7ec4\u5408\u8d77\u6765\uff0c\u8fd9\u5c31\u521b\u5efa\u4e86\u8fd9\u6bb5\u6587\u672c\u7684\u603b\u4f53\u6570\u503c\u8868\u793a"]}, {"cell_type": "code", "execution_count": 35, "id": "27ad0bb0", "metadata": {"height": 81}, "outputs": [], "source": ["'''\n", "\u4e3a\u521a\u624d\u7684\u6587\u672c\u521b\u5efaembedding\uff0c\u51c6\u5907\u5c06\u5b83\u4eec\u5b58\u50a8\u5728\u5411\u91cf\u5b58\u50a8\u4e2d\uff0c\u4f7f\u7528\u5411\u91cf\u5b58\u50a8\u4e0a\u7684from documents\u65b9\u6cd5\u6765\u5b9e\u73b0\u3002\n", "\u8be5\u65b9\u6cd5\u63a5\u53d7\u6587\u6863\u5217\u8868\u3001\u5d4c\u5165\u5bf9\u8c61\uff0c\u7136\u540e\u6211\u4eec\u5c06\u521b\u5efa\u4e00\u4e2a\u603b\u4f53\u5411\u91cf\u5b58\u50a8\n", "'''\n", "db = DocArrayInMemorySearch.from_documents(\n", " docs, \n", " embeddings\n", ")"]}, {"cell_type": "code", "execution_count": 36, "id": "0329bfd5", "metadata": {"height": 30}, "outputs": [], "source": ["query = \"Please suggest a shirt with sunblocking\""]}, {"cell_type": "code", "execution_count": 37, "id": "7909c6b7", "metadata": {"height": 30}, "outputs": [], "source": ["docs = db.similarity_search(query)#\u4f7f\u7528\u8fd9\u4e2a\u5411\u91cf\u5b58\u50a8\u6765\u67e5\u627e\u4e0e\u4f20\u5165\u67e5\u8be2\u7c7b\u4f3c\u7684\u6587\u672c\uff0c\u5982\u679c\u6211\u4eec\u5728\u5411\u91cf\u5b58\u50a8\u4e2d\u4f7f\u7528\u76f8\u4f3c\u6027\u641c\u7d22\u65b9\u6cd5\u5e76\u4f20\u5165\u4e00\u4e2a\u67e5\u8be2\uff0c\u6211\u4eec\u5c06\u5f97\u5230\u4e00\u4e2a\u6587\u6863\u5217\u8868"]}, {"cell_type": "code", "execution_count": 38, "id": "43321853", "metadata": {"height": 30}, "outputs": [{"data": {"text/plain": ["4"]}, "execution_count": 38, "metadata": {}, "output_type": "execute_result"}], "source": ["len(docs)# \u6211\u4eec\u53ef\u4ee5\u770b\u5230\u5b83\u8fd4\u56de\u4e86\u56db\u4e2a\u6587\u6863"]}, {"cell_type": "code", "execution_count": 39, "id": "6eba90b5", "metadata": {"height": 30}, "outputs": [{"data": {"text/plain": ["Document(page_content=': 255\\nname: Sun Shield Shirt by\\ndescription: \"Block the sun, not the fun \u2013 our high-performance sun shirt is guaranteed to protect from harmful UV rays. \\n\\nSize & Fit: Slightly Fitted: Softly shapes the body. Falls at hip.\\n\\nFabric & Care: 78% nylon, 22% Lycra Xtra Life fiber. UPF 50+ rated \u2013 the highest rated sun protection possible. Handwash, line dry.\\n\\nAdditional Features: Wicks moisture for quick-drying comfort. Fits comfortably over your favorite swimsuit. Abrasion resistant for season after season of wear. Imported.\\n\\nSun Protection That Won\\'t Wear Off\\nOur high-performance fabric provides SPF 50+ sun protection, blocking 98% of the sun\\'s harmful rays. This fabric is recommended by The Skin Cancer Foundation as an effective UV protectant.', metadata={'source': 'OutdoorClothingCatalog_1000.csv', 'row': 255})"]}, "execution_count": 39, "metadata": {}, "output_type": "execute_result"}], "source": ["docs[0] #\uff0c\u5982\u679c\u6211\u4eec\u770b\u7b2c\u4e00\u4e2a\u6587\u6863\uff0c\u6211\u4eec\u53ef\u4ee5\u770b\u5230\u5b83\u786e\u5b9e\u662f\u4e00\u4ef6\u5173\u4e8e\u9632\u6652\u7684\u886c\u886b"]}, {"cell_type": "markdown", "id": "fe41b36f", "metadata": {}, "source": ["## \u4e8c\u3001 \u5982\u4f55\u56de\u7b54\u6211\u4eec\u6587\u6863\u7684\u76f8\u5173\u95ee\u9898\n", "\u9996\u5148\uff0c\u6211\u4eec\u9700\u8981\u4ece\u8fd9\u4e2a\u5411\u91cf\u5b58\u50a8\u4e2d\u521b\u5efa\u4e00\u4e2a\u68c0\u7d22\u5668\uff0c\u68c0\u7d22\u5668\u662f\u4e00\u4e2a\u901a\u7528\u63a5\u53e3\uff0c\u53ef\u4ee5\u7531\u4efb\u4f55\u63a5\u53d7\u67e5\u8be2\u5e76\u8fd4\u56de\u6587\u6863\u7684\u65b9\u6cd5\u652f\u6301\u3002\u63a5\u4e0b\u6765\uff0c\u56e0\u4e3a\u6211\u4eec\u60f3\u8981\u8fdb\u884c\u6587\u672c\u751f\u6210\u5e76\u8fd4\u56de\u81ea\u7136\u8bed\u8a00\u54cd\u5e94\n"]}, {"cell_type": "code", "execution_count": 40, "id": "c0c3596e", "metadata": {"height": 30}, "outputs": [], "source": ["retriever = db.as_retriever() #\u521b\u5efa\u68c0\u7d22\u5668\u901a\u7528\u63a5\u53e3"]}, {"cell_type": "code", "execution_count": 55, "id": "0625f5e8", "metadata": {"height": 47}, "outputs": [], "source": ["llm = ChatOpenAI(temperature = 0.0,max_tokens=1024) #\u5bfc\u5165\u8bed\u8a00\u6a21\u578b\n"]}, {"cell_type": "code", "execution_count": 43, "id": "a573f58a", "metadata": {"height": 47}, "outputs": [], "source": ["qdocs = \"\".join([docs[i].page_content for i in range(len(docs))]) # \u5c06\u5408\u5e76\u6587\u6863\u4e2d\u7684\u6240\u6709\u9875\u9762\u5185\u5bb9\u5230\u4e00\u4e2a\u53d8\u91cf\u4e2d\n"]}, {"cell_type": "code", "execution_count": null, "id": "14682d95", "metadata": {"height": 64}, "outputs": [], "source": ["response = llm.call_as_llm(f\"{qdocs} Question: Please list all your \\\n", "shirts with sun protection in a table in markdown and summarize each one.\") #\u5217\u51fa\u6240\u6709\u5177\u6709\u9632\u6652\u529f\u80fd\u7684\u886c\u886b\u5e76\u5728Markdown\u8868\u683c\u4e2d\u603b\u7ed3\u6bcf\u4e2a\u886c\u886b\u7684\u8bed\u8a00\u6a21\u578b\n"]}, {"cell_type": "code", "execution_count": 28, "id": "8bba545b", "metadata": {"height": 30}, "outputs": [{"data": {"text/markdown": ["| Name | Description |\n", "| --- | --- |\n", "| Sun Shield Shirt | High-performance sun shirt with UPF 50+ sun protection, moisture-wicking, and abrasion-resistant fabric. Recommended by The Skin Cancer Foundation. |\n", "| Men's Plaid Tropic Shirt | Ultracomfortable shirt with UPF 50+ sun protection, wrinkle-free fabric, and front/back cape venting. Made with 52% polyester and 48% nylon. |\n", "| Men's TropicVibe Shirt | Men's sun-protection shirt with built-in UPF 50+ and front/back cape venting. Made with 71% nylon and 29% polyester. |\n", "| Men's Tropical Plaid Short-Sleeve Shirt | Lightest hot-weather shirt with UPF 50+ sun protection, front/back cape venting, and two front bellows pockets. Made with 100% polyester and is wrinkle-resistant. |\n", "\n", "All of these shirts provide UPF 50+ sun protection, blocking 98% of the sun's harmful rays. They are made with high-performance fabrics that are moisture-wicking, wrinkle-resistant, and abrasion-resistant. The Men's Plaid Tropic Shirt and Men's Tropical Plaid Short-Sleeve Shirt both have front/back cape venting for added breathability. The Sun Shield Shirt is recommended by The Skin Cancer Foundation as an effective UV protectant."], "text/plain": [""]}, "metadata": {}, "output_type": "display_data"}], "source": ["display(Markdown(response))"]}, {"cell_type": "markdown", "id": "12f042e7", "metadata": {}, "source": ["\u5728\u6b64\u5904\u6253\u5370\u54cd\u5e94\uff0c\u6211\u4eec\u53ef\u4ee5\u770b\u5230\u6211\u4eec\u5f97\u5230\u4e86\u4e00\u4e2a\u8868\u683c\uff0c\u6b63\u5982\u6211\u4eec\u6240\u8981\u6c42\u7684\u90a3\u6837"]}, {"cell_type": "code", "execution_count": 56, "id": "32c94d22", "metadata": {"height": 115}, "outputs": [], "source": ["''' \n", "\u901a\u8fc7LangChain\u94fe\u5c01\u88c5\u8d77\u6765\n", "\u521b\u5efa\u4e00\u4e2a\u68c0\u7d22QA\u94fe\uff0c\u5bf9\u68c0\u7d22\u5230\u7684\u6587\u6863\u8fdb\u884c\u95ee\u9898\u56de\u7b54\uff0c\u8981\u521b\u5efa\u8fd9\u6837\u7684\u94fe\uff0c\u6211\u4eec\u5c06\u4f20\u5165\u51e0\u4e2a\u4e0d\u540c\u7684\u4e1c\u897f\n", "1\u3001\u8bed\u8a00\u6a21\u578b\uff0c\u5728\u6700\u540e\u8fdb\u884c\u6587\u672c\u751f\u6210\n", "2\u3001\u4f20\u5165\u94fe\u7c7b\u578b\uff0c\u8fd9\u91cc\u4f7f\u7528stuff\uff0c\u5c06\u6240\u6709\u6587\u6863\u585e\u5165\u4e0a\u4e0b\u6587\u5e76\u5bf9\u8bed\u8a00\u6a21\u578b\u8fdb\u884c\u4e00\u6b21\u8c03\u7528\n", "3\u3001\u4f20\u5165\u4e00\u4e2a\u68c0\u7d22\u5668\n", "'''\n", "\n", "\n", "qa_stuff = RetrievalQA.from_chain_type(\n", " llm=llm, \n", " chain_type=\"stuff\", \n", " retriever=retriever, \n", " verbose=True\n", ")"]}, {"cell_type": "code", "execution_count": 46, "id": "e4769316", "metadata": {"height": 47}, "outputs": [], "source": ["query = \"Please list all your shirts with sun protection in a table \\\n", "in markdown and summarize each one.\"#\u521b\u5efa\u4e00\u4e2a\u67e5\u8be2\u5e76\u5728\u6b64\u67e5\u8be2\u4e0a\u8fd0\u884c\u94fe"]}, {"cell_type": "code", "execution_count": null, "id": "1fc3c2f3", "metadata": {"height": 30}, "outputs": [], "source": ["response = qa_stuff.run(query)"]}, {"cell_type": "code", "execution_count": 58, "id": "fba1a5db", "metadata": {"height": 30}, "outputs": [{"data": {"text/markdown": ["\n", "\n", "| Name | Description |\n", "| --- | --- |\n", "| Men's Tropical Plaid Short-Sleeve Shirt | UPF 50+ rated, 100% polyester, wrinkle-resistant, front and back cape venting, two front bellows pockets |\n", "| Men's Plaid Tropic Shirt, Short-Sleeve | UPF 50+ rated, 52% polyester and 48% nylon, machine washable and dryable, front and back cape venting, two front bellows pockets |\n", "| Men's TropicVibe Shirt, Short-Sleeve | UPF 50+ rated, 71% Nylon, 29% Polyester, 100% Polyester knit mesh, machine wash and dry, front and back cape venting, two front bellows pockets |\n", "| Sun Shield Shirt by | UPF 50+ rated, 78% nylon, 22% Lycra Xtra Life fiber, handwash, line dry, wicks moisture, fits comfortably over swimsuit, abrasion resistant |\n", "\n", "All four shirts provide UPF 50+ sun protection, blocking 98% of the sun's harmful rays. The Men's Tropical Plaid Short-Sleeve Shirt is made of 100% polyester and is wrinkle-resistant"], "text/plain": [""]}, "metadata": {}, "output_type": "display_data"}], "source": ["display(Markdown(response))#\u4f7f\u7528 display \u548c markdown \u663e\u793a\u5b83"]}, {"cell_type": "markdown", "id": "e28c5657", "metadata": {}, "source": ["\u8fd9\u4e24\u4e2a\u65b9\u5f0f\u8fd4\u56de\u76f8\u540c\u7684\u7ed3\u679c"]}, {"cell_type": "markdown", "id": "44f1fa38", "metadata": {}, "source": ["\u60f3\u5728\u8bb8\u591a\u4e0d\u540c\u7c7b\u578b\u7684\u5757\u4e0a\u6267\u884c\u76f8\u540c\u7c7b\u578b\u7684\u95ee\u7b54\uff0c\u8be5\u600e\u4e48\u529e\uff1f\u4e4b\u524d\u7684\u5b9e\u9a8c\u4e2d\u53ea\u8fd4\u56de\u4e864\u4e2a\u6587\u6863\uff0c\u5982\u679c\u6709\u591a\u4e2a\u6587\u6863\uff0c\u90a3\u4e48\u6211\u4eec\u53ef\u4ee5\u4f7f\u7528\u51e0\u79cd\u4e0d\u540c\u7684\u65b9\u6cd5\n", "* Map Reduce \n", "\u5c06\u6240\u6709\u5757\u4e0e\u95ee\u9898\u4e00\u8d77\u4f20\u9012\u7ed9\u8bed\u8a00\u6a21\u578b\uff0c\u83b7\u53d6\u56de\u590d\uff0c\u4f7f\u7528\u53e6\u4e00\u4e2a\u8bed\u8a00\u6a21\u578b\u8c03\u7528\u5c06\u6240\u6709\u5355\u72ec\u7684\u56de\u590d\u603b\u7ed3\u6210\u6700\u7ec8\u7b54\u6848\uff0c\u5b83\u53ef\u4ee5\u5728\u4efb\u610f\u6570\u91cf\u7684\u6587\u6863\u4e0a\u8fd0\u884c\u3002\u53ef\u4ee5\u5e76\u884c\u5904\u7406\u5355\u4e2a\u95ee\u9898\uff0c\u540c\u65f6\u4e5f\u9700\u8981\u66f4\u591a\u7684\u8c03\u7528\u3002\u5b83\u5c06\u6240\u6709\u6587\u6863\u89c6\u4e3a\u72ec\u7acb\u7684\n", "* Refine \n", "\u7528\u4e8e\u5faa\u73af\u8bb8\u591a\u6587\u6863\uff0c\u9645\u4e0a\u662f\u8fed\u4ee3\u7684\uff0c\u5efa\u7acb\u5728\u5148\u524d\u6587\u6863\u7684\u7b54\u6848\u4e4b\u4e0a\uff0c\u975e\u5e38\u9002\u5408\u524d\u540e\u56e0\u679c\u4fe1\u606f\u5e76\u968f\u65f6\u95f4\u9010\u6b65\u6784\u5efa\u7b54\u6848\uff0c\u4f9d\u8d56\u4e8e\u5148\u524d\u8c03\u7528\u7684\u7ed3\u679c\u3002\u5b83\u901a\u5e38\u9700\u8981\u66f4\u957f\u7684\u65f6\u95f4\uff0c\u5e76\u4e14\u57fa\u672c\u4e0a\u9700\u8981\u4e0eMap Reduce\u4e00\u6837\u591a\u7684\u8c03\u7528\n", "* Map Re-rank \n", "\u5bf9\u6bcf\u4e2a\u6587\u6863\u8fdb\u884c\u5355\u4e2a\u8bed\u8a00\u6a21\u578b\u8c03\u7528\uff0c\u8981\u6c42\u5b83\u8fd4\u56de\u4e00\u4e2a\u5206\u6570\uff0c\u9009\u62e9\u6700\u9ad8\u5206\uff0c\u8fd9\u4f9d\u8d56\u4e8e\u8bed\u8a00\u6a21\u578b\u77e5\u9053\u5206\u6570\u5e94\u8be5\u662f\u4ec0\u4e48\uff0c\u9700\u8981\u544a\u8bc9\u5b83\uff0c\u5982\u679c\u5b83\u4e0e\u6587\u6863\u76f8\u5173\uff0c\u5219\u5e94\u8be5\u662f\u9ad8\u5206\uff0c\u5e76\u5728\u90a3\u91cc\u7cbe\u7ec6\u8c03\u6574\u8bf4\u660e\uff0c\u53ef\u4ee5\u6279\u91cf\u5904\u7406\u5b83\u4eec\u76f8\u5bf9\u8f83\u5feb\uff0c\u4f46\u662f\u66f4\u52a0\u6602\u8d35\n", "* Stuff \n", "\u5c06\u6240\u6709\u5185\u5bb9\u7ec4\u5408\u6210\u4e00\u4e2a\u6587\u6863"]}, {"cell_type": "code", "execution_count": null, "id": "41c9d68a-251a-41f1-a571-f6a13b3d7b40", "metadata": {}, "outputs": [], "source": []}], "metadata": {"kernelspec": {"display_name": "Python 3 (ipykernel)", "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.9.12"}, "toc": {"base_numbering": 1, "nav_menu": {}, "number_sections": false, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": true}}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
+{"cells":[{"cell_type":"markdown","id":"f200ba9a","metadata":{},"source":["# 第五章 基于文档的问答\n","\n"," - [一、设置OpenAI API Key](#一、设置OpenAI-API-Key)\n"," - [一、导入embedding模型和向量存储组件](#一、导入embedding模型和向量存储组件)\n"," - [1.1 创建向量存储](#1.1-创建向量存储)\n"," - [1.2 使用语言模型与文档结合使用](#1.2-使用语言模型与文档结合使用)\n"," - [二、 如何回答我们文档的相关问题](#二、-如何回答我们文档的相关问题)\n"]},{"cell_type":"markdown","id":"52824b89-532a-4e54-87e9-1410813cd39e","metadata":{},"source":["\n","本章内容主要利用langchain构建向量数据库,可以在文档上方或关于文档回答问题,因此,给定从PDF文件、网页或某些公司的内部文档收集中提取的文本,使用llm回答有关这些文档内容的问题"]},{"cell_type":"markdown","id":"42ccf132-cfab-4153-97b5-d545faae4d36","metadata":{"tags":[]},"source":["## 一、设置OpenAI API Key\n","\n","登陆 [OpenAI 账户](https://platform.openai.com/account/api-keys) 获取API Key,然后将其设置为环境变量。\n","\n","- 如果你想要设置为全局环境变量,可以参考[知乎文章](https://zhuanlan.zhihu.com/p/627665725)。\n","- 如果你想要设置为本地/项目环境变量,在本文件目录下创建`.env`文件, 打开文件输入以下内容。\n","\n"," \n"," OPENAI_API_KEY=\"your_api_key\" \n","
\n"," \n"," 替换\"your_api_key\"为你自己的 API Key"]},{"cell_type":"code","execution_count":1,"id":"cc33ceb1-535f-454d-988c-347a8b14fd72","metadata":{},"outputs":[],"source":["# 下载需要的包python-dotenv和openai\n","# 如果你需要查看安装过程日志,可删除 -q \n","!pip install -q python-dotenv\n","!pip install -q openai"]},{"cell_type":"code","execution_count":2,"id":"e3c97235-f101-47f2-92db-1c37f4bf9845","metadata":{"tags":[]},"outputs":[],"source":["import os\n","import openai\n","from dotenv import load_dotenv, find_dotenv\n","\n","# 读取本地/项目的环境变量。\n","\n","# find_dotenv()寻找并定位.env文件的路径\n","# load_dotenv()读取该.env文件,并将其中的环境变量加载到当前的运行环境中 \n","# 如果你设置的是全局的环境变量,这行代码则没有任何作用。\n","_ = load_dotenv(find_dotenv())\n","\n","# 获取环境变量 OPENAI_API_KEY\n","openai.api_key = os.environ['OPENAI_API_KEY'] "]},{"cell_type":"code","execution_count":52,"id":"af8c3c96","metadata":{},"outputs":[{"data":{"text/plain":["'\\n\\n人工智能是一项极具前景的技术,它的发展正在改变人类的生活方式,带来了无数的便利,也被认为是未来发展的重要标志。人工智能的发展让许多复杂的任务变得更加容易,更高效的完成,节省了大量的时间和精力,为人类发展带来了极大的帮助。'"]},"execution_count":52,"metadata":{},"output_type":"execute_result"}],"source":["from langchain.llms import OpenAI\n","\n","llm = OpenAI(model_name=\"text-davinci-003\",max_tokens=1024)\n","llm(\"怎么评价人工智能\")"]},{"cell_type":"markdown","id":"8cb7a7ec","metadata":{"height":30},"source":["## 一、导入embedding模型和向量存储组件\n","使用Dock Array内存搜索向量存储,作为一个内存向量存储,不需要连接外部数据库"]},{"cell_type":"code","execution_count":3,"id":"974acf8e-8f88-42de-88f8-40a82cb58e8b","metadata":{"height":98},"outputs":[],"source":["from langchain.chains import RetrievalQA #检索QA链,在文档上进行检索\n","from langchain.chat_models import ChatOpenAI #openai模型\n","from langchain.document_loaders import CSVLoader #文档加载器,采用csv格式存储\n","from langchain.vectorstores import DocArrayInMemorySearch #向量存储\n","from IPython.display import display, Markdown #在jupyter显示信息的工具"]},{"cell_type":"code","execution_count":4,"id":"7249846e","metadata":{"height":75},"outputs":[],"source":["#读取文件\n","file = 'OutdoorClothingCatalog_1000.csv'\n","loader = CSVLoader(file_path=file)"]},{"cell_type":"code","execution_count":24,"id":"7724f00e","metadata":{"height":30},"outputs":[{"data":{"text/html":["\n","\n","
\n"," \n"," \n"," | \n"," 0 | \n"," 1 | \n"," 2 | \n","
\n"," \n"," \n"," \n"," | 0 | \n"," NaN | \n"," name | \n"," description | \n","
\n"," \n"," | 1 | \n"," 0.0 | \n"," Women's Campside Oxfords | \n"," This ultracomfortable lace-to-toe Oxford boast... | \n","
\n"," \n"," | 2 | \n"," 1.0 | \n"," Recycled Waterhog Dog Mat, Chevron Weave | \n"," Protect your floors from spills and splashing ... | \n","
\n"," \n"," | 3 | \n"," 2.0 | \n"," Infant and Toddler Girls' Coastal Chill Swimsu... | \n"," She'll love the bright colors, ruffles and exc... | \n","
\n"," \n"," | 4 | \n"," 3.0 | \n"," Refresh Swimwear, V-Neck Tankini Contrasts | \n"," Whether you're going for a swim or heading out... | \n","
\n"," \n"," | ... | \n"," ... | \n"," ... | \n"," ... | \n","
\n"," \n"," | 996 | \n"," 995.0 | \n"," Men's Classic Denim, Standard Fit | \n"," Crafted from premium denim that will last wash... | \n","
\n"," \n"," | 997 | \n"," 996.0 | \n"," CozyPrint Sweater Fleece Pullover | \n"," The ultimate sweater fleece - made from superi... | \n","
\n"," \n"," | 998 | \n"," 997.0 | \n"," Women's NRS Endurance Spray Paddling Pants | \n"," These comfortable and affordable splash paddli... | \n","
\n"," \n"," | 999 | \n"," 998.0 | \n"," Women's Stop Flies Hoodie | \n"," This great-looking hoodie uses No Fly Zone Tec... | \n","
\n"," \n"," | 1000 | \n"," 999.0 | \n"," Modern Utility Bag | \n"," This US-made crossbody bag is built with the s... | \n","
\n"," \n","
\n","
1001 rows × 3 columns
\n","
"],"text/plain":[" 0 1 \n","0 NaN name \\\n","1 0.0 Women's Campside Oxfords \n","2 1.0 Recycled Waterhog Dog Mat, Chevron Weave \n","3 2.0 Infant and Toddler Girls' Coastal Chill Swimsu... \n","4 3.0 Refresh Swimwear, V-Neck Tankini Contrasts \n","... ... ... \n","996 995.0 Men's Classic Denim, Standard Fit \n","997 996.0 CozyPrint Sweater Fleece Pullover \n","998 997.0 Women's NRS Endurance Spray Paddling Pants \n","999 998.0 Women's Stop Flies Hoodie \n","1000 999.0 Modern Utility Bag \n","\n"," 2 \n","0 description \n","1 This ultracomfortable lace-to-toe Oxford boast... \n","2 Protect your floors from spills and splashing ... \n","3 She'll love the bright colors, ruffles and exc... \n","4 Whether you're going for a swim or heading out... \n","... ... \n","996 Crafted from premium denim that will last wash... \n","997 The ultimate sweater fleece - made from superi... \n","998 These comfortable and affordable splash paddli... \n","999 This great-looking hoodie uses No Fly Zone Tec... \n","1000 This US-made crossbody bag is built with the s... \n","\n","[1001 rows x 3 columns]"]},"execution_count":24,"metadata":{},"output_type":"execute_result"}],"source":["#查看数据\n","import pandas as pd\n","data = pd.read_csv(file,header=None)\n","data"]},{"cell_type":"markdown","id":"3bd6422c","metadata":{},"source":["提供了一个户外服装的CSV文件,我们将使用它与语言模型结合使用"]},{"cell_type":"markdown","id":"2963fc63","metadata":{},"source":["### 1.1 创建向量存储\n","将导入一个索引,即向量存储索引创建器"]},{"cell_type":"code","execution_count":25,"id":"5bfaba30","metadata":{"height":30},"outputs":[],"source":["from langchain.indexes import VectorstoreIndexCreator #导入向量存储索引创建器"]},{"cell_type":"code","execution_count":null,"id":"9e200726","metadata":{"height":64},"outputs":[],"source":["'''\n","将指定向量存储类,创建完成后,我们将从加载器中调用,通过文档记载器列表加载\n","'''\n","\n","index = VectorstoreIndexCreator(\n"," vectorstore_cls=DocArrayInMemorySearch\n",").from_loaders([loader])"]},{"cell_type":"code","execution_count":9,"id":"34562d81","metadata":{"height":47},"outputs":[],"source":["query =\"Please list all your shirts with sun protection \\\n","in a table in markdown and summarize each one.\""]},{"cell_type":"code","execution_count":21,"id":"cfd0cc37","metadata":{"height":30},"outputs":[],"source":["response = index.query(query)#使用索引查询创建一个响应,并传入这个查询"]},{"cell_type":"code","execution_count":23,"id":"ae21f1ff","metadata":{"height":30,"scrolled":true},"outputs":[{"data":{"text/markdown":["\n","\n","| Name | Description |\n","| --- | --- |\n","| Men's Tropical Plaid Short-Sleeve Shirt | UPF 50+ rated, 100% polyester, wrinkle-resistant, front and back cape venting, two front bellows pockets |\n","| Men's Plaid Tropic Shirt, Short-Sleeve | UPF 50+ rated, 52% polyester and 48% nylon, machine washable and dryable, front and back cape venting, two front bellows pockets |\n","| Men's TropicVibe Shirt, Short-Sleeve | UPF 50+ rated, 71% Nylon, 29% Polyester, 100% Polyester knit mesh, machine wash and dry, front and back cape venting, two front bellows pockets |\n","| Sun Shield Shirt by | UPF 50+ rated, 78% nylon, 22% Lycra Xtra Life fiber, handwash, line dry, wicks moisture, fits comfortably over swimsuit, abrasion resistant |\n","\n","All four shirts provide UPF 50+ sun protection, blocking 98% of the sun's harmful rays. The Men's Tropical Plaid Short-Sleeve Shirt is made of 100% polyester and is wrinkle-resistant"],"text/plain":[""]},"metadata":{},"output_type":"display_data"}],"source":["display(Markdown(response))#查看查询返回的内容"]},{"cell_type":"markdown","id":"eb74cc79","metadata":{},"source":["得到了一个Markdown表格,其中包含所有带有防晒衣的衬衫的名称和描述,还得到了一个语言模型提供的不错的小总结"]},{"cell_type":"markdown","id":"dd34e50e","metadata":{},"source":["### 1.2 使用语言模型与文档结合使用\n","想要使用语言模型并将其与我们的许多文档结合使用,但是语言模型一次只能检查几千个单词,如果我们有非常大的文档,如何让语言模型回答关于其中所有内容的问题呢?通过embedding和向量存储实现\n","* embedding \n","文本片段创建数值表示文本语义,相似内容的文本片段将具有相似的向量,这使我们可以在向量空间中比较文本片段\n","* 向量数据库 \n","向量数据库是存储我们在上一步中创建的这些向量表示的一种方式,我们创建这个向量数据库的方式是用来自传入文档的文本块填充它。\n","当我们获得一个大的传入文档时,我们首先将其分成较小的块,因为我们可能无法将整个文档传递给语言模型,因此采用分块embedding的方式储存到向量数据库中。这就是创建索引的过程。\n","\n","通过运行时使用索引来查找与传入查询最相关的文本片段,然后我们将其与向量数据库中的所有向量进行比较,并选择最相似的n个,返回语言模型得到最终答案"]},{"cell_type":"code","execution_count":26,"id":"631396c6","metadata":{"height":30},"outputs":[],"source":["#创建一个文档加载器,通过csv格式加载\n","loader = CSVLoader(file_path=file)\n","docs = loader.load()"]},{"cell_type":"code","execution_count":27,"id":"4a977f44","metadata":{"height":30},"outputs":[{"data":{"text/plain":["Document(page_content=\": 0\\nname: Women's Campside Oxfords\\ndescription: This ultracomfortable lace-to-toe Oxford boasts a super-soft canvas, thick cushioning, and quality construction for a broken-in feel from the first time you put them on. \\n\\nSize & Fit: Order regular shoe size. For half sizes not offered, order up to next whole size. \\n\\nSpecs: Approx. weight: 1 lb.1 oz. per pair. \\n\\nConstruction: Soft canvas material for a broken-in feel and look. Comfortable EVA innersole with Cleansport NXT® antimicrobial odor control. Vintage hunt, fish and camping motif on innersole. Moderate arch contour of innersole. EVA foam midsole for cushioning and support. Chain-tread-inspired molded rubber outsole with modified chain-tread pattern. Imported. \\n\\nQuestions? Please contact us for any inquiries.\", metadata={'source': 'OutdoorClothingCatalog_1000.csv', 'row': 0})"]},"execution_count":27,"metadata":{},"output_type":"execute_result"}],"source":["docs[0]#查看单个文档,我们可以看到每个文档对应于CSV中的一个块"]},{"cell_type":"code","execution_count":31,"id":"e875693a","metadata":{"height":47},"outputs":[],"source":["'''\n","因为这些文档已经非常小了,所以我们实际上不需要在这里进行任何分块,可以直接进行embedding\n","'''\n","\n","from langchain.embeddings import OpenAIEmbeddings #要创建可以直接进行embedding,我们将使用OpenAI的可以直接进行embedding类\n","embeddings = OpenAIEmbeddings() #初始化"]},{"cell_type":"code","execution_count":32,"id":"779bec75","metadata":{"height":30},"outputs":[],"source":["embed = embeddings.embed_query(\"Hi my name is Harrison\")#让我们使用embedding上的查询方法为特定文本创建embedding"]},{"cell_type":"code","execution_count":33,"id":"699aaaf9","metadata":{"height":30},"outputs":[{"name":"stdout","output_type":"stream","text":["1536\n"]}],"source":["print(len(embed))#查看这个embedding,我们可以看到有超过一千个不同的元素"]},{"cell_type":"code","execution_count":34,"id":"9d00d346","metadata":{"height":30},"outputs":[{"name":"stdout","output_type":"stream","text":["[-0.021933607757091522, 0.006697045173496008, -0.01819835603237152, -0.039113257080316544, -0.014060650952160358]\n"]}],"source":["print(embed[:5])#每个元素都是不同的数字值,组合起来,这就创建了这段文本的总体数值表示"]},{"cell_type":"code","execution_count":35,"id":"27ad0bb0","metadata":{"height":81},"outputs":[],"source":["'''\n","为刚才的文本创建embedding,准备将它们存储在向量存储中,使用向量存储上的from documents方法来实现。\n","该方法接受文档列表、嵌入对象,然后我们将创建一个总体向量存储\n","'''\n","db = DocArrayInMemorySearch.from_documents(\n"," docs, \n"," embeddings\n",")"]},{"cell_type":"code","execution_count":36,"id":"0329bfd5","metadata":{"height":30},"outputs":[],"source":["query = \"Please suggest a shirt with sunblocking\""]},{"cell_type":"code","execution_count":37,"id":"7909c6b7","metadata":{"height":30},"outputs":[],"source":["docs = db.similarity_search(query)#使用这个向量存储来查找与传入查询类似的文本,如果我们在向量存储中使用相似性搜索方法并传入一个查询,我们将得到一个文档列表"]},{"cell_type":"code","execution_count":38,"id":"43321853","metadata":{"height":30},"outputs":[{"data":{"text/plain":["4"]},"execution_count":38,"metadata":{},"output_type":"execute_result"}],"source":["len(docs)# 我们可以看到它返回了四个文档"]},{"cell_type":"code","execution_count":39,"id":"6eba90b5","metadata":{"height":30},"outputs":[{"data":{"text/plain":["Document(page_content=': 255\\nname: Sun Shield Shirt by\\ndescription: \"Block the sun, not the fun – our high-performance sun shirt is guaranteed to protect from harmful UV rays. \\n\\nSize & Fit: Slightly Fitted: Softly shapes the body. Falls at hip.\\n\\nFabric & Care: 78% nylon, 22% Lycra Xtra Life fiber. UPF 50+ rated – the highest rated sun protection possible. Handwash, line dry.\\n\\nAdditional Features: Wicks moisture for quick-drying comfort. Fits comfortably over your favorite swimsuit. Abrasion resistant for season after season of wear. Imported.\\n\\nSun Protection That Won\\'t Wear Off\\nOur high-performance fabric provides SPF 50+ sun protection, blocking 98% of the sun\\'s harmful rays. This fabric is recommended by The Skin Cancer Foundation as an effective UV protectant.', metadata={'source': 'OutdoorClothingCatalog_1000.csv', 'row': 255})"]},"execution_count":39,"metadata":{},"output_type":"execute_result"}],"source":["docs[0] #,如果我们看第一个文档,我们可以看到它确实是一件关于防晒的衬衫"]},{"cell_type":"markdown","id":"fe41b36f","metadata":{},"source":["## 二、 如何回答我们文档的相关问题\n","首先,我们需要从这个向量存储中创建一个检索器,检索器是一个通用接口,可以由任何接受查询并返回文档的方法支持。接下来,因为我们想要进行文本生成并返回自然语言响应\n"]},{"cell_type":"code","execution_count":40,"id":"c0c3596e","metadata":{"height":30},"outputs":[],"source":["retriever = db.as_retriever() #创建检索器通用接口"]},{"cell_type":"code","execution_count":55,"id":"0625f5e8","metadata":{"height":47},"outputs":[],"source":["llm = ChatOpenAI(temperature = 0.0,max_tokens=1024) #导入语言模型\n"]},{"cell_type":"code","execution_count":43,"id":"a573f58a","metadata":{"height":47},"outputs":[],"source":["qdocs = \"\".join([docs[i].page_content for i in range(len(docs))]) # 将合并文档中的所有页面内容到一个变量中\n"]},{"cell_type":"code","execution_count":null,"id":"14682d95","metadata":{"height":64},"outputs":[],"source":["response = llm.call_as_llm(f\"{qdocs} Question: Please list all your \\\n","shirts with sun protection in a table in markdown and summarize each one.\") #列出所有具有防晒功能的衬衫并在Markdown表格中总结每个衬衫的语言模型\n"]},{"cell_type":"code","execution_count":28,"id":"8bba545b","metadata":{"height":30},"outputs":[{"data":{"text/markdown":["| Name | Description |\n","| --- | --- |\n","| Sun Shield Shirt | High-performance sun shirt with UPF 50+ sun protection, moisture-wicking, and abrasion-resistant fabric. Recommended by The Skin Cancer Foundation. |\n","| Men's Plaid Tropic Shirt | Ultracomfortable shirt with UPF 50+ sun protection, wrinkle-free fabric, and front/back cape venting. Made with 52% polyester and 48% nylon. |\n","| Men's TropicVibe Shirt | Men's sun-protection shirt with built-in UPF 50+ and front/back cape venting. Made with 71% nylon and 29% polyester. |\n","| Men's Tropical Plaid Short-Sleeve Shirt | Lightest hot-weather shirt with UPF 50+ sun protection, front/back cape venting, and two front bellows pockets. Made with 100% polyester and is wrinkle-resistant. |\n","\n","All of these shirts provide UPF 50+ sun protection, blocking 98% of the sun's harmful rays. They are made with high-performance fabrics that are moisture-wicking, wrinkle-resistant, and abrasion-resistant. The Men's Plaid Tropic Shirt and Men's Tropical Plaid Short-Sleeve Shirt both have front/back cape venting for added breathability. The Sun Shield Shirt is recommended by The Skin Cancer Foundation as an effective UV protectant."],"text/plain":[""]},"metadata":{},"output_type":"display_data"}],"source":["display(Markdown(response))"]},{"cell_type":"markdown","id":"12f042e7","metadata":{},"source":["在此处打印响应,我们可以看到我们得到了一个表格,正如我们所要求的那样"]},{"cell_type":"code","execution_count":56,"id":"32c94d22","metadata":{"height":115},"outputs":[],"source":["''' \n","通过LangChain链封装起来\n","创建一个检索QA链,对检索到的文档进行问题回答,要创建这样的链,我们将传入几个不同的东西\n","1、语言模型,在最后进行文本生成\n","2、传入链类型,这里使用stuff,将所有文档塞入上下文并对语言模型进行一次调用\n","3、传入一个检索器\n","'''\n","\n","\n","qa_stuff = RetrievalQA.from_chain_type(\n"," llm=llm, \n"," chain_type=\"stuff\", \n"," retriever=retriever, \n"," verbose=True\n",")"]},{"cell_type":"code","execution_count":46,"id":"e4769316","metadata":{"height":47},"outputs":[],"source":["query = \"Please list all your shirts with sun protection in a table \\\n","in markdown and summarize each one.\"#创建一个查询并在此查询上运行链"]},{"cell_type":"code","execution_count":null,"id":"1fc3c2f3","metadata":{"height":30},"outputs":[],"source":["response = qa_stuff.run(query)"]},{"cell_type":"code","execution_count":58,"id":"fba1a5db","metadata":{"height":30},"outputs":[{"data":{"text/markdown":["\n","\n","| Name | Description |\n","| --- | --- |\n","| Men's Tropical Plaid Short-Sleeve Shirt | UPF 50+ rated, 100% polyester, wrinkle-resistant, front and back cape venting, two front bellows pockets |\n","| Men's Plaid Tropic Shirt, Short-Sleeve | UPF 50+ rated, 52% polyester and 48% nylon, machine washable and dryable, front and back cape venting, two front bellows pockets |\n","| Men's TropicVibe Shirt, Short-Sleeve | UPF 50+ rated, 71% Nylon, 29% Polyester, 100% Polyester knit mesh, machine wash and dry, front and back cape venting, two front bellows pockets |\n","| Sun Shield Shirt by | UPF 50+ rated, 78% nylon, 22% Lycra Xtra Life fiber, handwash, line dry, wicks moisture, fits comfortably over swimsuit, abrasion resistant |\n","\n","All four shirts provide UPF 50+ sun protection, blocking 98% of the sun's harmful rays. The Men's Tropical Plaid Short-Sleeve Shirt is made of 100% polyester and is wrinkle-resistant"],"text/plain":[""]},"metadata":{},"output_type":"display_data"}],"source":["display(Markdown(response))#使用 display 和 markdown 显示它"]},{"cell_type":"markdown","id":"e28c5657","metadata":{},"source":["这两个方式返回相同的结果"]},{"cell_type":"markdown","id":"44f1fa38","metadata":{},"source":["想在许多不同类型的块上执行相同类型的问答,该怎么办?之前的实验中只返回了4个文档,如果有多个文档,那么我们可以使用几种不同的方法\n","* Map Reduce \n","将所有块与问题一起传递给语言模型,获取回复,使用另一个语言模型调用将所有单独的回复总结成最终答案,它可以在任意数量的文档上运行。可以并行处理单个问题,同时也需要更多的调用。它将所有文档视为独立的\n","* Refine \n","用于循环许多文档,际上是迭代的,建立在先前文档的答案之上,非常适合前后因果信息并随时间逐步构建答案,依赖于先前调用的结果。它通常需要更长的时间,并且基本上需要与Map Reduce一样多的调用\n","* Map Re-rank \n","对每个文档进行单个语言模型调用,要求它返回一个分数,选择最高分,这依赖于语言模型知道分数应该是什么,需要告诉它,如果它与文档相关,则应该是高分,并在那里精细调整说明,可以批量处理它们相对较快,但是更加昂贵\n","* Stuff \n","将所有内容组合成一个文档"]}],"metadata":{"kernelspec":{"display_name":"Python 3 (ipykernel)","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.9.12"},"toc":{"base_numbering":1,"nav_menu":{},"number_sections":false,"sideBar":true,"skip_h1_title":false,"title_cell":"Table of Contents","title_sidebar":"Contents","toc_cell":false,"toc_position":{},"toc_section_display":true,"toc_window_display":true}},"nbformat":4,"nbformat_minor":5}