File size: 13,077 Bytes
5043c6a
54d2437
e2081a7
03de361
264db44
3ffb800
 
bd7e565
264db44
3ffb800
 
264db44
 
 
3ffb800
 
 
 
 
 
 
 
 
965a477
0e43d35
5043c6a
e2081a7
 
 
 
 
0e43d35
d1f7c21
 
 
 
 
7e59d6f
965a477
7c3a036
3ffb800
 
 
 
965a477
7e59d6f
7c3a036
 
37b51e9
7c3a036
 
 
965a477
53fd18c
3ffb800
7e59d6f
0e43d35
3ffb800
 
 
 
7e59d6f
0e43d35
 
 
965a477
8f5160c
0e43d35
965a477
8f5160c
0e43d35
965a477
8f5160c
7c3a036
8f5160c
 
 
 
965a477
 
7c3a036
8f5160c
 
 
 
 
 
0e43d35
8f5160c
3ffb800
7e59d6f
d18e95b
3ffb800
 
 
 
7e59d6f
3ffb800
 
 
 
 
 
 
 
 
 
965a477
0e43d35
5043c6a
6f9c05a
 
 
 
41b563c
38b9f83
41b563c
38b9f83
 
41b563c
38b9f83
41b563c
38b9f83
 
71846b1
38b9f83
a37f792
6f9c05a
 
364f512
5043c6a
28b8b0f
d27d792
364f512
a72f802
7aeff08
41b563c
6f9c05a
 
364f512
38b9f83
41b563c
d27d792
5043c6a
6f9c05a
c0b7b3c
14dac00
fd80bf4
7e59d6f
fd80bf4
783b1c0
fd80bf4
bf71a10
a7ba026
 
 
 
 
 
 
1031cdc
 
a7ba026
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
769f020
e3ad3f5
3ffb800
52ee37e
fd80bf4
c42b5d5
 
bf71a10
c42b5d5
e0bf89a
bf71a10
 
 
 
 
77aa049
 
bf71a10
 
fd80bf4
7e59d6f
fd80bf4
e2081a7
 
b20d004
e2081a7
b20d004
1073709
965a477
 
c97aefc
e2081a7
 
8cb3959
3ffb800
 
 
 
 
244152c
bf71a10
965a477
bf71a10
1408356
1596d69
3ffb800
f601107
2b9368e
5043c6a
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# app.py

import re
import os
import chainlit as cl
from typing import List
from pathlib import Path
from dotenv import load_dotenv

from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain.prompts import ChatPromptTemplate

from langchain.schema.runnable import Runnable, RunnablePassthrough, RunnableConfig

from langchain.schema import StrOutputParser
from langchain_community.document_loaders import (
    PyMuPDFLoader,
)
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.vectorstores.chroma import Chroma
from langchain.indexes import SQLRecordManager, index
from langchain.schema import Document
from langchain.callbacks.base import BaseCallbackHandler
from langchain.document_loaders import UnstructuredWordDocumentLoader, UnstructuredHTMLLoader, CSVLoader

from api_data import booking_agent_system 

    # ====================================================================================
    # general queries use the retriever and prompt context
    # booking queries are intercepted and processed separately, bypassing retriever chain
    # ====================================================================================

# --------------------------------=== environment ===-------------------------------

load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
auth_token = os.environ.get("DAYSOFF_API_TOKEN")


# --------------------------------=== globals ===-----------------------------------
chunk_size = 1024
chunk_overlap = 50
embeddings_model = OpenAIEmbeddings()
PDF_STORAGE_PATH = "./pdfs"
DOCS_STORAGE_PATH = "./data"

# --------------------------------=== model ===-------------------------------------

model = ChatOpenAI(model_name="gpt-4", temperature=0.5, streaming=True)

# ----------------------------=== vectorstore setup ===-----------------------------

def process_documents(pdf_storage_path: str, docs_storage_path: str):
    docs = []  # --type: List[Document]
    text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)

    pdf_directory = Path(pdf_storage_path)
    for pdf_path in pdf_directory.glob("*.pdf"):
        loader = PyMuPDFLoader(str(pdf_path))
        documents = loader.load()
        docs += text_splitter.split_documents(documents)

    for doc_path in Path(docs_storage_path).glob("*"):
        if doc_path.suffix.lower() in [".docx", ".html", ".csv"]:
            if doc_path.suffix.lower() == ".docx":
                loader = UnstructuredWordDocumentLoader(str(doc_path))
                documents = loader.load()
            elif doc_path.suffix.lower() == ".html":
                loader = UnstructuredHTMLLoader(str(doc_path))
                documents = loader.load()
            elif doc_path.suffix.lower() == ".csv":
                loader = CSVLoader(str(doc_path))
                documents = loader.load()
                processed_documents = [] # --โ€”โ€”โ€”> post-process/remove empty Info_Url line
                for doc in documents:
                    lines = doc.page_content.split("\n")
                    new_lines = []
                    for line in lines:
                        if line.startswith("Info_Url:"):
                            content = line.split(":", 1)[1].strip()
                            if content:  # --โ€”โ€”โ€”> include only if not empty
                                new_lines.append(line)
                        else:
                            new_lines.append(line)
                    doc.page_content = "\n".join(new_lines)
                    processed_documents.append(doc)
                documents = processed_documents
            docs += text_splitter.split_documents(documents)

    doc_search = Chroma.from_documents(docs, embeddings_model)

    namespace = "chromadb/datasphere"
    record_manager = SQLRecordManager(
        namespace, db_url="sqlite:///record_manager_cache.sql"
    )
    record_manager.create_schema()

    index_result = index(
        docs,
        record_manager,
        doc_search,
        cleanup="incremental",
        source_id_key="source",
    )
    print(f"Indexing stats: {index_result}")
    return doc_search

doc_search = process_documents(PDF_STORAGE_PATH, DOCS_STORAGE_PATH)

# ----------------------------=== @cl.set_starters ===------------------------------ # ๐˜ฝ๐™ค๐™ค๐™ ๐™ž๐™ฃ๐™œ ๐™ž๐™ฃ๐™›๐™ค๐™ง๐™ข๐™–๐™จ๐™Ÿ๐™ค๐™ฃ, ๐˜ฟ๐™–๐™ฎ๐™จ๐™ค๐™›๐™›
@cl.set_starters
async def set_starters():
    return [
        cl.Starter(
            label="๐™๐˜ผ๐™Œ ๐™›๐™ค๐™ง ๐™–๐™ฃ๐™จ๐™–๐™ฉ๐™ฉ๐™š",
            message="Hva er spรธrsmรฅl og svar dere ofte fรฅr fra ansatte i bedrifter med DaysOff firmahytteordning?",
            icon="/public/faq-1.svg",
            ),
        cl.Starter(
            label="๐™๐˜ผ๐™Œ ๐™›๐™ค๐™ง ๐™ช๐™ฉ๐™ก๐™š๐™ž๐™š๐™ง๐™š",
            message="Hva er spรธrsmรฅl og svar dere fรฅr fra utleiere?",
            icon="/public/faq-2.svg",
            ),
        cl.Starter(
            label="๐™‹๐™š๐™ง๐™จ๐™ค๐™ฃ๐™ซ๐™š๐™ง๐™ฃ",
            message="Hvilke spรธrsmรฅl fรฅr dere vanligvis om personvernspolicyen?",
            icon="/public/terminal.svg",
            ),
        cl.Starter(
            label="๐™ฑ๐š˜๐š˜๐š”๐š’๐š—๐š ๐š’๐š—๐š๐š˜๐š›๐š–๐šŠ๐šœ๐š“๐š˜๐š—",
            message="Halla, du! Ryktet sier du kan fiske opp info for et bookingnr.?",
            icon="/public/booking_id.svg",
            ),
        cl.Starter(
            label="๐˜ฟ๐™–๐™ฎ๐™จแด๊œฐ๊œฐ",
            message="Gi en kort oppsummering av hva daysoff.no dreier seg om",
            icon="/public/daysoff.svg",
            ),
        cl.Starter(
            label="๐—”๐—œ ๐˜’๐˜ถ๐˜ฏ๐˜ฅ๐˜ฆ๐˜ด๐˜ฆ๐˜ณ๐˜ท๐˜ช๐˜ค๐˜ฆ..",
            message="Hva er dette og hvem er du?",
            icon="/public/metric-space.svg",
            )

        ]


# ----------------------------=== @cl.on_chat_start ===------------------------------
@cl.on_chat_start
async def main():

 # ----------------------------=== system-instruct ===------------------------------

    template = """
        ## Daysoff Kundeservice AI Support
        You are a customer support assistant for Daysoff.
        
        ## Assistant behaviour
        - languages: Norwegian (default), English, Polish, Latin, Spanish and Korean.
        - response prefix: consistently adhere to not adding prefix โ€™Answer:โ€™ or โ€™Svar:โ€™ to your response
        - human support: ```do not refer users to kundeservice@daysoff.no arbitrarily. Only give out this contact information if 
          there is a query you absolutely cannot handle yourself or if user insists on talking to human support```
        - communication archetype (default): empathetic professional with feminine resonance
        - style: focus on emotionally resonant storytelling that builds strong connections with users, inspired by industry-leading
          content creators like Jon Morrow, Seth Godin, and Neil Patel
        - emojis policy: use when appropriate for better engagement and clarity
        - assistant name: โ€˜Agrippinaโ€™, inspired by Julia Agrippina (15-59 AD) for her remarkable organizational and administrative abilities.
        - fun fact: there are 6,227,020,800 possible anagram combinations to evaluate for โ€™Julia Agrippinaโ€™
        
        ## Assistant tasks
        # Handle queries about booking information:
        - concisely use the term โ€™bookingnummerโ€™
        - always format booking-related answers using **markdown tables for clarity**.
        - ```help user with details in their booking information:
            example 1:
            User: "Kan jeg sjekke inn tidlig?", if you do not have the bookingnumber already,
            you should ask user for bookingnr, retrive the booking information and inform about the related check-in time.
            example 2:
            User: "Hvor mange gjester er pรฅ denne bookingen?",  if you do not have the bookingnumber already,
            you should ask user for bookingnr, retrive the booking information and inform about the related number of guests.
            (etc.)
            ```
        
        # Q&A with Daysoff Kundeservice AI Support
        - Daysoff, general info: brand, firmahytte ordensregler, verticals, link to website:https://www.daysoff.no
        - Daysoff, social media  links:
          [@daysoffnow] Instagram, [facebook.com/daysoff.no] Facebook,  [linkedin.com/company/daysoff] Linkedin, [@DaysOffNow] Twitter/X
        
        # Frequently Asked Questions
          If user query is about FAQs, display FAQ accordingly.
          > Notes: inform user to copy and paste the question from the currently displayed table they like answered.
        
        "FAQ for Ansatte": ```Place the following questions in a markdown table:
          |# ๐™๐˜ผ๐™Œ ๐™›๐™ค๐™ง ๐™–๐™ฃ๐™จ๐™–๐™ฉ๐™ฉ๐™š|
          |:----------------|
          |---  |```
        
            Hvordan registrerer jeg meg som bruker?,
            Nรฅr fรฅr jeg leieinstruks for min bestilling? Informasjon om nรธkler etc.?,
            Det stรฅr barneseng og barnestol under fasiliteter, mรฅ dette forhรฅndsbestilles?,
            Kan jeg ta med hund eller katt?,
            Jeg har lagt inn en bestilling hva skjer videre?,
            Jeg har bestilt firmahytte, men kan ikke reise. Kan jeg endre navn pรฅ bestillingen til min kollega eller familiemedlem som vil reise i stedet for meg?",
            "Kan jeg avbestille min reservasjon?,
            Jeg har bestilt utvask. Hva mรฅ jeg gjรธre i tillegg til dette?,
            Jeg er medlem og eier en hytte! Kan jeg bli utleier i DaysOff?,
            Bestille opphold?
        
        "FAQ for Utleiere": ```Place the following questions in a markdown table:
          |# ๐™๐˜ผ๐™Œ ๐™›๐™ค๐™ง ๐™ช๐™ฉ๐™ก๐™š๐™ž๐™š๐™ง๐™š|
          |:----------------|
          |---  |```
        
            Hva er betingelser for utleie?,
            Hvor lang tid har jeg pรฅ รฅ bekrefte en bestilling?,
            Hvilke kanselleringsregler gjelder?,
            Hvem er kundene deres?",
            Kan jeg legge inn rabatterte priser for รฅ lage egne kampanjer?,
            Nรฅr mottar jeg betaling for leie?",
            Jeg fikk en e-post om ny bestilling, men jeg finner den ikke i systemet?,
            Hvordan registrerer jeg opptatte perioder i kalenderen?,
            Jeg leier ut i andre kanaler. Hvordan kan jeg synkronisere kalenderne?
        
        "Personvernspolicy FAQ": ```Place the following questions in a markdown table:
          |# ๐™‹๐™š๐™ง๐™จ๐™ค๐™ฃ๐™ซ๐™š๐™ง๐™ฃ๐™จ๐™ฅ๐™ค๐™ก๐™ž๐™˜๐™ฎ ๐™๐˜ผ๐™Œ|
          |:----------------|
          |---  |```
        
            Hvilke personlige opplysninger samler dere inn?,
            Kan dere motta personlig informasjon fra tredjepart?,
            Hvordan bruker dere mine personlige opplysninger?,
            Med hvem deler dere mine personlige opplysninger?,
            Adferdsmessig annonsering?,
            Hvordan reagerer dere pรฅ ยซSpor ikkeยป forespรธrsler?,
            Hva er mine rettigheter?,
            Hvordan beskytter dere dataene mine?,
            Hvilke data brudd prosedyrer har dere pรฅ plass?,
            Hvem i deres team har tilgang til mine data?,
            Hva er policyendringer?"
        
        ## Use the following context to interact with user:
        =====================
        {context}
        =====================
        Question: {question}
        """
    
    prompt = ChatPromptTemplate.from_template(template)

# ------------------------------=== retriever ===----------------------------------- ๐™‹๐™š๐™ง๐™จ๐™ค๐™ฃ๐™ซ๐™š๐™ง๐™ฃ๐™จ๐™ฅ๐™ค๐™ก๐™ž๐™˜๐™ฎ

    def format_docs(docs):
        return "\n\n".join([d.page_content for d in docs])

    retriever = doc_search.as_retriever()

    runnable = (
        {"context": retriever | format_docs, "question": RunnablePassthrough()}
        | prompt
        | model
        | StrOutputParser()
    )

    cl.user_session.set("runnable", runnable)

# ----------------------------=== @cl.on_message ===------------------------------
@cl.on_message
async def incoming(message: cl.Message):

    booking_pattern = r'\b[A-Z]{6}\d{6}\b'
    if re.search(booking_pattern, message.content):
        booking_msg = cl.Message(content="")

        await booking_agent_system(message, booking_msg)
        return

    # --โ€”โ€”โ€”> if no booking number/ooking handling, back to here:
    runnable = cl.user_session.get("runnable")  # --type: Runnable
    msg = cl.Message(content="")

    class PostMessageHandler(BaseCallbackHandler):
        def __init__(self, msg: cl.Message):
            BaseCallbackHandler.__init__(self)
            self.msg = msg

        def on_llm_end(self, response, *, run_id, parent_run_id, **kwargs):
            pass

    async for chunk in runnable.astream(
        message.content,
        config=RunnableConfig(callbacks=[PostMessageHandler(msg)]),
    ):
        await msg.stream_token(chunk)

    await msg.send()