Find

Article
· Aug 16, 2024 1m read

First "vector search" on IRIS

There are a lot of great community articles regarding "vector search on IRIS", and samples in OpenExchange. Everytime I see these, I'm so excited to know that so many developers already try vectors on IRIS!

But if you've not tried "Vector Search on IRIS" yet, please give me one minute 😄 I create one IRIS class - and with only one IRIS class you can see how you put vector data in your IRIS database and how you compare these in your application. You can see the source code from OpenExchange "First-Vector-Search-on-IRIS".

---

(1) This class includes two properties

  • "feedback" as %String
  • "feedbackv" as %Vector (vector value), generated from "feedback".

      

(2) This class has the method "search", which returns the rows in order of "better feedback" with comparing vector "feedbackv".

 

---

The step-by-step guide is described in OpenExchange page.
I hope my sample and great other community articles will encourage you to try vector search on our product!

2 Comments
Discussion (2)2
Log in or sign up to continue
Article
· Aug 16, 2024 5m read

IRIS-RAG-Gen: Personalización de la aplicación ChatGPT RAG mediante la búsqueda vectorial IRIS

image

Hola Comunidad,

En este artículo, voy a presentar mi aplicación iris-RAG-Gen .

Iris-RAG-Gen es una aplicación generativa AI Retrieval-Augmented Generation (RAG) que aprovecha la funcionalidad de IRIS Vector Search para personalizar ChatGPT con la ayuda del framework web Streamlit, LangChain, y OpenAI. La aplicación utiliza IRIS como almacén de vectores.

image

Características de la aplicación

  • Ingesta de documentos (PDF o TXT) en IRIS
  • Chatear con el documento ingerido seleccionado
  • Borrar Documentos ingerido
  • OpenAI ChatGPT

Ingesta de documentos (PDF o TXT) en IRI

Seguid los siguientes pasos para ingerir el documento:

  • Introducid a clave OpenAI
  • Seleccionad el documento (PDF o TXT)
  • Introducid la descripción del documento
  • Haced clic en el botón Ingerir documento

image
 

La funcionalidad Ingest Document inserta los detalles del documento en la tabla rag_documents y crea la tabla 'rag_document + id' (id del rag_documents) para guardar los datos vectoriales.

El siguiente código Python guardará el documento seleccionado en vectores:

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

class RagOpr:
    #Ingest document. Parametres contains file path, description and file type  
    def ingestDoc(self,filePath,fileDesc,fileType):
        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
    def get_collection_name(self,fileDesc,fileType):
        # 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])

 

Escribid el siguiente comando SQL en el portal de gestión para recuperar los datos vectoriales

SELECT top 5
id, embedding, document, metadata
FROM SQLUser.rag_document2

image

 

Chatear con el documento ingerido seleccionado

Seleccionad el Documento en la sección de opciones de chat y escribid la pregunta. La aplicación leerá los datos del vector y devolverá la respuesta correspondiente.
image

El siguiente código Python guardará el documento seleccionado en vectores:

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


class RagOpr:
    def ragSearch(self,prompt,id):
        #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: {prompt}
        Relevant Docuemnts: {relevant_docs}
        """
        #Return the answer
        resp = conversation_sum(template)
        return resp['response']

    

Para más detalles, visitad la página de solicitud de intercambio abierto iris-RAG-Gen.

Gracias

Discussion (0)1
Log in or sign up to continue
Article
· Aug 16, 2024 12m read

VSCode を使った ObjectScript コードのデバッグ

Visual Studio Code(VSCode)は、市場で最も一般的なコードエディターです。 Microsoft によって制作され、無料 IDE として配布されています。 VSCode は ObjectScript などの多数のプログラミング言語をサポートしており、2018 年までは Atelier(Eclipse ベース)もサポートしていました。 InterSystems 製品開発の主なオプションの 1 つとして考えられていましたが、 2018 年、InterSystems 開発者コミュニティが VSCode のサポートを発表した際に、関連する InterSystems のプロユーザーらが実際にこのエディターを使用し始め、以来、特に新しいテクノロジー(Docker、Kubernetes、NodeJS、Angular、React、DevOps、GitLab など)を使用する開発者の間でその使用が続いています。 VSCode の一番の機能の中にはデバッグ機能が挙げられます。 そこで、この記事では、クラスコードや %CSP.REST コードなどの ObjectScript コードをデバッグする方法を詳しく紹介します。

Discussion (0)1
Log in or sign up to continue
Article
· Aug 15, 2024 2m read

IRISでエクスポートしたクラスやルーチンをCacheにインポートする方法

通常、Caché でエクスポートしたクラスやルーチンをIRISにインポートすることは可能ですが、IRISよりエクスポートしたクラスやルーチンを Caché にインポートすることはできません。

Caché にインポートしようとすると、以下のようなエラーになります。

USER>do $system.OBJ.Load("C:\temp\test.xml")
 
ロード開始 07/23/2024 16:50:42
ファイル C:\temp\test.xml を xml としてロード中
ERROR #6301 行: 2 オフセット: 117 これはCacheエクスポートファイルではありません。インポートできません。
読込時に 1 個のエラーを検出しました。
 


どうしても、古いバージョンにインポートする必要がある場合、「/exportversion」というエクスポート修飾子を使用することが可能です。

使用方法は以下のようになります。/exportversion には、エクスポートしたルーチンをインポートしたい環境のCacheバージョンを指定します。

USER>write $SYSTEM.OBJ.Export("test.mac","c:\temp\test2.xml","/exportversion=cache2018.1")


ただし、/exportversion を指定しても、エクスポートシステムとインポートシステム間のコードの互換性は保証されませんので、ご注意ください。
※一部の関数や API は IRIS では名前が異なり、IRIS 専用のものもあります。

詳細は以下のドキュメントをご覧ください。

エクスポート修飾子

2 Comments
Discussion (2)0
Log in or sign up to continue
Question
· Aug 15, 2024

Get '[Errro] Command "iris start IRIS quietly" exited with status 256' when run https://github.com/intersystems-ib/workshop-fhir-adapter/

iris | [ERROR] Command "iris start IRIS quietly" exited with status 256
iris |
iris |
iris |
iris | *** Recovery started at Thu Aug 15 05:47:48 2024
iris | Current default directory: /usr/irissys/mgr
iris | Log file directory: /usr/irissys/mgr/
iris | WIJ file spec: /usr/irissys/mgr/IRIS.WIJ
iris | Recovering local (/usr/irissys/mgr/IRIS.WIJ) image journal file...
iris | Starting WIJ recovery for '/usr/irissys/mgr/IRIS.WIJ'.
iris | 0 blocks pending in this WIJ.
iris | Exiting with status 3 (Success)
iris | 08/15/24-05:47:48:778 (828) 3 [Utility.Event] Error while moving data directories ERROR #5001: Cannot create target: /shared/durable/
iris | [ERROR] See the above messages or /shared/durable/mgr/messages.log for more information
iris | [FATAL] Error starting InterSystems IRIS (final attempt)

2 Comments
Discussion (2)0
Log in or sign up to continue