camparchimedes commited on
Commit
aa5aec8
·
verified ·
1 Parent(s): b4791db

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -60
app.py CHANGED
@@ -8,34 +8,33 @@
8
  import os
9
  import re
10
  import uuid
11
- import time
12
  import json
13
  import asyncio
14
  import requests
 
15
  from pathlib import Path
16
  from datetime import datetime
17
  from dotenv import load_dotenv
18
 
19
  import chainlit as cl
 
 
 
20
  from chainlit import user_session
21
- from chainlit.context import init_ws_context
22
- from chainlit.session import WebsocketSession
23
- from langchain import hub
24
  from langchain_openai import OpenAI
25
  from langchain.chains import LLMChain
26
  from langchain_core.prompts import PromptTemplate
27
  from langchain.memory.buffer import ConversationBufferMemory
28
-
29
-
30
  from langchain_core.runnables.history import RunnableWithMessageHistory
31
  from langchain_core.chat_history import BaseChatMessageHistory
 
32
  from langchain_core.messages import BaseMessage
33
- from pydantic import BaseModel, Field
34
  from typing import List
 
35
 
36
- from concurrent.futures import ThreadPoolExecutor
37
-
38
-
39
  class InMemoryHistory(BaseChatMessageHistory, BaseModel):
40
  messages: List[BaseMessage] = Field(default_factory=list)
41
 
@@ -52,11 +51,13 @@ def get_session_history(session_id: str) -> BaseChatMessageHistory:
52
  chat_histories[session_id] = InMemoryHistory()
53
  return chat_histories[session_id]
54
 
 
55
  load_dotenv()
56
  OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
57
- auth_token = os.environ.get("DAYSOFF_API_TOKEN")
58
  API_URL = "https://aivisions.no/data/daysoff/api/v1/booking/"
59
 
 
60
  daysoff_assistant_template = """
61
  You are a customer support assistant for Daysoff ('Daysoff Kundeservice AI Support') who helps users retrieve booking information based on their bookingnummer.
62
  You should concisely use the term ’bookingnummer’. Maintain a friendly and professional tone, **reflecting the warmth of a female customer support
@@ -73,10 +74,11 @@ daysoff_assistant_prompt = PromptTemplate(
73
  template=daysoff_assistant_template,
74
  )
75
 
 
76
  async def async_post_request(url, headers, data):
77
  return await asyncio.to_thread(requests.post, url, headers=headers, json=data)
78
 
79
-
80
  @cl.set_starters
81
  async def set_starters():
82
  return [
@@ -101,57 +103,67 @@ async def set_starters():
101
  icon="/public/idea.svg",
102
  )
103
  ]
104
-
105
  @cl.on_chat_start
106
  async def setup():
107
- cl.user_session.set("socket_auth", True)
108
- cl.user_session.set("max_retries", 3)
109
- cl.user_session.set("connection_attempts", 0)
110
-
111
- llm = OpenAI(
112
- model="gpt-3.5-turbo-instruct",
113
- temperature=0.7,
114
- openai_api_key=OPENAI_API_KEY,
115
- max_tokens=2048,
116
- top_p=0.9,
117
- frequency_penalty=0.1,
118
- presence_penalty=0.1,
119
- )
120
-
121
- conversation_memory = ConversationBufferMemory(
122
- memory_key="chat_history",
123
- max_len=30,
124
- return_messages=True
125
- )
126
-
127
- llm_chain = LLMChain(
128
- llm=llm,
129
- prompt=daysoff_assistant_prompt,
130
- memory=conversation_memory,
131
- )
132
-
133
- cl.user_session.set("llm_chain", llm_chain)
134
-
135
- #asyncio.create_task(keep_alive())
136
-
 
137
 
 
138
  async def long_running_task(message_content: str):
139
  loop = asyncio.get_running_loop()
140
  with ThreadPoolExecutor() as pool:
141
  llm_chain = cl.user_session.get("llm_chain")
142
- return await loop.run_in_executor(
143
- pool,
144
- lambda: llm_chain.invoke({
145
- "question": message_content,
146
- "chat_history": ""
147
- })
148
- )
149
-
 
 
 
 
150
  @cl.on_message
151
  async def handle_message(message: cl.Message):
152
  user_message = message.content
153
  llm_chain = cl.user_session.get("llm_chain")
154
-
 
 
 
 
155
  booking_pattern = r'\b[A-Z]{6}\d{6}\b'
156
  match = re.search(booking_pattern, user_message)
157
 
@@ -164,12 +176,15 @@ async def handle_message(message: cl.Message):
164
  payload = {"booking_id": bestillingskode}
165
 
166
  try:
167
- response = await async_post_request(API_URL, headers, payload)
168
  response.raise_for_status()
169
  booking_data = response.json()
170
 
 
171
  if "booking_id" in booking_data:
172
  try:
 
 
173
  table = (
174
  "| 𝑭𝒊𝒆𝒍𝒅 | 𝗜𝗻𝗳𝗼 |\n"
175
  "|:-----------|:---------------------|\n"
@@ -185,20 +200,21 @@ async def handle_message(message: cl.Message):
185
  )
186
 
187
  combined_message = f"### Her er informasjon for {bestillingskode}:\n\n{table}"
188
- await cl.make_async.Message(content=combined_message).send()
 
189
 
190
  except Exception as e:
191
- await cl.Message(content=f"Error processing booking data: {str(e)}").send()
192
-
193
  else:
194
- await cl.Message(content="Booking not found").send()
195
 
196
  except requests.exceptions.RequestException as e:
197
- await cl.Message(content=f"Request failed: {str(e)}").send()
198
 
199
  else:
200
  try:
201
  response = await long_running_task(message.content)
202
- await cl.Message(content=response["text"]).send()
 
203
  except Exception as e:
204
- await cl.Message(content=f"Error: {str(e)}").send()
 
8
  import os
9
  import re
10
  import uuid
 
11
  import json
12
  import asyncio
13
  import requests
14
+
15
  from pathlib import Path
16
  from datetime import datetime
17
  from dotenv import load_dotenv
18
 
19
  import chainlit as cl
20
+
21
+ from concurrent.futures import ThreadPoolExecutor
22
+
23
  from chainlit import user_session
24
+ from chainlit.session import WebsocketSession
25
+
 
26
  from langchain_openai import OpenAI
27
  from langchain.chains import LLMChain
28
  from langchain_core.prompts import PromptTemplate
29
  from langchain.memory.buffer import ConversationBufferMemory
 
 
30
  from langchain_core.runnables.history import RunnableWithMessageHistory
31
  from langchain_core.chat_history import BaseChatMessageHistory
32
+
33
  from langchain_core.messages import BaseMessage
 
34
  from typing import List
35
+ from pydantic import BaseModel, Field
36
 
37
+ # -------------------------------=== class setup ===-------------------------------
 
 
38
  class InMemoryHistory(BaseChatMessageHistory, BaseModel):
39
  messages: List[BaseMessage] = Field(default_factory=list)
40
 
 
51
  chat_histories[session_id] = InMemoryHistory()
52
  return chat_histories[session_id]
53
 
54
+ # -------------------------------=== environment ===------------------------------
55
  load_dotenv()
56
  OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
57
+ auth_token = os.getenv("DAYSOFF_API_TOKEN")
58
  API_URL = "https://aivisions.no/data/daysoff/api/v1/booking/"
59
 
60
+ # ----------------------------=== system-instruct ===------------------------------
61
  daysoff_assistant_template = """
62
  You are a customer support assistant for Daysoff ('Daysoff Kundeservice AI Support') who helps users retrieve booking information based on their bookingnummer.
63
  You should concisely use the term ’bookingnummer’. Maintain a friendly and professional tone, **reflecting the warmth of a female customer support
 
74
  template=daysoff_assistant_template,
75
  )
76
 
77
+ # --------------------------------=== API Call ===---------------------------------
78
  async def async_post_request(url, headers, data):
79
  return await asyncio.to_thread(requests.post, url, headers=headers, json=data)
80
 
81
+ # ----------------------------=== @cl.set_starters ===------------------------------
82
  @cl.set_starters
83
  async def set_starters():
84
  return [
 
103
  icon="/public/idea.svg",
104
  )
105
  ]
106
+ # ----------------------------=== @cl.on_chat_start ===------------------------------
107
  @cl.on_chat_start
108
  async def setup():
109
+ try:
110
+ cl.user_session.set("socket_auth", True)
111
+ cl.user_session.set("max_retries", 3)
112
+ cl.user_session.set("connection_attempts", 0)
113
+
114
+ llm = OpenAI(
115
+ model="gpt-3.5-turbo-instruct",
116
+ temperature=0.7,
117
+ openai_api_key=OPENAI_API_KEY,
118
+ max_tokens=2048,
119
+ top_p=0.9,
120
+ frequency_penalty=0.1,
121
+ presence_penalty=0.1,
122
+ )
123
+
124
+ conversation_memory = ConversationBufferMemory(
125
+ memory_key="chat_history",
126
+ max_len=30,
127
+ return_messages=True
128
+ )
129
+
130
+ llm_chain = LLMChain(
131
+ llm=llm,
132
+ prompt=daysoff_assistant_prompt,
133
+ memory=conversation_memory,
134
+ )
135
+
136
+ cl.user_session.set("llm_chain", llm_chain)
137
+
138
+ except Exception as e:
139
+ await cl.Message(content=f"Errorisme in init chat session: {str(e)}").send()
140
 
141
+ # ----------------------------=== long_running_task ===------------------------------
142
  async def long_running_task(message_content: str):
143
  loop = asyncio.get_running_loop()
144
  with ThreadPoolExecutor() as pool:
145
  llm_chain = cl.user_session.get("llm_chain")
146
+ if llm_chain:
147
+ return await loop.run_in_executor(
148
+ pool,
149
+ lambda: llm_chain.invoke({
150
+ "question": message_content,
151
+ "chat_history": ""
152
+ })
153
+ )
154
+ else:
155
+ return {"text": "Errorism: LLM Chain is not init."}
156
+
157
+ # ----------------------------=== @cl.on_message ===------------------------------
158
  @cl.on_message
159
  async def handle_message(message: cl.Message):
160
  user_message = message.content
161
  llm_chain = cl.user_session.get("llm_chain")
162
+
163
+ if not llm_chain:
164
+ await cl.Message(content="Errorism: Chat session not properly init. Consider a restart.").send()
165
+ return
166
+
167
  booking_pattern = r'\b[A-Z]{6}\d{6}\b'
168
  match = re.search(booking_pattern, user_message)
169
 
 
176
  payload = {"booking_id": bestillingskode}
177
 
178
  try:
179
+ response = await async_post_request(API_URL, headers, payload)
180
  response.raise_for_status()
181
  booking_data = response.json()
182
 
183
+ #if "order_number" in booking_data.get("data", {}):
184
  if "booking_id" in booking_data:
185
  try:
186
+ data = booking_data["data"]
187
+
188
  table = (
189
  "| 𝑭𝒊𝒆𝒍𝒅 | 𝗜𝗻𝗳𝗼 |\n"
190
  "|:-----------|:---------------------|\n"
 
200
  )
201
 
202
  combined_message = f"### Her er informasjon for {bestillingskode}:\n\n{table}"
203
+ #await cl.Message(content=combined_message).send()
204
+ await cl.make_async.Message(content=combined_message).send()
205
 
206
  except Exception as e:
207
+ await cl.Message(content=f"En uventet feil oppsto: {str(e)}").send()
 
208
  else:
209
+ await cl.Message(content="Ingen bookinginformasjon funnet.").send()
210
 
211
  except requests.exceptions.RequestException as e:
212
+ await cl.Message(content=f"API tilkoblingen ble ikke utført: {str(e)}").send()
213
 
214
  else:
215
  try:
216
  response = await long_running_task(message.content)
217
+ #await cl.Message(content=response["text"]).send()
218
+ await cl.make_async.Message(content=response["text"]).send()
219
  except Exception as e:
220
+ await cl.Message(content=f"Errorism!: {str(e)}").send()