File size: 4,114 Bytes
9abed2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25cb7e3
 
 
9abed2e
25cb7e3
9abed2e
25cb7e3
9abed2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import os
import google.generativeai as genai
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_community.vectorstores import FAISS
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
from langchain.prompts import PromptTemplate
import json
import re
from Classes.Helper_Class import DB_Retriever
from typing import Optional

os.environ["GOOGLE_API_KEY"] = "AIzaSyBoghqvvnMMS4bA61LjQkkPNdIRetqk438"
genai.configure(api_key="AIzaSyBoghqvvnMMS4bA61LjQkkPNdIRetqk438")

class OWiki:
    def __init__(self,**kwargs):
        temperature = kwargs['temperature']
        self.summary = kwargs['summary_length']
        model = kwargs["model"]
        self.db_loc = kwargs["db_loc"]
        self.llm = ChatGoogleGenerativeAI(model=model,
                            temperature=temperature)
        self.model_embedding = kwargs['model_embeddings']
    

    def get_summary_template(self):
        prompt = """Generate a summary for the following conversational data in less than {summary} lines.\nText:\n{text}\n\nSummary:"""
        prompt_template = PromptTemplate(template = prompt,input_variables=['summary','text'])
        return prompt_template
    
    def create_sql_prompt_template(self,schemas):
        prompt =  """Write an SQL query for the following questions whose schemas are as follows.\nSQL Schema:"""
        for table_name,table_schema in schemas.items():
            prompt+= f"Table Name: {table_name} Schema:"
            for key,value in table_schema.items():
                prompt+= f"{key} {value}"
        prompt+=  """\n\nQuestion:{question}\n\nAnswer:"""
        # print("Prompt",prompt,'\n\n')
        prompt_template = PromptTemplate(template = prompt,input_variables=['question'])
        # print("Prompt template",prompt_template)
        return prompt_template

    def create_prompt_for_OIC_bot(self):
        template = """You are OIC(Oracle Integration Cloud) Bot.Follow chat instructions and answer the question based only on the following 
        Chat_instructions:
        1. Response must contain Question Explaination along with Potential Solution Headings.
        2. Response must contain all possible Error Scenarios if applicable along with a Summary Heading containing breif summary at the end.

        Context:
        {context}
        
        Question: {question}
        """
        prompt = PromptTemplate.from_template(template)
        return prompt
    
    def create_sql_agent(self,question,schemas):
        prompt_template = self.create_sql_prompt_template(schemas)
        chain = prompt_template | self.llm | StrOutputParser()
        response = chain.invoke({"question":question})
        response = self.format_llm_response(response)
        return response
    
    def generate_summary(self,text):
        prompt_template = self.get_summary_template()
        chain = prompt_template | self.llm | StrOutputParser()
        response = chain.invoke({"text":text,"summary":self.summary})
        return response

    def format_llm_response(self,text):
        bold_pattern = r"\*\*(.*?)\*\*"
        italic_pattern = r"\*(.*?)\*"
        code_pattern = r"```(.*?)```"
        text = text.replace('\n', '<br>')
        formatted_text = re.sub(code_pattern,"<pre><code>\\1</code></pre>",text)
        formatted_text = re.sub(bold_pattern, "<b>\\1</b>", formatted_text)
        formatted_text = re.sub(italic_pattern, "<i>\\1</i>", formatted_text)
        return formatted_text

    def search_from_db(self, query : str, chat_history : Optional[str] ) -> str :
        db = DB_Retriever(self.db_loc,self.model_embedding)
        retriever = db.retrieve(query)
        prompt = self.create_prompt_for_OIC_bot()
        chat_history = self.generate_summary(chat_history)
        retrieval_chain = (
        {"context": retriever, "question": RunnablePassthrough()}
        | prompt
        | self.llm
        | StrOutputParser()
        )
        response = retrieval_chain.invoke(query)
        response = self.format_llm_response(response)
        return response