全体プログラムの更新
以下の記事で faiss_service.py を作成していますが、初期の頃よりも大分変更しましたので、最新のプログラム全体を再掲します。
初期の頃からの主な変更点は、以下の通りです。
・Swagger UI 対応
・delete で OpenAI API の再ベクトル化を行わない
・機能追加
- ドキュメント一覧
- ドキュメントのタイトル変更
- テキストファイルをアップロードして登録
- テキストファイルをチャンク分割し、アップロードして登録
・ナレッジIDで FAISS インデックスを切り替える
・短すぎる質問を複数のクエリに展開し、検索に適した形に変換
from flask import Flask, request, jsonify
from flasgger import Swagger
from openai import OpenAI
from langchain.text_splitter import RecursiveCharacterTextSplitter
import psycopg2
import faiss
import numpy as np
import os
import uuid
import json
import gc
app = Flask(__name__)
swagger = Swagger(app)
client = OpenAI()
# DB接続設定
db_conn = psycopg2.connect(
dbname="webmaster",
user="webmaster",
password=os.environ.get("PSQL_DB_PASSWORD"), # 環境変数から取得
host="localhost",
port="5432"
)
# FAISSインデックスの初期化
res = faiss.StandardGpuResources() # use a single GPU
dimension = 3072 # text-embedding-3-large
knowledge_info_path = "knowledge_id_to_no.json"
knowledge_id_to_no = {}
gpu_indexes = {}
doc_id_map = {}
vector_map = {}
if os.path.exists(knowledge_info_path):
with open(knowledge_info_path, "r") as f:
knowledge_id_to_no = json.load(f)
for knowledge_id, no in knowledge_id_to_no.items():
index = faiss.read_index(f"faiss_{no:03d}.index")
gpu_index = faiss.index_cpu_to_gpu(res, 0, index)
gpu_indexes[knowledge_id] = gpu_index
with open("doc_id_map.json", "r") as f:
doc_id_map = json.load(f)
vectors = np.load("vector_map.npy")
vector_map = {}
i = 0
for knowledge_id, doc_ids in doc_id_map.items():
vector_map[knowledge_id] = {}
for doc_id in doc_ids:
vector_map[knowledge_id][doc_id] = vectors[i]
i += 1
print("FAISSインデックスをロードしました")
def save_faiss():
with open(knowledge_info_path, "w") as f:
json.dump(knowledge_id_to_no, f)
for knowledge_id, no in knowledge_id_to_no.items():
index = faiss.index_gpu_to_cpu(gpu_indexes[knowledge_id])
faiss.write_index(index, f"faiss_{no:03d}.index")
with open("doc_id_map.json", "w") as f:
json.dump(doc_id_map, f)
vectors = []
for knowledge_id in doc_id_map:
for doc_id in doc_id_map[knowledge_id]:
vectors.append(vector_map[knowledge_id][doc_id])
vectors = np.array(vectors, dtype=np.float32)
np.save("vector_map.npy", vectors)
print("FAISSインデックスを保存しました")
def create_faiss_index(knowledge_id):
global gpu_indexes, doc_id_map, vector_map, knowledge_id_to_no
if knowledge_id_to_no:
new_index_no = max(knowledge_id_to_no.values()) + 1
else:
new_index_no = 0 # 初回は0からスタート
if new_index_no > 999: # 1000以上は作成せず、999を使いまわす
knowledge_id_to_no[knowledge_id] = 999
return
index = faiss.IndexFlatL2(dimension)
gpu_index = faiss.index_cpu_to_gpu(res, 0, index)
gpu_indexes[knowledge_id] = gpu_index
knowledge_id_to_no[knowledge_id] = new_index_no
doc_id_map.setdefault(knowledge_id, [])
vector_map.setdefault(knowledge_id, {})
print("FAISS新規インデックスを作成しました")
@app.route('/retrieval', methods=['POST'])
def retrieval():
"""
クエリベクトルで検索
---
tags:
- Document Management
description: クエリをベクトル化してナレッジベースから関連ドキュメントを検索します。
parameters:
- in: body
name: body
required: true
schema:
type: object
required:
- knowledge_id
- query
- retrieval_setting
properties:
knowledge_id:
type: string
description: 検索対象のナレッジベースのID
example: "AAA-BBB-CCC"
query:
type: string
description: 検索クエリのテキスト
example: "売上レポートについて教えてください。"
retrieval_setting:
type: object
description: 検索の詳細設定
properties:
top_k:
type: integer
description: 取得する上位ドキュメント数
example: 4
score_threshold:
type: number
format: float
description: スコアの最低しきい値(小さいとヒットしやすい)
example: 0.4
responses:
200:
description: 検索結果が返された場合
schema:
type: object
properties:
records:
type: array
items:
type: object
properties:
content:
type: string
description: ドキュメント本文
example: "売上レポート2023年第1四半期版"
title:
type: string
description: ドキュメントタイトル
example: "2023年Q1 売上まとめ.txt"
metadata:
type: object
description: メタデータ(任意)
example: {"category": "sales"}
score:
type: number
format: float
description: 類似スコア(1に近いほど類似)
example: 0.87
500:
description: サーバーエラー
schema:
type: object
properties:
error_code:
type: integer
example: 5000
error_msg:
type: string
example: "Internal Server Error"
"""
try:
data = request.get_json()
knowledge_id = data.get("knowledge_id")
query = data.get("query") # ユーザーが送信した質問文
retrieval_setting = data.get("retrieval_setting", {})
top_k = retrieval_setting.get("top_k", 4)
score_threshold = retrieval_setting.get("score_threshold", 0.4)
if not knowledge_id:
return jsonify({"error_code": 1001, "error_msg": "knowledge_idは必須です"}), 400
if not query:
return jsonify({"error_code": 1002, "error_msg": "queryは必須です"}), 400
# 短すぎる質問を複数のクエリに展開し、検索に適した形に変換する(MultiQueryRetriever)
if len(query) >= 70:
rewritten = query
else:
prompt = f"""
You are an AI language model assistant. Your task is to generate five
different versions of the given user question to retrieve relevant documents from a vector
database. By generating multiple perspectives on the user question, your goal is to help
the user overcome some of the limitations of the distance-based similarity search.
Provide these alternative questions separated by newlines. Please speak in Japanese.
Original question: {query}
"""
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a helpful query rewriting assistant."},
{"role": "user", "content": prompt}
],
temperature=0
)
rewritten = response.choices[0].message.content.strip()
print(f"[Rewritten]({len(query)}) {rewritten}")
# OpenAI API でクエリをベクトル化
response = client.embeddings.create(
input=rewritten,
model="text-embedding-3-large"
)
query_vector = np.array(response.data[0].embedding, dtype=np.float32)
if knowledge_id not in knowledge_id_to_no:
return jsonify({"error_code": 1003, "error_msg": "指定されたknowledge_idは存在しません"}), 400
# FAISS検索
D, I = gpu_indexes[knowledge_id].search(np.array([query_vector]), top_k)
cur = db_conn.cursor()
records = []
for dist, idx in zip(D[0], I[0]):
if idx == -1:
continue
score = 1 / (1 + dist)
if score < score_threshold:
continue
# UUIDを復元
doc_uuid = doc_id_map[knowledge_id][idx]
# PostgreSQLから取得
cur.execute("""
SELECT content, title, metadata
FROM knowledge_documents
WHERE id = %s AND knowledge_id = %s
""", (doc_uuid, knowledge_id))
row = cur.fetchone()
if row:
meta = row[2] or {}
# DBのmetadataが文字列(JSON)で返る環境対策(jsonbならdictのこと
if isinstance(meta, str):
try:
meta = json.loads(meta)
except Exception:
meta = {}
meta["document_id"] = str(doc_id)
records.append({
"content": row[0],
"title": row[1],
"metadata": meta,
"score": score
})
return jsonify({"records": records})
except Exception as e:
return jsonify({"error_code": 5000, "error_msg": str(e)}), 500
@app.route('/add', methods=['POST'])
def add():
"""
新しいドキュメント追加
---
tags:
- Document Management
description: 新しいドキュメントをナレッジベースに追加します。
parameters:
- in: body
name: body
required: true
schema:
type: object
required:
- knowledge_id
- content
- title
properties:
knowledge_id:
type: string
description: 登録するナレッジベースのID
example: "AAA-BBB-CCC"
content:
type: string
description: 登録するドキュメントの本文
example: "これはサンプルドキュメントの本文です。"
title:
type: string
description: ドキュメントのタイトル
example: "サンプルドキュメント.txt"
metadata:
type: object
description: 任意のメタデータ情報
example: {"category": "example"}
responses:
200:
description: 正常に登録された場合
schema:
type: object
properties:
status:
type: string
example: "success"
id:
type: string
description: 登録されたドキュメントのUUID
example: "d290f1ee-6c54-4b01-90e6-d701748f0851"
500:
description: サーバーエラー(登録に失敗した場合)
schema:
type: object
properties:
error_code:
type: integer
example: 5000
error_msg:
type: string
example: "Internal Server Error"
"""
try:
global gpu_indexes, doc_id_map, vector_map, knowledge_id_to_no
data = request.get_json()
knowledge_id = data['knowledge_id']
content = data['content']
title = data['title']
metadata = data.get('metadata', {})
# OpenAI APIで埋め込みベクトルを取得
response = client.embeddings.create(
input = content,
model = "text-embedding-3-large"
)
vector = np.array(response.data[0].embedding, dtype=np.float32)
# UUID生成
new_id = str(uuid.uuid4())
# PostgreSQLに保存
cur = db_conn.cursor()
cur.execute("""
INSERT INTO knowledge_documents (id, knowledge_id, content, title, metadata)
VALUES (%s, %s, %s, %s, %s)
""", (new_id, knowledge_id, content, title, json.dumps(metadata)))
db_conn.commit()
# knowledge が存在しない場合に、新しくインデックスを作成
if knowledge_id not in knowledge_id_to_no:
create_faiss_index(knowledge_id)
# FAISSに保存
gpu_indexes[knowledge_id].add(np.array([vector]))
doc_id_map[knowledge_id].append(new_id)
vector_map[knowledge_id][new_id] = vector
save_faiss()
return jsonify({"status": "success", "id": new_id})
except Exception as e:
return jsonify({"error_code": 5000, "error_msg": str(e)}), 500
@app.route('/delete', methods=['POST'])
def delete():
"""
ドキュメントを削除
---
tags:
- Document Management
description: 指定されたIDのドキュメントを削除します。
parameters:
- in: body
name: body
required: true
schema:
type: object
required:
- id
properties:
id:
type: string
description: 削除対象のドキュメントID(UUID形式)
example: "d290f1ee-6c54-4b01-90e6-d701748f0851"
responses:
200:
description: 正常に削除された場合
schema:
type: object
properties:
status:
type: string
example: "success"
id:
type: string
description: 削除されたドキュメントのID
500:
description: サーバーエラー(削除に失敗した場合)
schema:
type: object
properties:
error_code:
type: integer
example: 5000
error_msg:
type: string
example: "Internal Server Error"
"""
try:
data = request.get_json()
doc_id = data['id'] # 削除対象のUUID文字列
# 関数内で値を変更しする際は、global宣言が必要
global gpu_indexes, doc_id_map, vector_map, knowledge_id_to_no
cur = db_conn.cursor()
# PostgreSQL から knowledge_id を取得
cur.execute("SELECT knowledge_id FROM knowledge_documents WHERE id = %s", (doc_id,))
row = cur.fetchone()
if not row:
return jsonify({"error_code": 4004, "error_msg": "Document ID not found"}), 404
knowledge_id = row[0]
# PostgreSQLから削除
cur.execute("DELETE FROM knowledge_documents WHERE id = %s", (doc_id,))
db_conn.commit()
# knowledge_id に対応するレコードの id を PostgreSQL から取得
cur.execute("SELECT id FROM knowledge_documents WHERE knowledge_id = %s", (knowledge_id,))
rows = cur.fetchall()
new_doc_id_map = {}
new_vector_map = {}
new_doc_id_map[knowledge_id] = []
new_vector_map[knowledge_id] = {}
# FAISS 再構築
index = faiss.IndexFlatL2(dimension)
for row in rows:
add_doc_id = row[0]
if add_doc_id in vector_map[knowledge_id]:
vector = vector_map[knowledge_id][add_doc_id]
index.add(np.array([vector]))
new_doc_id_map[knowledge_id].append(add_doc_id)
new_vector_map[knowledge_id][add_doc_id] = vector
doc_id_map[knowledge_id] = new_doc_id_map[knowledge_id]
vector_map[knowledge_id] = new_vector_map[knowledge_id]
# インデックス更新
old_index = gpu_indexes[knowledge_id]
new_gpu_index = faiss.index_cpu_to_gpu(res, 0, index)
gpu_indexes[knowledge_id] = new_gpu_index
del old_index
gc.collect()
# 保存
save_faiss()
return jsonify({"status": "success", "id": doc_id})
except Exception as e:
return jsonify({"error_code": 5000, "error_msg": str(e)}), 500
@app.route('/delete_knowledge', methods=['POST'])
def delete_knowledge():
"""
空のナレッジを削除
---
tags:
- Document Management
description: 指定された knowledge_id のナレッジを削除します。ナレッジに紐づくドキュメントが存在する場合は削除されません。
parameters:
- in: body
name: body
required: true
schema:
type: object
required:
- knowledge_id
properties:
knowledge_id:
type: string
description: 削除対象の knowledge_id
example: "AAA-BBB-CCC"
responses:
200:
description: 正常に削除された場合
schema:
type: object
properties:
status:
type: string
example: "success"
knowledge_id:
type: string
description: 削除された knowledge_id
example: "AAA-BBB-CCC"
400:
description: ドキュメントが存在するため削除できなかった場合
schema:
type: object
properties:
error_code:
type: integer
example: 4004
error_msg:
type: string
example: "指定されたナレッジにドキュメントが存在します。"
500:
description: サーバーエラー(削除に失敗した場合)
schema:
type: object
properties:
error_code:
type: integer
example: 5000
error_msg:
type: string
example: "Internal Server Error"
"""
try:
data = request.get_json()
knowledge_id = data['knowledge_id'] # 削除対象の knowledge_id
global gpu_indexes, doc_id_map, vector_map, knowledge_id_to_no
if knowledge_id not in knowledge_id_to_no:
return jsonify({"error_code": 4005, "error_msg": "Knowledge ID not found"}), 404
cur = db_conn.cursor()
# knowledge_id に対応するレコードの id を PostgreSQL から取得
cur.execute("SELECT id FROM knowledge_documents WHERE knowledge_id = %s", (knowledge_id,))
rows = cur.fetchall()
if rows:
return jsonify({"error_code": 4004, "error_msg": "The specified knowledge contains documents."}), 400
index_no = knowledge_id_to_no.get(knowledge_id)
if index_no != 999: # 999 は共有なので除外
del gpu_indexes[knowledge_id]
if os.path.exists(f"faiss_{index_no:03d}.index"):
os.remove(f"faiss_{index_no:03d}.index")
gc.collect()
print(f"FAISSインデックス {index_no} ({knowledge_id})を削除しました。")
del doc_id_map[knowledge_id]
del vector_map[knowledge_id]
del knowledge_id_to_no[knowledge_id]
save_faiss()
return jsonify({"status": "success", "knowledge_id": knowledge_id})
except Exception as e:
return jsonify({"error_code": 5000, "error_msg": str(e)}), 500
@app.route('/list', methods=['GET'])
def list():
"""
ドキュメント一覧を表示
---
tags:
- Document Management
summary: 登録されたドキュメントの一覧を表示します
description:
登録されているすべてのドキュメントを取得し、index、doc_id、knowledge_id、title、文字数、metadata、作成日を表示します。
さらに、データベース内レコード数、doc_id_map 数、vector_map 数、knowledge 数の統計も返します。
responses:
200:
description: ドキュメント一覧と統計情報
schema:
type: object
properties:
documents:
type: array
description: ドキュメントのリスト
items:
type: object
properties:
index:
type: integer
description: リスト内の連番
example: 0
doc_id:
type: string
description: ドキュメントの一意ID
example: "abc123"
knowledge_id:
type: string
description: ナレッジベースのID
example: "AAA-BBB-CCC"
title:
type: string
description: ドキュメントのタイトル
example: "https://sample.com"
char_number:
type: integer
description: コンテンツの文字数
example: 1342
metadata:
type: object
description: メタデータ情報(JSON形式)
example: { "filename": "Sample.txt" }
created_at:
type: string
format: datetime
description: 作成日時
example: "2024-07-10 12:34:56"
knowledge:
type: object
description: 各 knowledge_id とそれに対応する内部インデックス番号のマッピング
additionalProperties:
type: integer
description: FAISS における knowledge_id のインデックス番号(通常は 0 からの連番。999 は共有インデックスを表す場合がある)
example:
AAA-BBB-CCC: 0
summary:
type: object
description: 登録数の統計
properties:
database_records:
type: integer
description: データベースのドキュメント総数
example: 25
doc_id_map_count:
type: object
description: メモリ上の doc_id_map 件数
additionalProperties:
type: integer
example: 2
example:
AAA-BBB-CCC: 2
DDD-EEE-FFF: 1
vector_map_count:
type: object
description: メモリ上の vector_map 件数
additionalProperties:
type: integer
example: 2
example:
AAA-BBB-CCC: 2
DDD-EEE-FFF: 1
knowledge_count:
type: integer
description: メモリ上の knowledge 件数
example: 2
500:
description: サーバー内部エラー
schema:
type: object
properties:
error_code:
type: integer
example: 5000
error_msg:
type: string
example: "Database connection failed"
"""
try:
cur = db_conn.cursor()
cur.execute("SELECT id, knowledge_id, title, content, metadata, created_at FROM knowledge_documents ORDER BY created_at ASC")
rows = cur.fetchall()
documents = []
for index, row in enumerate(rows):
doc_id, knowledge_id, title, content, metadata, created_at = row
documents.append({
"index": index,
"doc_id": doc_id,
"knowledge_id": knowledge_id,
"title": title,
"char_number": len(content or ""),
"metadata": metadata or {},
"created_at": created_at.strftime("%Y-%m-%d %H:%M:%S")
})
summary = {
"database_records": len(rows),
"doc_id_map_count": {k: len(v) for k, v in doc_id_map.items()},
"vector_map_count": {k: len(v) for k, v in vector_map.items()},
"knowledge_count": len(knowledge_id_to_no),
}
return jsonify({
"documents": documents,
"knowledge": knowledge_id_to_no,
"summary": summary
})
except Exception as e:
return jsonify({"error_code": 5000, "error_msg": str(e)}), 500
@app.route('/edit_title', methods=['POST'])
def edit_title():
"""
ドキュメントのタイトルを変更
---
tags:
- Document Management
description: 指定されたドキュメントIDのタイトルを変更します。チャットボットの回答では、タイトルが引用情報として使用されます。
parameters:
- in: body
name: body
required: true
schema:
type: object
required:
- id
- title
properties:
id:
type: string
description: 変更対象のドキュメントUUID
example: "d290f1ee-6c54-4b01-90e6-d701748f0851"
title:
type: string
description: 新しいタイトル
example: "2023年Q1 売上まとめ.txt"
responses:
200:
description: タイトルの変更成功
schema:
type: object
properties:
status:
type: string
example: "success"
id:
type: string
example: "d290f1ee-6c54-4b01-90e6-d701748f0851"
404:
description: 指定されたIDが存在しない場合
500:
description: サーバーエラー
"""
try:
data = request.get_json()
doc_id = data['id']
new_title = data['title']
cur = db_conn.cursor()
cur.execute("""
UPDATE knowledge_documents
SET title = %s
WHERE id = %s
""", (new_title, doc_id))
if cur.rowcount == 0:
return jsonify({"error_code": 404, "error_msg": "指定されたIDのドキュメントが見つかりません。"}), 404
db_conn.commit()
return jsonify({"status": "success", "id": doc_id})
except Exception as e:
return jsonify({"error_code": 5000, "error_msg": str(e)}), 500
@app.route('/upload_files', methods=['POST'])
def upload_files():
"""
テキストファイルをアップロードして登録
---
tags:
- Document Management
description: テキストファイルをアップロードしてナレッジベースに登録します。
consumes:
- multipart/form-data
parameters:
- in: formData
name: knowledge_id
type: string
required: true
description: 全ファイル共通の knowledge_id
example: "AAA-BBB-CCC"
- in: formData
name: files
type: array
items:
type: file
format: binary
required: true
description: 最大20個のテキストファイル
allowMultiple: true
- in: formData
name: titles
type: array
items:
type: string
required: false
description: 各ファイルのタイトル(最大20件まで、省略時はファイル名になります)
responses:
200:
description: 登録成功時
schema:
type: object
properties:
status:
type: string
example: "success"
titles_uploaded:
type: array
items:
type: string
example:
- "https://en.wikipedia.org/wiki/Curling_at_the_2022_Winter_Olympics"
files_uploaded:
type: array
items:
type: string
example:
- "CurlingAtThe2022WinterOlympics.txt"
uploaded_doc_ids:
type: array
items:
type: string
example:
- "4469d7e6-f5be-44a8-9808-a17c96b05e53"
"""
global gpu_indexes, doc_id_map, vector_map, knowledge_id_to_no
# 入力取得
knowledge_id = request.form.get('knowledge_id')
files = request.files.getlist('files')
titles_raw = request.form.get('titles', '')
title_list = [t.strip() for t in titles_raw.split(',')] if titles_raw else []
if not knowledge_id:
return jsonify({"error": "knowledge_id is required"}), 400
if not files or len(files) == 0:
return jsonify({"error": "No files uploaded"}), 400
if len(files) > 20:
return jsonify({"error": "Maximum 20 files allowed"}), 400
added_titles = []
added_docs = []
added_doc_ids = []
for i, file in enumerate(files):
try:
filename = file.filename
content = file.read().decode('utf-8') # テキストファイル前提
# 改行・タブ・クォート・バックスラッシュを置換
content = content.replace("\r\n", "\n") \
.replace("\\", "\\\\") \
.replace("\"", "\\\"") \
.replace("\t", " ")
title = title_list[i] if i < len(title_list) and title_list[i] else filename
# OpenAI APIで埋め込みベクトルを取得
response = client.embeddings.create(
input = content,
model = "text-embedding-3-large"
)
vector = np.array(response.data[0].embedding, dtype=np.float32)
# UUID生成
doc_uuid = str(uuid.uuid4())
# PostgreSQLに登録
cur = db_conn.cursor()
cur.execute("""
INSERT INTO knowledge_documents (id, knowledge_id, title, content, metadata)
VALUES (%s, %s, %s, %s, %s)
""", (doc_uuid, knowledge_id, title, content, json.dumps({"filename": filename})))
db_conn.commit()
# knowledge が存在しない場合に、新しくインデックスを作成
if knowledge_id not in knowledge_id_to_no:
create_faiss_index(knowledge_id)
# FAISS に追加
gpu_indexes[knowledge_id].add(np.array([vector]))
doc_id_map[knowledge_id].append(doc_uuid)
vector_map[knowledge_id][doc_uuid] = vector
added_titles.append(title)
added_docs.append(filename)
added_doc_ids.append(doc_uuid)
except Exception as e:
return jsonify({"error": f"Failed to process {file.filename}: {str(e)}"}), 500
# 保存
save_faiss()
return jsonify({
"status": "success",
"titles_uploaded": added_titles,
"files_uploaded": added_docs,
"uploaded_doc_ids": added_doc_ids
})
@app.route('/upload_files_chunk', methods=['POST'])
def upload_files_chunk():
"""
テキストファイルをチャンク分割し、アップロードして登録
---
tags:
- Document Management
description: テキストファイルをチャンク分割してアップロードし、ナレッジベースに登録します。分割されたテキストファイルは、異なるドキュメントIDで、同じタイトル、同じファイル名(メタデータ)になります。また、文書内インデックス(メタデータ)が追加されます。
consumes:
- multipart/form-data
parameters:
- in: formData
name: knowledge_id
type: string
required: true
description: 全ファイル共通の knowledge_id
example: "AAA-BBB-CCC"
- in: formData
name: chunk_size
type: integer
required: false
description: チャンクサイズ(文字数)
default: 1000
- in: formData
name: chunk_overlap
type: integer
required: false
description: チャンクの重なり(文字数)
default: 200
- in: formData
name: separator
type: string
required: false
description: セパレータ(カンマ区切りで複数指定可)
- in: formData
name: files
type: array
items:
type: file
format: binary
required: true
description: 最大20個のテキストファイル
allowMultiple: true
- in: formData
name: titles
type: array
items:
type: string
required: false
description: 各ファイルのタイトル(最大20件まで、省略時はファイル名になります)
responses:
200:
description: 登録成功時
schema:
type: object
properties:
status:
type: string
example: "success"
titles_uploaded:
type: array
items:
type: string
example:
- "https://en.wikipedia.org/wiki/europe/"
files_uploaded:
type: array
items:
type: string
example:
- "europe_summary.txt"
chunks_uploaded:
type: array
items:
type: integer
example:
- 3
uploaded_doc_ids:
type: array
items:
type: string
example:
- "fbcd332b-13c0-4473-b128-1f0d980f8ba5"
- "3e519d79-4152-4ce3-9975-9b6103da4ceb"
- "1dc574e1-dcec-4237-8e30-400efaf9f965"
"""
global gpu_indexes, doc_id_map, vector_map, knowledge_id_to_no
# 入力取得
knowledge_id = request.form.get('knowledge_id')
chunk_size = int(request.form.get('chunk_size', '1000'))
chunk_overlap = int(request.form.get('chunk_overlap', '200'))
separator_raw = request.form.get('separator', '')
separator = [s.strip(' ') for s in separator_raw.split(',') if s.strip(' ')]
files = request.files.getlist('files')
titles_raw = request.form.get('titles', '')
title_list = [t.strip() for t in titles_raw.split(',')] if titles_raw else []
if not knowledge_id:
return jsonify({"error": "knowledge_id is required"}), 400
if not files or len(files) == 0:
return jsonify({"error": "No files uploaded"}), 400
if len(files) > 20:
return jsonify({"error": "Maximum 20 files allowed"}), 400
added_titles = []
added_docs = []
added_chunks = []
added_doc_ids = []
for i, file in enumerate(files):
try:
filename = file.filename
docs = file.read().decode('utf-8') # テキストファイル前提
# チャンク分割
if not separator:
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=chunk_size,
chunk_overlap=chunk_overlap
)
else:
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
separators=separator
)
title = title_list[i] if i < len(title_list) and title_list[i] else filename
splits = text_splitter.split_text(docs)
for idx, content in enumerate(splits, start=0):
# 改行・タブ・クォート・バックスラッシュを置換
content = content.replace("\r\n", "\n") \
.replace("\\", "\\\\") \
.replace("\"", "\\\"") \
.replace("\t", " ")
# OpenAI APIで埋め込みベクトルを取得
response = client.embeddings.create(
input = content,
model = "text-embedding-3-large"
)
vector = np.array(response.data[0].embedding, dtype=np.float32)
# UUID生成
doc_uuid = str(uuid.uuid4())
# PostgreSQLに登録
cur = db_conn.cursor()
cur.execute("""
INSERT INTO knowledge_documents (id, knowledge_id, title, content, metadata)
VALUES (%s, %s, %s, %s, %s)
""", (doc_uuid, knowledge_id, title, content, json.dumps({"filename": filename, "in-document index": idx})))
db_conn.commit()
# knowledge が存在しない場合に、新しくインデックスを作成
if knowledge_id not in knowledge_id_to_no:
create_faiss_index(knowledge_id)
# FAISS に追加
gpu_indexes[knowledge_id].add(np.array([vector]))
doc_id_map[knowledge_id].append(doc_uuid)
vector_map[knowledge_id][doc_uuid] = vector
added_doc_ids.append(doc_uuid)
added_titles.append(title)
added_docs.append(filename)
added_chunks.append(len(splits))
except Exception as e:
return jsonify({"error": f"Failed to process {file.filename}: {str(e)}"}), 500
# 保存
save_faiss()
return jsonify({
"status": "success",
"titles_uploaded": added_titles,
"files_uploaded": added_docs,
"chunks_uploaded": added_chunks,
"uploaded_doc_ids": added_doc_ids
})
# ウェブサーバー起動
@app.route("/")
def index():
return "こんにちは、これは Python の Web サーバーです!"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)
export PSQL_DB_PASSWORD="..."
export OPENAI_API_KEY="..."
export LANGCHAIN_TRACING_V2="true"
export LANGCHAIN_API_KEY="..."
export USER_AGENT="MyLangChainBot/1.0 (contact: your-email@example.com)"
python faiss_service.py
# または、Ubuntu 起動時に Python プログラムを実行する
登録データの削除(更新)
rm faiss_000.index
rm faiss_001.index
...
rm doc_id_map.json
rm vector_map.npy
rm knowledge_id_to_no.json
psql -U webmaster -d webmaster -h localhost
DELETE FROM knowledge_documents;
登録データのバックアップ(更新)
mkdir backup
cp faiss_000.index ./backup/faiss_000_$(date '+%Y%m%d_%H%M%S').index
cp faiss_001.index ./backup/faiss_001_$(date '+%Y%m%d_%H%M%S').index
...
cp doc_id_map.json ./backup/doc_id_map_$(date '+%Y%m%d_%H%M%S').json
cp vector_map.npy ./backup/vector_map_$(date '+%Y%m%d_%H%M%S').npy
cp knowledge_id_to_no.json ./backup/knowledge_id_to_no_$(date '+%Y%m%d_%H%M%S').npy
pg_dump -U webmaster -d webmaster -t knowledge_documents -F p -f ./backup/knowledge_documents_$(date '+%Y%m%d_%H%M%S').sql
(「$」は半角文字に変えます)
Dify を v1.8.1 から v1.13.0 へ移行
Dify 1.13 以降では、外部 Knowledge API が返す各 record の metadata の中に document_id が必要となったため、faiss_service.py の /retrieval を修正しました。