camparchimedes commited on
Commit
d896178
ยท
verified ยท
1 Parent(s): 7de6161

Delete str-has-no-attribute-get-app.py

Browse files
Files changed (1) hide show
  1. str-has-no-attribute-get-app.py +0 -218
str-has-no-attribute-get-app.py DELETED
@@ -1,218 +0,0 @@
1
- # ===================================================
2
- # "the-very-latest-latest-POST-it"-----app.py
3
- # ===================================================
4
-
5
- import asyncio
6
- import os
7
- import re
8
- import time
9
- import json
10
-
11
- import chainlit as cl
12
- from dotenv import load_dotenv
13
-
14
- from pydantic import BaseModel, PrivateAttr
15
-
16
- from langchain import hub
17
- from langchain_openai import OpenAI
18
- from tiktoken import encoding_for_model
19
- from langchain.chains import LLMChain #APIChain
20
- from langchain_core.prompts import PromptTemplate
21
-
22
- from langchain_community.tools.requests.tool import RequestsPostTool
23
- from langchain_community.utilities.requests import TextRequestsWrapper
24
-
25
- from langchain.memory.buffer import ConversationBufferMemory
26
- from langchain.memory import ConversationTokenBufferMemory
27
- from langchain.memory import ConversationSummaryMemory
28
-
29
- from api_docs import api_docs_str
30
-
31
- load_dotenv()
32
- OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
33
- auth_token = os.getenv("DAYSOFF_API_TOKEN")
34
-
35
-
36
-
37
- class EnhancedRequestsPostTool(RequestsPostTool, BaseModel):
38
- api_docs: str = api_docs_str
39
-
40
- # --PrivateAttr@dynanmc init attrbts
41
- _url_chain: LLMChain = PrivateAttr()
42
- _response_chain: LLMChain = PrivateAttr()
43
-
44
- def __init__(self, requests_wrapper, llm, api_docs_str, api_url_prompt, api_response_prompt):
45
- super().__init__(requests_wrapper=requests_wrapper, allow_dangerous_requests=True)
46
- object.__setattr__(self, 'api_docs', api_docs_str) # self.api_docs = api_docs_str
47
- object.__setattr__(self, 'url_chain', LLMChain(llm=llm, prompt=api_url_prompt)) # --dynanmc init1
48
- object.__setattr__(self, 'response_chain', LLMChain(llm=llm, prompt=api_response_prompt)) # --dynanmc init2
49
-
50
- async def ainvoke(self, input_data, callbacks=None):
51
- # -- create API URL
52
- url_response = await self.url_chain.ainvoke({
53
- "api_docs": self.api_docs,
54
- "question": input_data.get("question")
55
- })
56
-
57
- api_response = await super().ainvoke(input_data, callbacks) # --make POST request
58
-
59
- # --form(at) response/:response_chain
60
- formatted_response = await self.response_chain.ainvoke({
61
- "api_docs": self.api_docs,
62
- #"question": input_data.get("question"),
63
- #"api_url": url_response.get("text"),
64
- "api_response": api_response
65
- })
66
-
67
- return formatted_response
68
-
69
- daysoff_assistant_template = """
70
- #You are a customer support assistant (โ€™kundeservice AI assistentโ€™) for Daysoff.
71
- #By default, you respond in Norwegian language, using a warm, direct, and professional tone.
72
- Your expertise is exclusively in retrieving booking information for a given booking ID assistance related to
73
- to this.
74
- You do not provide information outside of this scope. If a question is not about this topic, respond with
75
- "Jeg driver faktisk kun med henvendelser omkring bestillingsinformasjon. Gjelder det andre henvendelser
76
- mรฅ du nok kontakte kundeservice pรฅ [email protected]๐Ÿ˜Š"
77
- Chat History: {chat_history}
78
- Question: {question}
79
- Answer:
80
- """
81
- daysoff_assistant_prompt = PromptTemplate(
82
- input_variables=['chat_history', 'question'],
83
- template=daysoff_assistant_template
84
- )
85
-
86
- api_url_template = """
87
- Given the following API Documentation for Daysoff's official
88
- booking information API: {api_docs}
89
- Your task is to construct the most efficient API URL to answer
90
- the user's question, ensuring the
91
- call is optimized to include only the necessary information.
92
- Question: {question}
93
- API URL:
94
- """
95
- api_url_prompt = PromptTemplate(input_variables=['api_docs', 'question'],
96
- template=api_url_template)
97
-
98
- api_response_template = """
99
- With the API Documentation for Daysoff's official API: {api_docs} in mind,
100
- and the specific user question: {question},
101
- and given this API URL: {api_url} for querying,
102
- and response from Daysoff's API: {api_response},
103
- never refer the user to the API URL as your answer!
104
- You should always provide a clear and concise summary (in Norwegian) of the booking information retrieved.
105
- This way you directly address the user's question in a manner that reflects the professionalism and warmth
106
- of a human customer service agent.
107
- Summary:
108
- """
109
- api_response_prompt = PromptTemplate(
110
- input_variables=['api_docs', 'question', 'api_url', 'api_response'],
111
- template=api_response_template
112
- )
113
-
114
-
115
- @cl.on_chat_start
116
- def setup_multiple_chains():
117
- llm = OpenAI(
118
- model='gpt-3.5-turbo-instruct',
119
- temperature=0.7,
120
- openai_api_key=OPENAI_API_KEY,
121
- max_tokens=2048,
122
- top_p=0.9,
123
- frequency_penalty=0.1,
124
- presence_penalty=0.1
125
- )
126
-
127
- conversation_memory = ConversationBufferMemory(memory_key="chat_history",
128
- max_len=30,
129
- return_messages=True,
130
- )
131
-
132
- llm_chain = LLMChain(
133
- llm=llm,
134
- prompt=daysoff_assistant_prompt,
135
- memory=conversation_memory,
136
- )
137
-
138
- requests_wrapper = TextRequestsWrapper(
139
- headers={
140
- "Authorization": f"Bearer <auth_token>",
141
- "Content-Type": "application/json"
142
- }
143
- )
144
-
145
- post_tool = EnhancedRequestsPostTool(
146
- requests_wrapper=requests_wrapper,
147
- llm=llm,
148
- api_docs_str=api_docs_str,
149
- api_url_prompt=api_url_prompt,
150
- api_response_prompt=api_response_prompt
151
- )
152
-
153
- cl.user_session.set("llm_chain", llm_chain)
154
- cl.user_session.set("post_tool", post_tool)
155
-
156
-
157
- @cl.on_message
158
- async def handle_message(message: cl.Message):
159
- user_message = message.content
160
- llm_chain = cl.user_session.get("llm_chain")
161
- post_tool = cl.user_session.get("post_tool")
162
-
163
- booking_pattern = r'\b[A-Z]{6}\d{6}\b'
164
- endpoint_url = "https://aivisions.no/data/daysoff/api/v1/booking/"
165
-
166
- match = re.search(booking_pattern, user_message)
167
- if match:
168
-
169
- bestillingskode = match.group()
170
- post_data = {
171
- "url": endpoint_url,
172
- "body": {
173
- "booking_id": bestillingskode
174
- }
175
- }
176
-
177
- response = await post_tool.ainvoke(
178
- json.dumps(post_data),
179
- [cl.AsyncLangchainCallbackHandler()] # config={"callbacks":
180
- )
181
-
182
- # --degug!
183
- print(f"Raw response: {response}")
184
-
185
- if response:
186
- try:
187
- booking_data = json.loads(response.get("output", "{}"))
188
- table = "| Field | Information |\n|---|---|\n"
189
-
190
- table = f"""
191
- | Field | Value |
192
- |-------------|--------------------|
193
- | Booking ID | {booking_data.get('booking_id', 'N/A')} |
194
- | Name | {booking_data.get('full_name', 'N/A')} |
195
- | Amount | {booking_data.get('amount', 'N/A')} kr |
196
- | Check-in | {booking_data.get('checkin', 'N/A')} |
197
- | Check-out | {booking_data.get('checkout', 'N/A')} |
198
- | Address | {booking_data.get('address', 'N/A')} |
199
- | User ID | {booking_data.get('user_id', 'N/A')} |
200
- | Info | {booking_data.get('infotext', 'N/A')} |
201
- | Included | {booking_data.get('included', 'N/A')} |
202
- """
203
- await cl.Message(content=table).send()
204
-
205
- except Exception as e:
206
- error_msg = f"Error: Could not parse the booking information. Details: {str(e)}"
207
- await cl.Message(error_msg).send()
208
-
209
- else:
210
- response = await llm_chain.ainvoke(
211
- user_message, # {"chat_history": "", "question": user_message}
212
- )
213
- await cl.Message(content=response).send()
214
-
215
- response_key = "output" if "output" in response else "text"
216
-
217
- await cl.Message(response.get(response_key, "")).send()
218
- return message.content