import langchain
from dotenv import load_dotenv
from langchain.chains import HypotheticalDocumentEmbedder, RetrievalQA
from langchain.chat_models import ChatOpenAI
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import FAISS

langchain.debug = True

load_dotenv()

# HyDE (LLMが生成した仮説的な回答のベクトル化) の準備
base_embeddings = OpenAIEmbeddings()
chat = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)
embeddings = HypotheticalDocumentEmbedder.from_llm(chat, base_embeddings, "web_search")

# FAISSで保存されたベクトルを読み込む
db = FAISS.load_local("./tmp/faiss", embeddings)
retriever = db.as_retriever()

# 「関連する文書を検索 => LLMに回答を生成させる」を実行する「RetrievalQA」を準備
qa_chain = RetrievalQA.from_chain_type(
    llm=chat, chain_type="stuff", retriever=retriever
)

query = "LangChainとは"
result = qa_chain.run(query)
print(result)

langchain.chains.RetrievalQA.from_chain_type langchain.vectorstores.FAISS.load_local langchain.chat_models.ChatOpenAI langchain.chains.HypotheticalDocumentEmbedder.from_llm langchain.embeddings.OpenAIEmbeddings
[((280, 293), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (291, 293), False, 'from dotenv import load_dotenv\n'), ((347, 365), 'langchain.embeddings.OpenAIEmbeddings', 'OpenAIEmbeddings', ([], {}), '()\n', (363, 365), False, 'from langchain.embeddings import OpenAIEmbeddings\n'), ((373, 426), 'langchain.chat_models.ChatOpenAI', 'ChatOpenAI', ([], {'model_name': '"""gpt-3.5-turbo"""', 'temperature': '(0)'}), "(model_name='gpt-3.5-turbo', temperature=0)\n", (383, 426), False, 'from langchain.chat_models import ChatOpenAI\n'), ((440, 514), 'langchain.chains.HypotheticalDocumentEmbedder.from_llm', 'HypotheticalDocumentEmbedder.from_llm', (['chat', 'base_embeddings', '"""web_search"""'], {}), "(chat, base_embeddings, 'web_search')\n", (477, 514), False, 'from langchain.chains import HypotheticalDocumentEmbedder, RetrievalQA\n'), ((544, 587), 'langchain.vectorstores.FAISS.load_local', 'FAISS.load_local', (['"""./tmp/faiss"""', 'embeddings'], {}), "('./tmp/faiss', embeddings)\n", (560, 587), False, 'from langchain.vectorstores import FAISS\n'), ((681, 759), 'langchain.chains.RetrievalQA.from_chain_type', 'RetrievalQA.from_chain_type', ([], {'llm': 'chat', 'chain_type': '"""stuff"""', 'retriever': 'retriever'}), "(llm=chat, chain_type='stuff', retriever=retriever)\n", (708, 759), False, 'from langchain.chains import HypotheticalDocumentEmbedder, RetrievalQA\n')]