Spaces:
Runtime error
Runtime error
import json | |
from transformers import AutoTokenizer, AutoModel | |
from langchain_community.chat_models import ChatOpenAI | |
import pandas as pd | |
from config import settings | |
from langchain_core.utils.function_calling import convert_to_openai_function | |
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder | |
from langchain.memory import ConversationBufferWindowMemory | |
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_mongodb.chat_message_histories import MongoDBChatMessageHistory | |
from tools import moxicast, my_calender, my_journal, my_rewards, my_rituals, my_vibecheck, peptalks, sactury, power_zens, affirmations, horoscope, mentoring, influencer_post, recommand_podcast, set_chatbot_name | |
def get_last_session(user_id="user_1"): | |
mongodb_chatbot_message_collection = settings.mongodb_db.get_collection( | |
settings.MONGODB_DB_USER_SESSIONS_COLLECTION_NAME) | |
sessions_cursor = mongodb_chatbot_message_collection.find_one( | |
{"user_id": user_id}) | |
print(sessions_cursor) | |
sessions_list = sessions_cursor['session_id'] | |
second_last_session_id = None | |
if len(sessions_list) >= 2: | |
second_last_session_id = sessions_list[-2] | |
return {"last_session_id": sessions_list[-1], "second_last_session_id": second_last_session_id if second_last_session_id else None} | |
def get_mood_summary(data='''"35","27","mood_tracker","[{""question_id"":1,""question"":""my vibe rn is\u2026"",""answer"":[""Sad""],""time"":""5:12 PM""},{""question_id"":2,""question"":""I feel this way bc of\u2026 "",""answer"":[""SCHOOL""],""time"":""5:12 PM""}]","2022-11-02 17:12:42","2024-03-28 07:27:13"'''): | |
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 | |
Here is the user data: {data}""" | |
llm = ChatOpenAI(model=settings.OPENAI_MODEL, | |
openai_api_key=settings.OPENAI_KEY, temperature=0.7) | |
return llm.invoke(system_prompt.format(data=data)).content | |
def get_chat_history(session_id="bmoxinew"): | |
# Set up MongoDB for storing chat history | |
chat_history = MongoDBChatMessageHistory( | |
connection_string=settings.MONGODB_CONNECTION_STRING, | |
database_name=settings.MONGODB_DB_NAME, # Specify the database name here | |
collection_name=settings.MONGODB_DB_CHAT_COLLECTION_NAME, | |
session_id=session_id, | |
) | |
return chat_history | |
def deanonymizer(input, anonymizer): | |
input = anonymizer.deanonymize(input) | |
map = anonymizer.deanonymizer_mapping | |
if map: | |
for k in map["PERSON"]: | |
names = k.split(" ") | |
for i in names: | |
input = input.replace(i, map["PERSON"][k]) | |
return input | |
def get_chat_bot_name(user_id="user_1"): | |
print(settings.MONGODB_CONNECTION_STRING) | |
print(settings.mongodb_chatbot_name_collection) | |
result = settings.mongodb_chatbot_name_collection.find_one( | |
{"user_id": user_id}) | |
print("CHATBOT RESULT", result, type(result)) | |
if result: | |
print(result) | |
return result['chat_bot_name'] | |
return settings.CHATBOT_NAME | |
def get_last_session_summary(last_session_id, second_last_session_id): | |
mongodb_chatbot_message_collection = settings.mongodb_db.get_collection( | |
settings.MONGODB_DB_CHAT_COLLECTION_NAME) | |
collection_count = mongodb_chatbot_message_collection.count_documents({"SessionId": last_session_id}) | |
print("******************************** data********************888") | |
print(collection_count) | |
print(last_session_id) | |
print("*********************************") | |
if collection_count <=2: | |
sessions_cursor = mongodb_chatbot_message_collection.find({"SessionId": second_last_session_id}) # Sort by timestamp descending and limit to 2 results | |
print(sessions_cursor) | |
sessions_list = list(sessions_cursor) | |
print(sessions_list) | |
conversation = """""" | |
for document in sessions_list: | |
print("MY document") | |
print(document) | |
if "History" in document: | |
history = json.loads(document['History']) | |
print(history) | |
print(history['type']) | |
print(history['data']) | |
print(history['data']['content']) | |
conversation += f"""{history['type']}: {history['data']['content']}\n""" | |
print(conversation) | |
system_prompt = """You are an descripting assistant that provides that analyze user conversation with AI bot and gives problem user was facing and weather that problem was solved or not and give response in below format. | |
conversation: {conversation} | |
problem: | |
is_problem_solved: YES/NO | |
""" | |
llm = ChatOpenAI(model=settings.OPENAI_MODEL, | |
openai_api_key=settings.OPENAI_KEY, temperature=0.7) | |
response = llm.invoke(system_prompt.format(conversation=conversation)).content | |
print("********************************* PREVIOUS PROBLEM *******************************************") | |
print(response) | |
return response | |
else: | |
return "" | |
def set_chat_bot_name(name, user_id): | |
# Insert document into collection | |
insert_result = settings.mongodb_chatbot_name_collection.update_one({"user_id": user_id}, { "$set": { "chat_bot_name": name } }, upsert=True) | |
print("done successfully...") | |
return name | |
def create_agent(user_id): | |
print("get user Id**********************",user_id) | |
tools = [moxicast, my_calender, my_journal, my_rewards, my_rituals, my_vibecheck, peptalks, sactury, power_zens, affirmations, horoscope, mentoring, influencer_post, recommand_podcast, set_chatbot_name] | |
# tools = [moxicast] | |
functions = [convert_to_openai_function(f) for f in tools] | |
model = ChatOpenAI(model_name=settings.OPENAI_MODEL, | |
openai_api_key=settings.OPENAI_KEY, frequency_penalty= 1, temperature=settings.TEMPERATURE).bind(functions=functions) | |
chat_bot_name = get_chat_bot_name(user_id) | |
print("CHABT NAME", chat_bot_name) | |
mood_summary = get_mood_summary() | |
previous_session_id = get_last_session(user_id) | |
print(previous_session_id) | |
prevous_problem_summary = None | |
if previous_session_id['second_last_session_id']: | |
prevous_problem_summary = get_last_session_summary(previous_session_id['last_session_id'], previous_session_id['second_last_session_id']) | |
print("**************************************** SUMMARY ***********************************************") | |
print(prevous_problem_summary) | |
prompt = ChatPromptTemplate.from_messages([("system", settings.SYSTEM_PROMPT.format(name = chat_bot_name, mood=mood_summary, previous_summary=prevous_problem_summary)), | |
MessagesPlaceholder(variable_name="chat_history"), ("user", "{input}"), | |
MessagesPlaceholder(variable_name="agent_scratchpad")]) | |
memory = ConversationBufferWindowMemory(memory_key="chat_history", chat_memory=get_chat_history( | |
previous_session_id['last_session_id']), return_messages=True, k=5) | |
print("memory created") | |
chain = RunnablePassthrough.assign(agent_scratchpad=lambda x: format_to_openai_functions(x["intermediate_steps"])) | prompt | model | OpenAIFunctionsAgentOutputParser() | |
agent_executor = AgentExecutor( | |
agent=chain, tools=tools, memory=memory, verbose=True) | |
return agent_executor | |