LoginSignup
8
1

概要

Langchainって最近聞くけどいったい何ですか?って人はかなり多いと思います。

LangChain is a framework for developing applications powered by language models.

つまり、「GPTみたいなLLM(大規模言語モデル)を使ってアプリケーションを開発をしたい!」ってときに手助けをしてくれるものなんですね。しかも、ただ単にLLMに接続できる、というわけではなくGPTに知識を追加で与えたりなどいろんな機能拡張をすることが出来てしまいます。

Model I/O
Interface with language models

Retrieval
Interface with application-specific data

Agents
Let chains choose which tools to use given high-level directives

Chains
Common, building block compositions

Memory
Persist application state between runs of a chain

Callbacks
Log and stream intermediate steps of any chain

かくいう自分もぼんやりどんなことが出来るのかは知っているけど、実際に使ったことはない。ということで、今回は簡単にLangchainを導入してみよう!という企画です。LangchainでPDFを読み込む記事は日本語でも割とありますが、Excelファイルを読み込むものはあまり見かけなかったので、今回はExcelファイルでチャレンジしました。

手順

1. 導入

早速、公式のクイックスタートに沿ってインストールを進めていきましょう。

> pip install langchain

下記のエラーが出る場合はまずPythonがインストールされているかどうか、Pathが通っているかどうかを確認しましょう。Pythonのインストール時に”環境変数に追加”みたいなチェックボックスをオンにしていない場合は恐らく通りません。

> pip install langchain
'pip’ は、内部コマンドまたは外部コマンド、
操作可能なプログラムまたはバッチ ファイルとして認識されていません。

また、今回はOpenAI APIやEmbedding(テキストをベクトル化するやつ)を利用したいので、それらのパッケージもまとめてインストールしておきます。

> pip install openai
> pip install chromadb

なお、Pythonの現最新バージョン(=3.12.1)だとchromadbがインストールできなかったので、今回は3.10.0でインストールしました。

2.作成物

構成と中身は以下。

langchain_prac
│  langchain_prac.py
│
└─data
        test.xlsx
langchain_prac.py
from langchain.document_loaders import UnstructuredExcelLoader
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import Chroma
from langchain.chat_models import ChatOpenAI
from langchain.chains import ConversationalRetrievalChain

import os

os.environ['OPENAI_API_KEY']='***'
FILEPATH = "data/test.xlsx"

# load Excel file
loader = UnstructuredExcelLoader(FILEPATH)
docs = loader.load()

# create vector store
vector_stores = Chroma.from_documents(docs, OpenAIEmbeddings())

# create chatbot
qa = ConversationalRetrievalChain.from_llm(
    ChatOpenAI(model_name="gpt-4",temperature=0),
    vector_stores.as_retriever(search_kwargs={'k': 1}),
    return_source_documents=True,
)

# interaction
chat_history = []
for _ in range(10):
    query = input("ボットへの質問:")
    result = qa({'question': query, "chat_history": chat_history})
    print('chat bot:',result['answer'])
    chat_history.append((query, result['answer']))

test.xlsx(用意したExcelファイル)
image.png

os.environ['OPENAI_API_KEY']='***'の部分に自分のAPI Keyを入力してください。
また、環境によってはモジュールが見つからないといわれることがあると思いますので、適宜pip install hogeしてあげてください。

3.結果

ボットへの質問:りんごは好きですか?
chat bot: りんごについての感情は「ふつう」です。
ボットへの質問:ぶどうは好き?
chat bot: はい、ぶどうは好きです。
ボットへの質問:さくらんぼはすき?
chat bot: その情報は提供されていませんので、答えることができません。
ボットへの質問:嫌いなものを教えて
chat bot: トマトが嫌いです。
ボットへの質問:好きなものは何個ある?
chat bot: 私が好きなものは3個あります。

行と列の情報をしっかり認識し、数まで答えることが出来ています。かしこい。
他にもCSVなどたくさんの種類のファイルを読み込むことができるので、メールを一括エクスポートして参照させたりなどいろんな使い方が出来そうですね。

参考

8
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
1