File size: 7,339 Bytes
4d4c181
 
 
 
 
c839b4c
4d4c181
 
 
 
 
 
 
 
 
 
c5ab12e
c839b4c
4d4c181
 
c5ab12e
 
 
 
 
 
4d4c181
 
 
 
 
 
 
 
 
c5ab12e
4d4c181
 
c839b4c
 
4d4c181
c5ab12e
4d4c181
 
 
 
 
 
 
 
 
 
 
48c9d4e
4d4c181
 
 
 
c839b4c
4d4c181
c839b4c
4d4c181
 
 
 
c839b4c
 
 
 
 
4d4c181
 
 
 
 
 
c839b4c
4d4c181
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5ab12e
c839b4c
4d4c181
c5ab12e
 
4d4c181
 
 
c5ab12e
4d4c181
 
 
 
 
 
c5ab12e
4d4c181
c5ab12e
4d4c181
c5ab12e
 
 
 
 
a3d3d25
4d4c181
 
c5ab12e
 
 
 
 
 
 
 
 
 
 
4d4c181
c5ab12e
4d4c181
 
 
 
 
 
 
 
 
c839b4c
 
c5ab12e
 
 
4d4c181
c839b4c
 
4d4c181
c5ab12e
 
 
 
 
 
 
 
 
 
 
 
 
 
c839b4c
c5ab12e
4d4c181
 
c5ab12e
4d4c181
c5ab12e
 
4d4c181
 
 
 
 
c5ab12e
 
4d4c181
c5ab12e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c839b4c
 
 
 
 
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import os
import pandas as pd
import chainlit as cl
from chainlit import user_session
from chainlit.types import LLMSettings
from chainlit.logger import logger
from langchain import LLMChain
from langchain.prompts import PromptTemplate
from langchain.llms import AzureOpenAI
from langchain.document_loaders import DataFrameLoader
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.memory import ConversationBufferWindowMemory
from langchain.vectorstores import Chroma
from langchain.vectorstores.base import VectorStoreRetriever


current_agent = "Demo"
vectordb = None


def load_agent():
    df = pd.read_excel(os.environ["AGENT_SHEET"], header=0, keep_default_na=False)
    df = df[df["Agent"] == current_agent]
    return df


def load_dialogues():
    df = pd.read_excel(os.environ["DIALOGUE_SHEET"], header=0, keep_default_na=False)
    df = df[df["Agent"] == current_agent]
    return df.astype(str)


def load_persona():
    df = pd.read_excel(os.environ["PERSONA_SHEET"], header=0, keep_default_na=False)
    df = df[df["Agent"] == current_agent]
    return df


def load_prompts():
    df = pd.read_excel(os.environ["PROMPT_SHEET"], header=0, keep_default_na=False)
    df = df[df["Agent"] == current_agent]
    return df


def load_documents(df, page_content_column: str):
    return DataFrameLoader(df, page_content_column).load()


def init_embedding_function():
    EMBEDDING_MODEL_FOLDER = ".embedding-model"
    return HuggingFaceEmbeddings(
        model_name="sentence-transformers/all-mpnet-base-v2",
        encode_kwargs={"normalize_embeddings": True},
        #cache_folder=EMBEDDING_MODEL_FOLDER,
    )


def load_vectordb(init: bool = False):
    global vectordb
    VECTORDB_FOLDER = ".vectordb"
    if not init and vectordb is None:
        vectordb = Chroma(
            embedding_function=init_embedding_function(),
            persist_directory=VECTORDB_FOLDER,
        )
        if not vectordb.get()["ids"]:
            init = True
        else:
            logger.info(f"Vector DB loaded")
    if init:
        vectordb = Chroma.from_documents(
            documents=load_documents(load_dialogues(), page_content_column="Utterance"),
            embedding=init_embedding_function(),
            persist_directory=VECTORDB_FOLDER,
        )
        vectordb.persist()
        logger.info(f"Vector DB initialised")
    return vectordb


def get_retriever(context_state: str, vectordb):
    return VectorStoreRetriever(
        vectorstore=vectordb,
        search_type="similarity",
        search_kwargs={
            "filter": {
                "$or": [{"Context": {"$eq": ""}}, {"Context": {"$eq": context_state}}]
            },
            "k": 1,
        },
    )


@cl.langchain_factory(use_async=True)
def factory():
    df_agent = load_agent()
    load_vectordb()
    user_session.set("context_state", "")
    user_session.set("df_prompts", load_prompts())
    user_session.set("df_persona", load_persona())

    llm_settings = LLMSettings(
        model_name="text-davinci-003",
        temperature=0.7,
    )
    user_session.set("llm_settings", llm_settings)

    chat_memory = ConversationBufferWindowMemory(
        memory_key="History",
        input_key="Utterance",
        k=df_agent["History"].values[0],
    )
    user_session.set("chat_memory", chat_memory)

    llm = AzureOpenAI(
        deployment_name="davinci003",
        model_name=llm_settings.model_name,
        temperature=llm_settings.temperature,
        streaming=True,
        openai_api_key=cl.user_session.get("env").get("OPENAI_API_KEY") if "OPENAI_API_KEY" not in os.environ else None
    )

    default_prompt = """{History}
    ##
    System: {Persona}
    ##
    Human: {Utterance}
    Response: {Response}
    ##
    AI:"""

    return LLMChain(
        prompt=PromptTemplate.from_template(default_prompt),
        llm=llm,
        verbose=True,
        memory=chat_memory,
    )


@cl.langchain_run
async def run(agent, input_str):
    global vectordb
    if input_str == "/reload":
        vectordb = load_vectordb(True)
        return await cl.Message(content="Data loaded").send()

    df_prompts = user_session.get("df_prompts")
    df_persona = user_session.get("df_persona")
    llm_settings = user_session.get("llm_settings")

    retriever = get_retriever(user_session.get("context_state"), vectordb)
    document = retriever.get_relevant_documents(query=input_str)

    prompt = document[0].metadata["Prompt"]
    if not prompt:
        await cl.Message(
            content=document[0].metadata["Response"],
            author=document[0].metadata["Role"],
        ).send()
    else:
        agent.prompt = PromptTemplate.from_template(
            df_prompts.loc[df_prompts["Prompt"] == prompt]["Template"].values[0]
        )
        llm_settings.temperature = df_prompts.loc[df_prompts["Prompt"] == prompt][
            "Temperature"
        ].values[0]
        agent.llm.temperature = llm_settings.temperature

        response = await agent.acall(
            {
                "Persona": df_persona.loc[
                    df_persona["Role"] == document[0].metadata["Role"]
                ]["Persona"].values[0],
                "Utterance": input_str,
                "Response": document[0].metadata["Response"],
            },
            callbacks=[cl.AsyncLangchainCallbackHandler()],
        )
        await cl.Message(
            content=response["text"],
            author=document[0].metadata["Role"],
            llm_settings=llm_settings,
        ).send()

    user_session.set("context_state", document[0].metadata["Contextualisation"])
    continuation = document[0].metadata["Continuation"]

    while continuation != "":
        document_continuation = vectordb.get(where={"Intent": continuation})

        prompt = document_continuation["metadatas"][0]["Prompt"]
        if not prompt:
            await cl.Message(
                content=document_continuation["metadatas"][0]["Response"],
                author=document_continuation["metadatas"][0]["Role"],
            ).send()
        else:
            agent.prompt = PromptTemplate.from_template(
                df_prompts.loc[df_prompts["Prompt"] == prompt]["Template"].values[0]
            )
            llm_settings.temperature = df_prompts.loc[df_prompts["Prompt"] == prompt][
                "Temperature"
            ].values[0]
            agent.llm.temperature = llm_settings.temperature

            response = await agent.acall(
                {
                    "Persona": df_persona.loc[
                        df_persona["Role"]
                        == document_continuation["metadatas"][0]["Role"]
                    ]["Persona"].values[0],
                    "Utterance": "",
                    "Response": document_continuation["metadatas"][0]["Response"],
                },
                callbacks=[cl.AsyncLangchainCallbackHandler()],
            )
            await cl.Message(
                content=response["text"],
                author=document_continuation["metadatas"][0]["Role"],
                llm_settings=llm_settings,
            ).send()
        user_session.set(
            "context_state",
            document_continuation["metadatas"][0]["Contextualisation"],
        )
        continuation = document_continuation["metadatas"][0]["Continuation"]