[email protected] commited on
Commit
5480e8d
·
1 Parent(s): 214b1f8

Add messages limitation

Browse files
Files changed (4) hide show
  1. apis/LangSmith.py +72 -0
  2. app.py +11 -0
  3. pages/chatbot.py +7 -1
  4. subscription/index.py +20 -0
apis/LangSmith.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import json
3
+ import os
4
+ from time import sleep
5
+ from dotenv import load_dotenv
6
+ from datetime import datetime
7
+
8
+
9
+ load_dotenv()
10
+
11
+ API_BASE_URL = "https://api.smith.langchain.com/api/v1"
12
+
13
+ class LangSmithAPI:
14
+
15
+ def __init__(self):
16
+ self.base_url = API_BASE_URL
17
+ self.headers = {
18
+ 'X-API-Key': os.environ.get("LANGCHAIN_API_KEY")
19
+ }
20
+
21
+ self.getSessionId()
22
+
23
+ def getSessionId(self):
24
+
25
+ payload = {}
26
+
27
+ response = requests.request("GET", f"{self.base_url}/sessions", headers=self.headers, data=payload)
28
+ response_json = response.json()
29
+
30
+ for session in response_json:
31
+ session_id = session.get('id', None)
32
+ name = session.get('name', 'Unnamed')
33
+ if( name == os.environ.get("LANGCHAIN_PROJECT") ):
34
+ self.session_id = session_id
35
+
36
+
37
+ def getLastTraces(self, id_request: str = ''):
38
+ payload = {
39
+ "session": [self.session_id],
40
+ "run_type":"chain",
41
+ "select": [
42
+ "id","trace_id","name","run_type","extra","start_time","inputs",
43
+ "total_tokens","prompt_tokens","completion_tokens",
44
+ "total_cost","prompt_cost","completion_cost","first_token_time"
45
+ ],
46
+ "order": "desc",
47
+ "limit": 100
48
+ }
49
+
50
+ # Make request
51
+ response = requests.request("POST", f"{self.base_url}/runs/query", headers=self.headers, data=json.dumps(payload))
52
+ response_json = response.json()
53
+
54
+ # filters for the traces that have the same id_request
55
+ # filtered_traces = [trace for trace in response_json['runs'] if 'extra' in trace and 'metadata' in trace['extra'] and 'id_request' in trace['extra']['metadata'] and trace['extra']['metadata']['id_request'] == id_request]
56
+ filtered_traces = [trace for trace in response_json['runs'] if trace.get('parent_run_ids') is not None and trace['parent_run_ids'] == []]
57
+
58
+ return filtered_traces
59
+
60
+
61
+ def getDailyMessages(self, id_request: str = ""):
62
+
63
+ trace = self.getLastTraces(id_request)
64
+
65
+ daily_counter = 0
66
+
67
+ for t in trace:
68
+ start_time = datetime.fromisoformat(t['start_time'])
69
+ if start_time.date() == datetime.today().date():
70
+ daily_counter += 1
71
+
72
+ return daily_counter
app.py CHANGED
@@ -5,6 +5,7 @@ from dotenv import load_dotenv
5
  from rag import Rag
6
  from vectore_store.PineconeConnector import PineconeConnector
7
  from vectore_store.VectoreStoreManager import VectoreStoreManager
 
8
 
9
  from util import getYamlConfig
10
 
@@ -49,6 +50,16 @@ def main():
49
 
50
  st.logo(LOGO)
51
  st.title(GROUP_NAME)
 
 
 
 
 
 
 
 
 
 
52
 
53
  saved_documents = st.Page("pages/persistent_documents.py", title="Communs", icon="🗃️")
54
  documents = st.Page("pages/documents.py", title="Vos documents", icon="📂")
 
5
  from rag import Rag
6
  from vectore_store.PineconeConnector import PineconeConnector
7
  from vectore_store.VectoreStoreManager import VectoreStoreManager
8
+ from subscription.index import get_usages, is_usage_limit_reached
9
 
10
  from util import getYamlConfig
11
 
 
50
 
51
  st.logo(LOGO)
52
  st.title(GROUP_NAME)
53
+
54
+ usages = get_usages()
55
+ reached = is_usage_limit_reached()
56
+
57
+ st.sidebar.html(f"<p style='margin:0;text-align:center;font-weight:bold;font-size:24px;'>{usages['count']} / {usages['daily_limit']}</p>")
58
+ if reached:
59
+ st.sidebar.html(f"<p style='text-align:center;font-style:italic;'>Vous avez atteint la limite d'utilisation<p>")
60
+ else:
61
+ st.sidebar.html(f"<p style='text-align:center;'>Nombre de messages envoyés aujourd'hui<p>")
62
+
63
 
64
  saved_documents = st.Page("pages/persistent_documents.py", title="Communs", icon="🗃️")
65
  documents = st.Page("pages/documents.py", title="Vos documents", icon="📂")
pages/chatbot.py CHANGED
@@ -4,6 +4,7 @@ from langchain.prompts import PromptTemplate
4
  from model import selector
5
  from util import getYamlConfig
6
  from st_copy_to_clipboard import st_copy_to_clipboard
 
7
 
8
  def display_messages():
9
 
@@ -123,8 +124,13 @@ def page():
123
  # Displaying messages
124
  display_messages()
125
 
 
 
 
 
 
 
126
 
127
- user_query = st.chat_input("")
128
  if user_query is not None and user_query != "":
129
 
130
  st.session_state["chat_history"].append(HumanMessage(content=user_query))
 
4
  from model import selector
5
  from util import getYamlConfig
6
  from st_copy_to_clipboard import st_copy_to_clipboard
7
+ from subscription.index import is_usage_limit_reached
8
 
9
  def display_messages():
10
 
 
124
  # Displaying messages
125
  display_messages()
126
 
127
+ reached = is_usage_limit_reached()
128
+ message = ""
129
+ if reached:
130
+ message = "Vous avez atteint la limite quotidienne de messages."
131
+
132
+ user_query = st.chat_input(message, disabled=reached)
133
 
 
134
  if user_query is not None and user_query != "":
135
 
136
  st.session_state["chat_history"].append(HumanMessage(content=user_query))
subscription/index.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from apis.LangSmith import LangSmithAPI
3
+ from dotenv import load_dotenv
4
+
5
+ load_dotenv()
6
+
7
+ langsmith = LangSmithAPI()
8
+ count = langsmith.getDailyMessages()
9
+
10
+ # Convert DAILY_LIMIT to int with a default value of 5
11
+ DAILY_LIMIT = int(os.getenv("DAILY_MESSAGES_LIMIT", "5"))
12
+
13
+ def is_usage_limit_reached():
14
+ return count >= DAILY_LIMIT
15
+
16
+ def get_usages():
17
+ return {
18
+ "count": count,
19
+ "daily_limit": DAILY_LIMIT
20
+ }