首页 >后端开发 >Python教程 >IRIS-RAG-Gen:由 IRIS 矢量搜索提供支持的个性化 ChatGPT RAG 应用程序

IRIS-RAG-Gen:由 IRIS 矢量搜索提供支持的个性化 ChatGPT RAG 应用程序

Patricia Arquette
Patricia Arquette原创
2025-01-03 16:56:39241浏览

IRIS-RAG-Gen: Personalizing ChatGPT RAG Application Powered by IRIS Vector Search

社区大家好,

在本文中,我将介绍我的应用程序 iris-RAG-Gen 。

Iris-RAG-Gen 是一款生成式 AI 检索增强生成 (RAG) 应用程序,它利用 IRIS 矢量搜索的功能,在 Streamlit Web 框架、LangChain 和 OpenAI 的帮助下个性化 ChatGPT。该应用程序使用 IRIS 作为矢量存储。
IRIS-RAG-Gen: Personalizing ChatGPT RAG Application Powered by IRIS Vector Search

应用功能

  • 将文档(PDF 或 TXT)提取到 IRIS
  • 与选定的摄取文档聊天
  • 删除摄取的文档
  • OpenAI ChatGPT

将文档(PDF 或 TXT)提取到 IRIS

按照以下步骤提取文档:

  • 输入 OpenAI 密钥
  • 选择文档(PDF 或 TXT)
  • 输入文档说明
  • 单击“摄取文档”按钮

IRIS-RAG-Gen: Personalizing ChatGPT RAG Application Powered by IRIS Vector Search
 

摄取文档功能将文档详细信息插入到 rag_documents 表中,并创建“rag_document id”(rag_documents 的 ID)表来保存矢量数据。

IRIS-RAG-Gen: Personalizing ChatGPT RAG Application Powered by IRIS Vector Search

下面的 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

IRIS-RAG-Gen: Personalizing ChatGPT RAG Application Powered by IRIS Vector Search

 

与选定的摄取文档聊天

从选择聊天选项部分选择文档并输入问题。 应用程序将读取矢量数据并返回相关答案
IRIS-RAG-Gen: Personalizing ChatGPT RAG Application Powered by IRIS Vector Search

下面的 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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn