HarshSanghavi commited on
Commit
f85379e
·
verified ·
1 Parent(s): 287750f

Update utils.py

Browse files
Files changed (1) hide show
  1. utils.py +119 -119
utils.py CHANGED
@@ -1,119 +1,119 @@
1
- import json
2
- import time
3
- from transformers import AutoTokenizer, AutoModel
4
- from langchain_community.chat_models import ChatOpenAI
5
- import pandas as pd
6
- from config import settings
7
- from langchain_core.utils.function_calling import convert_to_openai_function
8
- from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
9
- from langchain.memory import ConversationBufferWindowMemory
10
- from langchain.schema.runnable import RunnablePassthrough
11
- from langchain.agents.format_scratchpad import format_to_openai_functions
12
- from langchain.agents.output_parsers import OpenAIFunctionsAgentOutputParser
13
- from langchain.agents import AgentExecutor
14
-
15
- from tools import MEMORY, set_chatbot_name, close_chat, recommand_podcast,app_features,joke_teller,SESSION_ID
16
-
17
- from database_functions import get_chat_bot_name,get_chat_history, get_last_conversion, get_last_session, get_mood_data
18
-
19
-
20
- def get_mood_summary(user_id):
21
-
22
- data = get_mood_data(user_id)
23
- system_prompt = """You are an descripting assistant that provides the breif description of the user data which is related to their mood tracking activity. Properly descibe the reason for their mood.Avoid times and dates in description
24
- Here is the user data: {data}"""
25
-
26
- llm = ChatOpenAI(model=settings.OPENAI_MODEL,
27
- openai_api_key=settings.OPENAI_KEY, temperature=0.0)
28
-
29
- return llm.invoke(system_prompt.format(data=data)).content
30
-
31
-
32
- def deanonymizer(input, anonymizer):
33
- input = anonymizer.deanonymize(input)
34
- map = anonymizer.deanonymizer_mapping
35
- if map:
36
- for k in map["PERSON"]:
37
- names = k.split(" ")
38
- for i in names:
39
- input = input.replace(i, map["PERSON"][k])
40
- return input
41
-
42
-
43
-
44
- def get_last_session_summary(last_session_id, second_last_session_id):
45
-
46
- conversation = get_last_conversion(last_session_id,second_last_session_id)
47
- if conversation:
48
- system_prompt = """ context: there is one typical conversation going on between two high school gen z girls.
49
- you are one of the high school gen z girl. your voice is edgy and raw.
50
- must use I for AI named BMOXI and for human use my friend. in summary.
51
- this is your conversation with your best friend. summerize whole conversation and if you found any question can be asked from chat then return summary and qustion else return summary and append None at last.
52
- conversation: {conversation}
53
- summary:
54
- """
55
-
56
- llm = ChatOpenAI(model=settings.OPENAI_MODEL,
57
- openai_api_key=settings.OPENAI_KEY, temperature=0.0)
58
-
59
- response = llm.invoke(system_prompt.format(conversation=conversation)).content
60
- return response
61
- else:
62
- return ""
63
-
64
- def create_agent(user_id,is_first = False):
65
- # print("get user Id**********************",user_id)
66
-
67
- previous_session_id = get_last_session(user_id)
68
- # print(previous_session_id)
69
-
70
- tools = [set_chatbot_name,close_chat,recommand_podcast,app_features,joke_teller]
71
-
72
- functions = [convert_to_openai_function(f) for f in tools]
73
- model = ChatOpenAI(model_name=settings.OPENAI_MODEL,
74
- openai_api_key=settings.OPENAI_KEY, frequency_penalty= 1, temperature=0.7).bind(functions=functions)
75
-
76
- chat_bot_name = get_chat_bot_name(user_id)
77
-
78
- extra_prompt = ""
79
- previous_problem_summary = None
80
- if is_first:
81
- start = time.time()
82
- mood_summary = get_mood_summary(user_id)
83
- print(previous_session_id)
84
- if previous_session_id['second_last_session_id']:
85
- previous_problem_summary = get_last_session_summary(previous_session_id['last_session_id'], previous_session_id['second_last_session_id'])
86
-
87
- print("time require for mood summary: ",time.time()-start)
88
- if previous_problem_summary.find('None') == -1:
89
- extra_prompt = f"""ask user her previous problem is solved or not.use previous problem summary for framming the question. must include her name which is {user_id} .nothing else."""
90
- else:
91
- extra_prompt = f""" Only use these templates to start conversation:-
92
- 1. Hey again {user_id}! How's it going?
93
- 2. hey again {user_id}! What's up today? Need ✨ Advice, ✨ a Mood Boost, ✨ a Chat, ✨ Resource Suggestions, ✨ App Features help? How can I help?"
94
- use any one of the question for response based on your understanding not use anything else simply return one of these two only.
95
- """
96
-
97
-
98
- prompt = ChatPromptTemplate.from_messages([("system", settings.SYSTEM_PROMPT.format(name = chat_bot_name, mood="", previous_summary=previous_problem_summary)+extra_prompt),
99
- MessagesPlaceholder(variable_name="chat_history"), ("user", "{input}"),
100
- MessagesPlaceholder(variable_name="agent_scratchpad")])
101
-
102
-
103
-
104
- memory = ConversationBufferWindowMemory(memory_key="chat_history", chat_memory=get_chat_history(
105
- previous_session_id['last_session_id']), return_messages=True, k=5)
106
-
107
- # print("memory created")
108
- global MEMORY,SESSION_ID
109
- MEMORY = memory
110
- SESSION_ID = previous_session_id['last_session_id']
111
-
112
- chain = RunnablePassthrough.assign(agent_scratchpad=lambda x: format_to_openai_functions(x["intermediate_steps"])) | prompt | model | OpenAIFunctionsAgentOutputParser()
113
-
114
- agent_executor = AgentExecutor(
115
- agent=chain, tools=tools, memory=memory, verbose=True)
116
-
117
- return agent_executor
118
-
119
-
 
1
+ import json
2
+ import time
3
+ from transformers import AutoTokenizer, AutoModel
4
+ from langchain_community.chat_models import ChatOpenAI
5
+ import pandas as pd
6
+ from config import settings
7
+ from langchain_core.utils.function_calling import convert_to_openai_function
8
+ from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
9
+ from langchain.memory import ConversationBufferWindowMemory
10
+ from langchain.schema.runnable import RunnablePassthrough
11
+ from langchain.agents.format_scratchpad import format_to_openai_functions
12
+ from langchain.agents.output_parsers import OpenAIFunctionsAgentOutputParser
13
+ from langchain.agents import AgentExecutor
14
+
15
+ from tools import MEMORY, set_chatbot_name, close_chat, recommand_podcast,app_features,joke_teller,SESSION_ID
16
+
17
+ from database_functions import get_chat_bot_name,get_chat_history, get_last_conversion, get_last_session, get_mood_data
18
+
19
+
20
+ def get_mood_summary(user_id):
21
+
22
+ data = get_mood_data(user_id)
23
+ system_prompt = """You are an descripting assistant that provides the breif description of the user data which is related to their mood tracking activity. Properly descibe the reason for their mood.Avoid times and dates in description
24
+ Here is the user data: {data}"""
25
+
26
+ llm = ChatOpenAI(model=settings.OPENAI_MODEL,
27
+ openai_api_key=settings.OPENAI_KEY, temperature=0.0)
28
+
29
+ return llm.invoke(system_prompt.format(data=data)).content
30
+
31
+
32
+ def deanonymizer(input, anonymizer):
33
+ input = anonymizer.deanonymize(input)
34
+ map = anonymizer.deanonymizer_mapping
35
+ if map:
36
+ for k in map["PERSON"]:
37
+ names = k.split(" ")
38
+ for i in names:
39
+ input = input.replace(i, map["PERSON"][k])
40
+ return input
41
+
42
+
43
+
44
+ def get_last_session_summary(last_session_id, second_last_session_id):
45
+
46
+ conversation = get_last_conversion(last_session_id,second_last_session_id)
47
+ if conversation:
48
+ system_prompt = """ context: there is one typical conversation going on between two high school gen z girls.
49
+ you are one of the high school gen z girl. your voice is edgy and raw.
50
+ must use I for AI named BMOXI and for human use my friend. in summary.
51
+ this is your conversation with your best friend. summerize whole conversation and if you found any question can be asked from chat then return summary and qustion else return summary and append None at last.
52
+ conversation: {conversation}
53
+ summary:
54
+ """
55
+
56
+ llm = ChatOpenAI(model=settings.OPENAI_MODEL,
57
+ openai_api_key=settings.OPENAI_KEY, temperature=0.0)
58
+
59
+ response = llm.invoke(system_prompt.format(conversation=conversation)).content
60
+ return response
61
+ else:
62
+ return ""
63
+
64
+ def create_agent(user_id,is_first = False):
65
+ # print("get user Id**********************",user_id)
66
+
67
+ previous_session_id = get_last_session(user_id)
68
+ # print(previous_session_id)
69
+
70
+ tools = [set_chatbot_name,close_chat,recommand_podcast,app_features,joke_teller]
71
+
72
+ functions = [convert_to_openai_function(f) for f in tools]
73
+ model = ChatOpenAI(model_name=settings.OPENAI_MODEL,
74
+ openai_api_key=settings.OPENAI_KEY, frequency_penalty= 1, temperature=0.7).bind(functions=functions)
75
+
76
+ chat_bot_name = get_chat_bot_name(user_id)
77
+
78
+ extra_prompt = ""
79
+ previous_problem_summary = None
80
+ if is_first:
81
+ start = time.time()
82
+ mood_summary = get_mood_summary(user_id)
83
+ print(previous_session_id)
84
+ if previous_session_id['second_last_session_id']:
85
+ previous_problem_summary = get_last_session_summary(previous_session_id['last_session_id'], previous_session_id['second_last_session_id'])
86
+
87
+ print("time require for mood summary: ",time.time()-start)
88
+ if previous_problem_summary.find('None') == -1:
89
+ extra_prompt = f"""ask user her previous problem is solved or not.use previous problem summary for framming the question. must include her name which is {user_id} .nothing else."""
90
+ else:
91
+ extra_prompt = f""" Only use these templates to start conversation:-
92
+ 1. Hey again {user_id}! How's it going?
93
+ 2. hey again {user_id}! What's up today? Need ✨ Advice, ✨ a Mood Boost, ✨ a Chat, ✨ Resource Suggestions, ✨ App Features help? How can I help?"
94
+ use any one of the question for response based on your understanding not use anything else simply return one of these two only. also must include her name which is {userid}. nothing else.
95
+ """
96
+
97
+
98
+ prompt = ChatPromptTemplate.from_messages([("system", settings.SYSTEM_PROMPT.format(name = chat_bot_name, mood="", previous_summary=previous_problem_summary)+extra_prompt),
99
+ MessagesPlaceholder(variable_name="chat_history"), ("user", "{input}"),
100
+ MessagesPlaceholder(variable_name="agent_scratchpad")])
101
+
102
+
103
+
104
+ memory = ConversationBufferWindowMemory(memory_key="chat_history", chat_memory=get_chat_history(
105
+ previous_session_id['last_session_id']), return_messages=True, k=5)
106
+
107
+ # print("memory created")
108
+ global MEMORY,SESSION_ID
109
+ MEMORY = memory
110
+ SESSION_ID = previous_session_id['last_session_id']
111
+
112
+ chain = RunnablePassthrough.assign(agent_scratchpad=lambda x: format_to_openai_functions(x["intermediate_steps"])) | prompt | model | OpenAIFunctionsAgentOutputParser()
113
+
114
+ agent_executor = AgentExecutor(
115
+ agent=chain, tools=tools, memory=memory, verbose=True)
116
+
117
+ return agent_executor
118
+
119
+