搜尋
首頁後端開發Python教學IRIS-RAG-Gen:由 IRIS 向量搜尋提供支援的個人化 ChatGPT RAG 應用程式

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
Python vs. C:了解關鍵差異Python vs. C:了解關鍵差異Apr 21, 2025 am 12:18 AM

Python和C 各有優勢,選擇應基於項目需求。 1)Python適合快速開發和數據處理,因其簡潔語法和動態類型。 2)C 適用於高性能和系統編程,因其靜態類型和手動內存管理。

Python vs.C:您的項目選擇哪種語言?Python vs.C:您的項目選擇哪種語言?Apr 21, 2025 am 12:17 AM

選擇Python還是C 取決於項目需求:1)如果需要快速開發、數據處理和原型設計,選擇Python;2)如果需要高性能、低延遲和接近硬件的控制,選擇C 。

達到python目標:每天2小時的力量達到python目標:每天2小時的力量Apr 20, 2025 am 12:21 AM

通過每天投入2小時的Python學習,可以有效提升編程技能。 1.學習新知識:閱讀文檔或觀看教程。 2.實踐:編寫代碼和完成練習。 3.複習:鞏固所學內容。 4.項目實踐:應用所學於實際項目中。這樣的結構化學習計劃能幫助你係統掌握Python並實現職業目標。

最大化2小時:有效的Python學習策略最大化2小時:有效的Python學習策略Apr 20, 2025 am 12:20 AM

在兩小時內高效學習Python的方法包括:1.回顧基礎知識,確保熟悉Python的安裝和基本語法;2.理解Python的核心概念,如變量、列表、函數等;3.通過使用示例掌握基本和高級用法;4.學習常見錯誤與調試技巧;5.應用性能優化與最佳實踐,如使用列表推導式和遵循PEP8風格指南。

在Python和C之間進行選擇:適合您的語言在Python和C之間進行選擇:適合您的語言Apr 20, 2025 am 12:20 AM

Python適合初學者和數據科學,C 適用於系統編程和遊戲開發。 1.Python簡潔易用,適用於數據科學和Web開發。 2.C 提供高性能和控制力,適用於遊戲開發和系統編程。選擇應基於項目需求和個人興趣。

Python與C:編程語言的比較分析Python與C:編程語言的比較分析Apr 20, 2025 am 12:14 AM

Python更適合數據科學和快速開發,C 更適合高性能和系統編程。 1.Python語法簡潔,易於學習,適用於數據處理和科學計算。 2.C 語法複雜,但性能優越,常用於遊戲開發和系統編程。

每天2小時:Python學習的潛力每天2小時:Python學習的潛力Apr 20, 2025 am 12:14 AM

每天投入兩小時學習Python是可行的。 1.學習新知識:用一小時學習新概念,如列表和字典。 2.實踐和練習:用一小時進行編程練習,如編寫小程序。通過合理規劃和堅持不懈,你可以在短時間內掌握Python的核心概念。

Python與C:學習曲線和易用性Python與C:學習曲線和易用性Apr 19, 2025 am 12:20 AM

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具