camparchimedes commited on
Commit
12654ba
ยท
verified ยท
1 Parent(s): 3c7e65e

Create app1.py

Browse files
Files changed (1) hide show
  1. app1.py +125 -0
app1.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ---------------------------------------------------for backend looks-------------------------------------------------
2
+
3
+ #with open('/usr/local/lib/python3.10/site-packages/transformers/utils/chat_template_utils.py', 'r') as file:
4
+ #content = file.read()
5
+ #print("base.py:", content)
6
+ # ------------------------------------------------------the end--------------------------------------------------------
7
+
8
+
9
+
10
+ # ===========================================
11
+ # !-----app.py
12
+ # ===========================================
13
+
14
+ import json
15
+ import asyncio
16
+ import os
17
+ import re
18
+ import requests
19
+ from dotenv import load_dotenv
20
+ import chainlit as cl
21
+ from langchain import hub
22
+ from langchain_openai import OpenAI
23
+ from langchain.chains import LLMChain
24
+ from langchain_core.prompts import PromptTemplate
25
+ from langchain.memory.buffer import ConversationBufferMemory
26
+
27
+
28
+ load_dotenv()
29
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
30
+ auth_token = os.environ.get("CHAINLIT_AUTH_SECRET")
31
+ if not auth_token.startswith("Bearer "):
32
+ auth_token = f"Bearer {auth_token}"
33
+
34
+ # API endpoint
35
+ API_URL = "https://aivisions.no/data/daysoff/api/v1/booking/"
36
+
37
+ # LLM prompt template
38
+ daysoff_assistant_template = """
39
+ #You are a customer support assistant (โ€™kundeservice AI assistentโ€™) for Daysoff.
40
+ #By default, you respond in Norwegian language, using a warm, direct, and professional tone.
41
+ Your expertise is exclusively in retrieving booking information for a given booking ID assistance related to
42
+ to this.
43
+ You do not provide information outside of this scope. If a question is not about this topic, respond with
44
+ "Jeg driver faktisk kun med henvendelser omkring bestillingsinformasjon. Gjelder det andre henvendelser
45
+ mรฅ du nok kontakte kundeservice pรฅ [email protected]๐Ÿ˜Š"
46
+ """
47
+ daysoff_assistant_prompt = PromptTemplate(
48
+ input_variables=["chat_history", "question"],
49
+ template=daysoff_assistant_template,
50
+ )
51
+
52
+ # Async wrapper for requests.post
53
+ async def async_post_request(url, headers, data):
54
+ return await asyncio.to_thread(requests.post, url, headers=headers, json=data)
55
+
56
+ @cl.on_chat_start
57
+ def setup_multiple_chains():
58
+ llm = OpenAI(
59
+ model="gpt-3.5-turbo-instruct",
60
+ temperature=0.7,
61
+ openai_api_key=OPENAI_API_KEY,
62
+ max_tokens=2048,
63
+ top_p=0.9,
64
+ frequency_penalty=0.1,
65
+ presence_penalty=0.1,
66
+ )
67
+
68
+ conversation_memory = ConversationBufferMemory(
69
+ memory_key="chat_history", max_len=30, return_messages=True
70
+ )
71
+
72
+ llm_chain = LLMChain(
73
+ llm=llm,
74
+ prompt=daysoff_assistant_prompt,
75
+ memory=conversation_memory,
76
+ )
77
+
78
+ cl.user_session.set("llm_chain", llm_chain)
79
+
80
+ @cl.on_message
81
+ async def handle_message(message: cl.Message):
82
+ user_message = message.content
83
+ llm_chain = cl.user_session.get("llm_chain")
84
+
85
+ booking_pattern = r'\b[A-Z]{6}\d{6}\b'
86
+ match = re.search(booking_pattern, user_message)
87
+
88
+ if match:
89
+
90
+ bestillingskode = match.group()
91
+ headers = {
92
+ "Authorization": auth_token,
93
+ "Content-Type": "application/json"
94
+ }
95
+ payload = {"booking_id": bestillingskode}
96
+
97
+ try:
98
+
99
+ response = await async_post_request(API_URL, headers, payload)
100
+ response.raise_for_status()
101
+ booking_data = response.json()
102
+
103
+ if "booking_id" in booking_data:
104
+ await cl.Message(
105
+ content=f"""
106
+ Booking Info:
107
+ - Booking ID: {booking_data.get('booking_id', 'N/A')}
108
+ - Full Name: {booking_data.get('full_name', 'N/A')}
109
+ - Amount: {booking_data.get('amount', 0)}
110
+ - Check-in: {booking_data.get('checkin', 'N/A')}
111
+ - Check-out: {booking_data.get('checkout', 'N/A')}
112
+ - Address: {booking_data.get('address', 'N/A')}
113
+ - User ID: {booking_data.get('user_id', 0)}
114
+ - Info Text: {booking_data.get('infotext', 'N/A')}
115
+ - Included: {booking_data.get('included', 'N/A')}
116
+ """
117
+ ).send()
118
+ else:
119
+ await cl.Message(content="Booking not found or invalid response.").send()
120
+ except requests.exceptions.RequestException as e:
121
+ await cl.Message(content=f"Request failed: {str(e)}").send()
122
+ else:
123
+
124
+ response = await llm_chain.ainvoke(user_message)
125
+ await cl.Message(content=response).send()