遷移
LangChain v0.2 已於 2024 年 5 月發布。此版本包含許多重大變更和棄用。本文檔包含升級到 0.2.x 的指南。
遷移
此文件將幫助您將程式碼升級到 LangChain 0.2.x.
。為了準備遷移,我們首先建議您採取以下步驟
- 安裝 0.2.x 版本的 langchain-core、langchain,並升級到您可能正在使用的其他套件的最新版本。(例如 langgraph、langchain-community、langchain-openai 等)
- 驗證您的程式碼在新套件下是否正常運行(例如,單元測試通過)。
- 安裝最新版本的
langchain-cli
,並使用該工具將程式碼使用的舊導入替換為新導入。(請參閱以下說明。) - 手動解決任何剩餘的棄用警告。
- 重新運行單元測試。
- 如果您正在使用
astream_events
,請查看如何遷移到 astream events v2。
升級到新的導入
我們建立了一個工具來幫助遷移您的程式碼。此工具仍處於測試階段,可能無法涵蓋所有情況,但我們希望它能幫助您更快地遷移程式碼。
遷移腳本具有以下限制
- 它僅限於幫助用戶從舊導入移動到新導入。它不協助解決其他棄用問題。
- 它無法處理涉及
as
的導入。 - 新導入始終放置在全局範圍內,即使替換的舊導入位於某些局部範圍內(例如,函數體)。
- 它可能會遺漏一些已棄用的導入。
以下是遷移腳本可以幫助自動應用的導入變更範例
來自套件 | 到套件 | 已棄用的導入 | 新的導入 |
---|---|---|---|
langchain | langchain-community | from langchain.vectorstores import InMemoryVectorStore | from langchain_community.vectorstores import InMemoryVectorStore |
langchain-community | langchain_openai | from langchain_community.chat_models import ChatOpenAI | from langchain_openai import ChatOpenAI |
langchain-community | langchain-core | from langchain_community.document_loaders import Blob | from langchain_core.document_loaders import Blob |
langchain | langchain-core | from langchain.schema.document import Document | from langchain_core.documents import Document |
langchain | langchain-text-splitters | from langchain.text_splitter import RecursiveCharacterTextSplitter | from langchain_text_splitters import RecursiveCharacterTextSplitter |
安裝
pip install langchain-cli
langchain-cli --version # <-- Make sure the version is at least 0.0.22
用法
鑑於遷移腳本並不完美,您應確保首先備份您的程式碼(例如,使用版本控制,如 git
)。
您需要運行遷移腳本兩次,因為它每次運行只應用一個導入替換。
例如,假設您的程式碼仍然使用 from langchain.chat_models import ChatOpenAI
在第一次運行後,您將得到:from langchain_community.chat_models import ChatOpenAI
在第二次運行後,您將得到:from langchain_openai import ChatOpenAI
# Run a first time
# Will replace from langchain.chat_models import ChatOpenAI
langchain-cli migrate --diff [path to code] # Preview
langchain-cli migrate [path to code] # Apply
# Run a second time to apply more import replacements
langchain-cli migrate --diff [path to code] # Preview
langchain-cli migrate [path to code] # Apply
其他選項
# See help menu
langchain-cli migrate --help
# Preview Changes without applying
langchain-cli migrate --diff [path to code]
# Run on code including ipython notebooks
# Apply all import updates except for updates from langchain to langchain-core
langchain-cli migrate --disable langchain_to_core --include-ipynb [path to code]