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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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
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