안녕하세요 커뮤니티 여러분,
이 글에서는 제 애플리케이션인 iris-RAG-Gen을 소개하겠습니다.
Iris-RAG-Gen은 Streamlit 웹 프레임워크, LangChain 및 OpenAI의 도움으로 IRIS 벡터 검색 기능을 활용하여 ChatGPT를 개인화하는 생성형 AI RAG(검색 증강 생성) 애플리케이션입니다. 이 애플리케이션은 IRIS를 벡터 저장소로 사용합니다.
문서를 수집하려면 아래 단계를 따르세요.
문서 수집 기능은 문서 세부정보를 rag_documents 테이블에 삽입하고 'rag_document id'(rag_documents의 ID) 테이블을 생성하여 벡터 데이터를 저장합니다.
아래 Python 코드는 선택한 문서를 벡터로 저장합니다.
from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.document_loaders import PyPDFLoader, TextLoader from langchain_iris import IRISVector from langchain_openai import OpenAIEmbeddings from sqlalchemy import create_engine,text <span>class RagOpr:</span> #Ingest document. Parametres contains file path, description and file type <span>def ingestDoc(self,filePath,fileDesc,fileType):</span> embeddings = OpenAIEmbeddings() #Load the document based on the file type if fileType == "text/plain": loader = TextLoader(filePath) elif fileType == "application/pdf": loader = PyPDFLoader(filePath) #load data into documents documents = loader.load() text_splitter = RecursiveCharacterTextSplitter(chunk_size=400, chunk_overlap=0) #Split text into chunks texts = text_splitter.split_documents(documents) #Get collection Name from rag_doucments table. COLLECTION_NAME = self.get_collection_name(fileDesc,fileType) # function to create collection_name table and store vector data in it. db = IRISVector.from_documents( embedding=embeddings, documents=texts, collection_name = COLLECTION_NAME, connection_string=self.CONNECTION_STRING, ) #Get collection name <span>def get_collection_name(self,fileDesc,fileType):</span> # check if rag_documents table exists, if not then create it with self.engine.connect() as conn: with conn.begin(): sql = text(""" SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'SQLUser' AND TABLE_NAME = 'rag_documents'; """) result = [] try: result = conn.execute(sql).fetchall() except Exception as err: print("An exception occurred:", err) return '' #if table is not created, then create rag_documents table first if len(result) == 0: sql = text(""" CREATE TABLE rag_documents ( description VARCHAR(255), docType VARCHAR(50) ) """) try: result = conn.execute(sql) except Exception as err: print("An exception occurred:", err) return '' #Insert description value with self.engine.connect() as conn: with conn.begin(): sql = text(""" INSERT INTO rag_documents (description,docType) VALUES (:desc,:ftype) """) try: result = conn.execute(sql, {'desc':fileDesc,'ftype':fileType}) except Exception as err: print("An exception occurred:", err) return '' #select ID of last inserted record sql = text(""" SELECT LAST_IDENTITY() """) try: result = conn.execute(sql).fetchall() except Exception as err: print("An exception occurred:", err) return '' return "rag_document"+str(result[0][0])
벡터 데이터를 검색하려면 관리 포털에서 아래 SQL 명령을 입력하세요
SELECT top 5 id, embedding, document, metadata FROM SQLUser.rag_document2
채팅 옵션 선택 섹션에서 문서를 선택하고 질문을 입력하세요. 애플리케이션은 벡터 데이터를 읽고 관련 답변을 반환합니다
아래 Python 코드는 선택한 문서를 벡터로 저장합니다.
from langchain_iris import IRISVector from langchain_openai import OpenAIEmbeddings,ChatOpenAI from langchain.chains import ConversationChain from langchain.chains.conversation.memory import ConversationSummaryMemory from langchain.chat_models import ChatOpenAI <span>class RagOpr:</span> <span>def ragSearch(self,prompt,id):</span> #Concat document id with rag_doucment to get the collection name COLLECTION_NAME = "rag_document"+str(id) embeddings = OpenAIEmbeddings() #Get vector store reference db2 = IRISVector ( embedding_function=embeddings, collection_name=COLLECTION_NAME, connection_string=self.CONNECTION_STRING, ) #Similarity search docs_with_score = db2.similarity_search_with_score(prompt) #Prepair the retrieved documents to pass to LLM relevant_docs = ["".join(str(doc.page_content)) + " " for doc, _ in docs_with_score] #init LLM llm = ChatOpenAI( temperature=0, model_name="gpt-3.5-turbo" ) #manage and handle LangChain multi-turn conversations conversation_sum = ConversationChain( llm=llm, memory= ConversationSummaryMemory(llm=llm), verbose=False ) #Create prompt template = f""" Prompt: <span>{prompt} Relevant Docuemnts: {relevant_docs} """</span> #Return the answer resp = conversation_sum(template) return resp['response']
자세한 내용은 iris-RAG-Gen 공개 교환 신청 페이지를 참조하세요.
감사합니다
위 내용은 IRIS-RAG-Gen: IRIS 벡터 검색으로 구동되는 ChatGPT RAG 애플리케이션 개인화의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!