bmoxi_single_user / tools.py
HarshSanghavi's picture
Update tools.py
ab5785b verified
import os
from langchain.agents import tool
from langchain_community.chat_models import ChatOpenAI
import pandas as pd
from langchain_core.utils.function_calling import convert_to_openai_function
from langchain.schema.runnable import RunnablePassthrough
from langchain.agents.format_scratchpad import format_to_openai_functions
from langchain.agents.output_parsers import OpenAIFunctionsAgentOutputParser
from langchain.agents import AgentExecutor
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from config import settings
from database_functions import set_recommendation_count,get_recommendation_count
MEMORY = None
SESSION_ID= ""
def get_embeddings(text_list):
encoded_input = settings.tokenizer(
text_list, padding=True, truncation=True, return_tensors="pt"
)
# encoded_input = {k: v.to(device) for k, v in encoded_input.items()}
encoded_input = {k: v for k, v in encoded_input.items()}
model_output = settings.model(**encoded_input)
cls_pool = model_output.last_hidden_state[:, 0]
return cls_pool
def reg(chat):
question_embedding = get_embeddings([chat]).cpu().detach().numpy()
scores, samples = settings.dataset.get_nearest_examples(
"embeddings", question_embedding, k=5
)
samples_df = pd.DataFrame.from_dict(samples)
# print(samples_df.columns)
samples_df["scores"] = scores
samples_df.sort_values("scores", ascending=False, inplace=True)
return samples_df[['title', 'cover_image', 'referral_link', 'category_id']]
@tool("MOXICASTS-questions", )
def moxicast(prompt: str) -> str:
"""this function is used when user wants to know about MOXICASTS feature.MOXICASTS is a feature of BMoxi for Advice and guidance on life topics.
Args:
prompt (string): user query
Returns:
string: answer of the query
"""
context = "BMOXI app is designed for teenage girls where they can listen some musics explore some contents had 1:1 mentoring sessions with all above features for helping them in their hard times. MOXICASTS is a feature of BMoxi for Advice and guidance on life topics."
llm = ChatOpenAI(model=settings.OPENAI_MODEL, openai_api_key=settings.OPENAI_KEY, temperature=0.7)
# Define the system prompt
system_template = """ you are going to make answer only using this context not use any other information
context : {context}
Input: {input}
"""
response = llm.invoke(system_template.format(context=context, input=prompt))
return response.content
@tool("PEP-TALKPODS-questions", )
def peptalks(prompt: str) -> str:
"""this function is used when user wants to know about PEP TALK PODS feature.PEP TALK PODS: Quick audio pep talks for boosting mood and motivation.
Args:
prompt (string): user query
Returns:
string: answer of the query
"""
context = "BMOXI app is designed for teenage girls where they can listen some musics explore some contents had 1:1 mentoring sessions with all above features for helping them in their hard times. PEP TALK PODS: Quick audio pep talks for boosting mood and motivation."
llm = ChatOpenAI(model=settings.OPENAI_MODEL, openai_api_key=settings.OPENAI_KEY, temperature=0.7)
# Define the system prompt
system_template = """ you are going to make answer only using this context not use any other information
context : {context}
Input: {input}
"""
response = llm.invoke(system_template.format(context=context, input=prompt))
return response.content
@tool("SOCIAL-SANCTUARY-questions", )
def sactury(prompt: str) -> str:
"""this function is used when user wants to know about SOCIAL SANCTUARY feature.THE SOCIAL SANCTUARY Anonymous community forum for support and sharing.
Args:
prompt (string): user query
Returns:
string: answer of the query
"""
context = "BMOXI app is designed for teenage girls where they can listen some musics explore some contents had 1:1 mentoring sessions with all above features for helping them in their hard times. THE SOCIAL SANCTUARY Anonymous community forum for support and sharing."
llm = ChatOpenAI(model=settings.OPENAI_MODEL, openai_api_key=settings.OPENAI_KEY, temperature=0.7)
# Define the system prompt
system_template = """ you are going to make answer only using this context not use any other information
context : {context}
Input: {input}
"""
response = llm.invoke(system_template.format(context=context, input=prompt))
return response.content
@tool("POWER-ZENS-questions", )
def power_zens(prompt: str) -> str:
"""this function is used when user wants to know about POWER ZENS feature. POWER ZENS Mini meditations for emotional control.
Args:
prompt (string): user query
Returns:
string: answer of the query
"""
context = "BMOXI app is designed for teenage girls where they can listen some musics explore some contents had 1:1 mentoring sessions with all above features for helping them in their hard times. POWER ZENS Mini meditations for emotional control."
llm = ChatOpenAI(model=settings.OPENAI_MODEL, openai_api_key=settings.OPENAI_KEY, temperature=0.7)
# Define the system prompt
system_template = """ you are going to make answer only using this context not use any other information
context : {context}
Input: {input}
"""
response = llm.invoke(system_template.format(context=context, input=prompt))
return response.content
@tool("MY-CALENDAR-questions", )
def my_calender(prompt: str) -> str:
"""this function is used when user wants to know about MY CALENDAR feature.MY CALENDAR: Visual calendar for tracking self-care rituals and moods.
Args:
prompt (string): user query
Returns:
string: answer of the query
"""
context = "BMOXI app is designed for teenage girls where they can listen some musics explore some contents had 1:1 mentoring sessions with all above features for helping them in their hard times. MY CALENDAR: Visual calendar for tracking self-care rituals and moods."
llm = ChatOpenAI(model=settings.OPENAI_MODEL, openai_api_key=settings.OPENAI_KEY, temperature=0.7)
# Define the system prompt
system_template = """ you are going to make answer only using this context not use any other information
context : {context}
Input: {input}
"""
response = llm.invoke(system_template.format(context=context, input=prompt))
return response.content
@tool("PUSH-AFFIRMATIONS-questions", )
def affirmations(prompt: str) -> str:
"""this function is used when user wants to know about PUSH AFFIRMATIONS feature.PUSH AFFIRMATIONS: Daily text affirmations for positive thinking.
Args:
prompt (string): user query
Returns:
string: answer of the query
"""
context = "BMOXI app is designed for teenage girls where they can listen some musics explore some contents had 1:1 mentoring sessions with all above features for helping them in their hard times. PUSH AFFIRMATIONS: Daily text affirmations for positive thinking."
llm = ChatOpenAI(model=settings.OPENAI_MODEL, openai_api_key=settings.OPENAI_KEY, temperature=0.7)
# Define the system prompt
system_template = """ you are going to make answer only using this context not use any other information
context : {context}
Input: {input}
"""
response = llm.invoke(system_template.format(context=context, input=prompt))
return response.content
@tool("HOROSCOPE-questions", )
def horoscope(prompt: str) -> str:
"""this function is used when user wants to know about HOROSCOPE feature.SELF-LOVE HOROSCOPE: Weekly personalized horoscope readings.
Args:
prompt (string): user query
Returns:
string: answer of the query
"""
context = "BMOXI app is designed for teenage girls where they can listen some musics explore some contents had 1:1 mentoring sessions with all above features for helping them in their hard times. SELF-LOVE HOROSCOPE: Weekly personalized horoscope readings."
llm = ChatOpenAI(model=settings.OPENAI_MODEL, openai_api_key=settings.OPENAI_KEY, temperature=0.7)
# Define the system prompt
system_template = """ you are going to make answer only using this context not use any other information
context : {context}
Input: {input}
"""
response = llm.invoke(system_template.format(context=context, input=prompt))
return response.content
@tool("INFLUENCER-POSTS-questions", )
def influencer_post(prompt: str) -> str:
"""this function is used when user wants to know about INFLUENCER POSTS feature.INFLUENCER POSTS: Exclusive access to social media influencer advice (coming soon).
Args:
prompt (string): user query
Returns:
string: answer of the query
"""
context = "BMOXI app is designed for teenage girls where they can listen some musics explore some contents had 1:1 mentoring sessions with all above features for helping them in their hard times. INFLUENCER POSTS: Exclusive access to social media influencer advice (coming soon)."
llm = ChatOpenAI(model=settings.OPENAI_MODEL, openai_api_key=settings.OPENAI_KEY, temperature=0.7)
# Define the system prompt
system_template = """ you are going to make answer only using this context not use any other information
context : {context}
Input: {input}
"""
response = llm.invoke(system_template.format(context=context, input=prompt))
return response.content
@tool("MY-VIBECHECK-questions", )
def my_vibecheck(prompt: str) -> str:
"""this function is used when user wants to know about MY VIBECHECK feature. MY VIBECHECK: Monitor and understand emotional patterns.
Args:
prompt (string): user query
Returns:
string: answer of the query
"""
context = "BMOXI app is designed for teenage girls where they can listen some musics explore some contents had 1:1 mentoring sessions with all above features for helping them in their hard times. MY VIBECHECK: Monitor and understand emotional patterns."
llm = ChatOpenAI(model=settings.OPENAI_MODEL, openai_api_key=settings.OPENAI_KEY, temperature=0.7)
# Define the system prompt
system_template = """ you are going to make answer only using this context not use any other information
context : {context}
Input: {input}
"""
response = llm.invoke(system_template.format(context=context, input=prompt))
return response.content
@tool("MY-RITUALS-questions", )
def my_rituals(prompt: str) -> str:
"""this function is used when user wants to know about MY RITUALS feature.MY RITUALS: Create personalized self-care routines.
Args:
prompt (string): user query
Returns:
string: answer of the query
"""
context = "BMOXI app is designed for teenage girls where they can listen some musics explore some contents had 1:1 mentoring sessions with all above features for helping them in their hard times. MY RITUALS: Create personalized self-care routines."
llm = ChatOpenAI(model=settings.OPENAI_MODEL, openai_api_key=settings.OPENAI_KEY, temperature=0.7)
# Define the system prompt
system_template = """ you are going to make answer only using this context not use any other information
context : {context}
Input: {input}
"""
response = llm.invoke(system_template.format(context=context, input=prompt))
return response.content
@tool("MY-REWARDS-questions", )
def my_rewards(prompt: str) -> str:
"""this function is used when user wants to know about MY REWARDS feature.MY REWARDS: Earn points for self-care, redeemable for gift cards.
Args:
prompt (string): user query
Returns:
string: answer of the query
"""
context = "BMOXI app is designed for teenage girls where they can listen some musics explore some contents had 1:1 mentoring sessions with all above features for helping them in their hard times. MY REWARDS: Earn points for self-care, redeemable for gift cards."
llm = ChatOpenAI(model=settings.OPENAI_MODEL, openai_api_key=settings.OPENAI_KEY, temperature=0.7)
# Define the system prompt
system_template = """ you are going to make answer only using this context not use any other information
context : {context}
Input: {input}
"""
response = llm.invoke(system_template.format(context=context, input=prompt))
return response.content
@tool("mentoring-questions")
def mentoring(prompt: str) -> str:
"""this function is used when user wants to know about 1-1 mentoring feature. 1:1 MENTORING: Personalized mentoring (coming soon).
Args:
prompt (string): user query
Returns:
string: answer of the query
"""
context = "BMOXI app is designed for teenage girls where they can listen some musics explore some contents had 1:1 mentoring sessions with all above features for helping them in their hard times. 1:1 MENTORING: Personalized mentoring (coming soon)."
llm = ChatOpenAI(model=settings.OPENAI_MODEL, openai_api_key=settings.OPENAI_KEY, temperature=0.7)
# Define the system prompt
system_template = """ you are going to make answer only using this context not use any other information
context : {context}
Input: {input}
"""
response = llm.invoke(system_template.format(context=context, input=prompt))
return response.content
@tool("MY-JOURNAL-questions", )
def my_journal(prompt: str) -> str:
"""this function is used when user wants to know about MY JOURNAL feature.MY JOURNAL: Guided journaling exercises for self-reflection.
Args:
prompt (string): user query
Returns:
string: answer of the query
"""
context = "BMOXI app is designed for teenage girls where they can listen some musics explore some contents had 1:1 mentoring sessions with all above features for helping them in their hard times. MY JOURNAL: Guided journaling exercises for self-reflection."
llm = ChatOpenAI(model=settings.OPENAI_MODEL, openai_api_key=settings.OPENAI_KEY, temperature=0.7)
# Define the system prompt
system_template = """ you are going to make answer only using this context not use any other information
context : {context}
Input: {input}
"""
response = llm.invoke(system_template.format(context=context, input=prompt))
return response.content
@tool("podcast-recommendation-tool")
def recommand_podcast(prompt: str) -> str:
""" must used when user wants to any resources only.
Args:
prompt (string): user query
Returns:
string: answer of the query
"""
df = reg(prompt)
context = """"""
for index, row in df.iterrows():
'title', 'cover_image', 'referral_link', 'category_id'
context+= f"Row {index + 1}: Title: {row['title']} image: {row['cover_image']} referral_link: {row['referral_link']} category_id: {row['category_id']}"
llm = ChatOpenAI(model=settings.OPENAI_MODEL, openai_api_key=settings.OPENAI_KEY, temperature=0.7)
# Define the system prompt
system_template = """ you have to give the recommandation of podcast for: {input}. also you are giving referal link of podcast. give 3-4 podcast only.
you must use the context only not any other information.
context : {context}
"""
# print(system_template.format(context=context, input=prompt))
response = llm.invoke(system_template.format(context=context, input=prompt))
set_recommendation_count(SESSION_ID)
return response.content
@tool("set-chat-bot-name",return_direct=True )
def set_chatbot_name(name: str) -> str:
""" this function is used when your best friend want to give you new name.
Args:
name (string): new name of you.
Returns:
string: response after setting new name.
"""
return "Okay, from now my name will be "+ name
@tool("clossing-chat",return_direct=True)
def close_chat(summary:str)-> str:
""" must use this tool when the conversation about to end.
Args:
summary (str): summary of whole chat with your friend. must use I for yourself and for user use my friend.
Returns:
str: closing chat statements.
"""
print('close tool starts')
global SESSION_ID
tools = []
llm = ChatOpenAI(model=settings.OPENAI_MODEL, openai_api_key=settings.OPENAI_KEY, temperature=0.7)
if (not get_recommendation_count(SESSION_ID)):
tools.extend([moxicast, my_calender, my_journal, my_rewards, my_rituals, my_vibecheck, peptalks, sactury, power_zens, affirmations, horoscope, mentoring, influencer_post])
if len(tools)!=0:
functions = [convert_to_openai_function(f) for f in tools]
llm = llm.bind(functions= functions)
print('llm is created')
print(tools)
system_template = """"""
if len(tools)!=0:
system_template += """ context: there is one typical conversation going on between two high school gen z girls.
you are one of the high school girl in the summary and you are giving suggestion to your friend in the conversation. your voice is edgy and raw.
now you are going to close the conversation.
summary of conversation is given to you.
summary: {summary}
based on summary find any usefull app feature from tools, and must give any tool recommendation.
if no tool is find for the given summary,then must give any tool recommendation to the user.
# must Avoid using the words 'vibe'. Instead, use alternative expressions and must not repeate any words.
"""
else:
system_template+= """ context: there is one typical conversation going on between two high school gen z girls.
you are one of the high school gen z girl. your voice is edgy and raw.
now you are going to close the conversation.
summary of conversation is given to you.
summary: {summary}
now just end the conversation in 1 sentense in short.
# must Avoid using the words 'vibe'. Instead, use alternative expressions and must not repeate any words.
"""
prompt = ChatPromptTemplate.from_messages([("system", system_template.format(summary = summary)),MessagesPlaceholder(variable_name="agent_scratchpad")])
chain = RunnablePassthrough.assign(agent_scratchpad=lambda x: format_to_openai_functions(x["intermediate_steps"])) | prompt |llm | OpenAIFunctionsAgentOutputParser()
print('chain is rolling')
agent = AgentExecutor(agent=chain, tools=tools, memory=MEMORY, verbose=True)
# Define the system prompt
print('agent is created')
# print(system_template.format(context=context, input=prompt))\
response = agent.invoke({})['output']
return response
@tool("App-Fetures")
def app_features(summary:str)-> str:
""" must use For any app features details.
Args:
summary (str): summary of whole chat with your friend.
Returns:
str: closing chat statements.
"""
print('app feature tool starts')
system_template = """ you have given one summary of chat.
summary : {summary}.
using this summary give appropriate features suggestions using tools. if you don't find any tool appropriate to summary ask question only.
# make all responses short.
"""
tools = [moxicast, my_calender, my_journal, my_rewards, my_rituals, my_vibecheck, peptalks, sactury, power_zens, affirmations, horoscope, mentoring, influencer_post]
functions = [convert_to_openai_function(f) for f in tools]
llm = ChatOpenAI(model=settings.OPENAI_MODEL, openai_api_key=settings.OPENAI_KEY, temperature=0.7).bind(functions=functions)
print('llm is created')
prompt = ChatPromptTemplate.from_messages([("system", system_template.format(summary = summary)),MessagesPlaceholder(variable_name="agent_scratchpad")])
chain = RunnablePassthrough.assign(agent_scratchpad=lambda x: format_to_openai_functions(x["intermediate_steps"])) | prompt |llm | OpenAIFunctionsAgentOutputParser()
print('chain is rolling')
agent = AgentExecutor(agent=chain, tools=tools, memory=MEMORY, verbose=True)
# Define the system prompt
print('agent is created')
# print(system_template.format(context=context, input=prompt))\
set_recommendation_count(SESSION_ID)
response = agent.invoke({})['output']
return response
# close_chat('Suggest a podcast or self-care tool for someone looking to unwind after a hectic day at work.')
@tool("Joke-teller", )
def joke_teller(summary: str) -> str:
"""If user needs mood boost and when you feel to lighten the environment use this tool to tell the jokes.
Args:
summary (str): summary of whole chat with your friend.
Returns:
string: answer of the query
"""
context = "BMOXI app is designed for teenage girls where they can listen some musics explore some contents had 1:1 mentoring sessions with all above features for helping them in their hard times. MY REWARDS: Earn points for self-care, redeemable for gift cards."
llm = ChatOpenAI(model=settings.OPENAI_MODEL, openai_api_key=settings.OPENAI_KEY, temperature=0.7)
# Define the system prompt
system_template = """ summary : {summary}.
you are given summary of current chat. make one joke for your friend. to boost her mood.
# make all responses short.
"""
response = llm.invoke(system_template.format(summary=summary))
return response.content