0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

LangchainでRAGをDBに保管する方法

Posted at

必要なライブラリのインストール

まず、Langchainとデータベース用のライブラリをインストールします。例えば、SQLiteを使う場合は以下のようにします。

pip install langchain sqlite3

データベースのセットアップ

SQLiteを使ってデータベースをセットアップします。以下は基本的なテーブルを作成する例です。

import sqlite3

# データベースに接続
conn = sqlite3.connect('rag_data.db')
cursor = conn.cursor()

# テーブルの作成
cursor.execute('''
CREATE TABLE IF NOT EXISTS documents (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    content TEXT NOT NULL
)
''')

conn.commit()
conn.close()

Langchainの設定

Langchainを使ってRAGを実装します。以下は基本的な流れです。

from langchain import Langchain
from langchain.vectorstores import SQLiteVectorStore
from langchain.embeddings import OpenAIEmbeddings

# データベース接続
conn = sqlite3.connect('rag_data.db')

# ベクトルストアの設定
vectorstore = SQLiteVectorStore(conn, 'documents', embedding=OpenAIEmbeddings())

# Langchainのインスタンスを作成
langchain = Langchain(vectorstore)

# データの追加
def add_document(content):
    cursor = conn.cursor()
    cursor.execute('INSERT INTO documents (content) VALUES (?)', (content,))
    conn.commit()

# ドキュメントの追加例
add_document("これはサンプルドキュメントです。")

質問応答の実装

RAGを使って質問応答を行うための基本的な例です。

# 質問応答の実行
query = "サンプルドキュメントについて教えてください。"
response = langchain.query(query)

print(response)
0
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?