camparchimedes commited on
Commit
ec9c412
·
verified ·
1 Parent(s): acf7259

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -85
app.py CHANGED
@@ -1,15 +1,9 @@
1
 
2
- # ===================================================
3
- # "the-very-latest-latest-POST-it"-----app.py✍🏽 👾
4
- # ===================================================
5
- """
6
- Change from APIChain to EnhancedRequestsPostTool was heisted by the need to handle POST requests.
7
- APIChain internally was responsible for URL construction, API interaction, and response formatting:
8
- EnhancedRequestsPostTool is an enabler for POST handling@RequestsPostTool.
9
- Routing mechanisms for prompts (api_url_prompt+api_response_prompt) remain are being used across distinct components.
10
- """
11
  import asyncio
12
- import concurrent.futures
13
  import os
14
  import re
15
  import time
@@ -18,72 +12,24 @@ import json
18
  import chainlit as cl
19
  from dotenv import load_dotenv
20
 
21
- from pydantic import BaseModel, PrivateAttr
 
 
22
 
23
  from langchain import hub
24
  from langchain_openai import OpenAI
25
  from tiktoken import encoding_for_model
26
- from langchain.chains import LLMChain #APIChain
27
  from langchain_core.prompts import PromptTemplate
28
-
29
- from langchain_community.tools.requests.tool import RequestsPostTool
30
- from langchain_community.utilities.requests import TextRequestsWrapper
31
-
32
  from langchain.memory.buffer import ConversationBufferMemory
33
  from langchain.memory import ConversationTokenBufferMemory
34
  from langchain.memory import ConversationSummaryMemory
35
 
36
  from api_docs import api_docs_str
37
-
38
  load_dotenv()
39
  OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
40
- auth_token = os.getenv("DAYSOFF_API_TOKEN")
41
-
42
- """
43
- class EnhancedRequestsPostTool(RequestsPostTool, BaseModel):
44
- url_chain: LLMChain
45
- response_chain: LLMChain
46
- api_docs: str
47
-
48
- def __init__(self, requests_wrapper, llm, api_docs, api_url_prompt, api_response_prompt):
49
- super().__init__(requests_wrapper=requests_wrapper, allow_dangerous_requests=True)
50
- object.__setattr__(self, 'url_chain', LLMChain(llm=llm, prompt=api_url_prompt)) # object.__setattr__ (’set attribute’, i.e error with "fields")
51
- object.__setattr__(self, 'response_chain', LLMChain(llm=llm, prompt=api_response_prompt))
52
- object.__setattr__(self, 'api_docs', api_docs)
53
- """
54
 
55
- class EnhancedRequestsPostTool(RequestsPostTool, BaseModel):
56
- api_docs: str = api_docs_str
57
-
58
- # --PrivateAttr@dynanmc init attrbts
59
- _url_chain: LLMChain = PrivateAttr()
60
- _response_chain: LLMChain = PrivateAttr()
61
-
62
- def __init__(self, requests_wrapper, llm, api_docs_str, api_url_prompt, api_response_prompt):
63
- super().__init__(requests_wrapper=requests_wrapper, allow_dangerous_requests=True)
64
- object.__setattr__(self, 'api_docs', api_docs_str) # self.api_docs = api_docs_str
65
- object.__setattr__(self, 'url_chain', LLMChain(llm=llm, prompt=api_url_prompt)) # --dynanmc init1
66
- object.__setattr__(self, 'response_chain', LLMChain(llm=llm, prompt=api_response_prompt)) # --dynanmc init2
67
-
68
- async def ainvoke(self, input_data, callbacks=None):
69
- # -- create API URL
70
- url_response = await self.url_chain.ainvoke({
71
- "api_docs": self.api_docs,
72
- "question": input_data.get("question")
73
- })
74
-
75
- api_response = await super().ainvoke(input_data, callbacks) # --make POST request
76
-
77
- # --form(at) response/:response_chain
78
- formatted_response = await self.response_chain.ainvoke({
79
- "api_docs": self.api_docs,
80
- "question": input_data.get("question"),
81
- "api_url": url_response.get("text"),
82
- "api_response": api_response
83
- })
84
-
85
- return formatted_response
86
-
87
  daysoff_assistant_template = """
88
  #You are a customer support assistant (’kundeservice AI assistent’) for Daysoff.
89
  #By default, you respond in Norwegian language, using a warm, direct, and professional tone.
@@ -130,6 +76,7 @@ api_response_prompt = PromptTemplate(
130
  )
131
 
132
 
 
133
  @cl.on_chat_start
134
  def setup_multiple_chains():
135
  llm = OpenAI(
@@ -153,35 +100,47 @@ def setup_multiple_chains():
153
  memory=conversation_memory,
154
  )
155
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  requests_wrapper = TextRequestsWrapper(
157
- headers={
158
- "Authorization": auth_token,
159
- "Content-Type": "application/json"
160
  }
161
  )
162
-
163
- post_tool = EnhancedRequestsPostTool(
164
  requests_wrapper=requests_wrapper,
165
- llm=llm,
166
- api_docs_str=api_docs_str,
167
- api_url_prompt=api_url_prompt,
168
- api_response_prompt=api_response_prompt
169
  )
170
-
171
- cl.user_session.set("llm_chain", llm_chain)
172
  cl.user_session.set("post_tool", post_tool)
173
-
174
 
175
  @cl.on_message
176
  async def handle_message(message: cl.Message):
177
  user_message = message.content
178
  llm_chain = cl.user_session.get("llm_chain")
 
179
  post_tool = cl.user_session.get("post_tool")
180
 
181
  booking_pattern = r'\b[A-Z]{6}\d{6}\b'
182
  endpoint_url = "https://aivisions.no/data/daysoff/api/v1/booking/"
183
 
 
184
  match = re.search(booking_pattern, user_message)
 
185
  if match:
186
  bestillingskode = match.group()
187
  post_data = {
@@ -190,21 +149,17 @@ async def handle_message(message: cl.Message):
190
  "booking_id": bestillingskode
191
  }
192
  }
193
-
194
  response = await post_tool.acall(
195
  json.dumps(post_data),
196
  callbacks=[cl.AsyncLangchainCallbackHandler()]
197
  )
198
-
199
- else:
200
- response = await llm_chain.ainvoke(
201
- user_message, # {"chat_history": "", "question": user_message}
202
- )
203
- await cl.Message(content=response).send()
204
 
205
- response_key = "output" if "output" in response else "text"
 
206
 
207
- await cl.Message(response.get(response_key, "")).send()
208
- return message.content
 
209
 
210
 
 
1
 
2
+ # ===========================================
3
+ # aha-----app.py
4
+ # ===========================================
5
+
 
 
 
 
 
6
  import asyncio
 
7
  import os
8
  import re
9
  import time
 
12
  import chainlit as cl
13
  from dotenv import load_dotenv
14
 
15
+ from langchain_community.tools.requests.tool import RequestsPostTool
16
+ from langchain_community.utilities.requests import TextRequestsWrapper
17
+
18
 
19
  from langchain import hub
20
  from langchain_openai import OpenAI
21
  from tiktoken import encoding_for_model
22
+ from langchain.chains import LLMChain, APIChain
23
  from langchain_core.prompts import PromptTemplate
 
 
 
 
24
  from langchain.memory.buffer import ConversationBufferMemory
25
  from langchain.memory import ConversationTokenBufferMemory
26
  from langchain.memory import ConversationSummaryMemory
27
 
28
  from api_docs import api_docs_str
 
29
  load_dotenv()
30
  OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
31
+ auth = os.environ.get("CHAINLIT_AUTH_SECRET")
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  daysoff_assistant_template = """
34
  #You are a customer support assistant (’kundeservice AI assistent’) for Daysoff.
35
  #By default, you respond in Norwegian language, using a warm, direct, and professional tone.
 
76
  )
77
 
78
 
79
+
80
  @cl.on_chat_start
81
  def setup_multiple_chains():
82
  llm = OpenAI(
 
100
  memory=conversation_memory,
101
  )
102
 
103
+ cl.user_session.set("llm_chain", llm_chain)
104
+
105
+ api_chain = APIChain.from_llm_and_api_docs(
106
+ llm=llm,
107
+ api_docs=api_docs_str,
108
+ api_url_prompt=api_url_prompt,
109
+ api_response_prompt=api_response_prompt,
110
+ verbose=True,
111
+ limit_to_domains=["http://0.0.0.0:7860/"]
112
+ )
113
+
114
+ cl.user_session.set("api_chain", api_chain)
115
+
116
  requests_wrapper = TextRequestsWrapper(
117
+ headers={
118
+ "Authorization": auth_token,
119
+ "Content-Type": "application/json"
120
  }
121
  )
122
+
123
+ post_tool = RequestsPostTool(
124
  requests_wrapper=requests_wrapper,
125
+ allow_dangerous_requests=True
 
 
 
126
  )
127
+
 
128
  cl.user_session.set("post_tool", post_tool)
129
+
130
 
131
  @cl.on_message
132
  async def handle_message(message: cl.Message):
133
  user_message = message.content
134
  llm_chain = cl.user_session.get("llm_chain")
135
+ api_chain = cl.user_session.get("api_chain")
136
  post_tool = cl.user_session.get("post_tool")
137
 
138
  booking_pattern = r'\b[A-Z]{6}\d{6}\b'
139
  endpoint_url = "https://aivisions.no/data/daysoff/api/v1/booking/"
140
 
141
+
142
  match = re.search(booking_pattern, user_message)
143
+
144
  if match:
145
  bestillingskode = match.group()
146
  post_data = {
 
149
  "booking_id": bestillingskode
150
  }
151
  }
152
+
153
  response = await post_tool.acall(
154
  json.dumps(post_data),
155
  callbacks=[cl.AsyncLangchainCallbackHandler()]
156
  )
 
 
 
 
 
 
157
 
158
+ else:
159
+ response = await llm_chain.ainvoke(user_message, callbacks=[cl.AsyncLangchainCallbackHandler()])
160
 
161
+ response_key = "output" if "output" in response else "text"
162
+ await cl.Message(response.get(response_key, "")).send()
163
+ return message.content
164
 
165