File size: 7,802 Bytes
d7762a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c8ff36
d7762a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
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="", 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