Skip to content

Commit

Permalink
uso do firestore
Browse files Browse the repository at this point in the history
  • Loading branch information
luisleao committed Mar 24, 2024
1 parent f58c5bc commit 961c48c
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 9 deletions.
22 changes: 13 additions & 9 deletions app/agent/lex_chatgpt.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import os
from flask import session

from ..app import firestoreClient

#LLM
from langchain_community.llms import OpenAI
Expand All @@ -26,33 +27,36 @@
#Define o LLM
llm = ChatOpenAI(model_name="gpt-3.5-turbo")



promptDoc = firestoreClient.collection(
"settings_prompts"
).document("default").get()

if promptDoc.exists():
prompt = promptDoc.to_dict()['prompt']

prompt = ChatPromptTemplate.from_messages([
SystemMessage(content=SYS_PROMPT), # The persistent system prompt
SystemMessage(content=prompt), #SYS_PROMPT), # The persistent system prompt
MessagesPlaceholder(variable_name="history"), # Where the memory will be stored.
HumanMessagePromptTemplate.from_template("{human_input}"), # Where the human input will injected
])


# TODO: use different memory_key for each session

import firebase_admin
from firebase_admin import credentials, firestore
script_dir = os.path.dirname(os.path.abspath(__file__))
cred = credentials.Certificate(f"{script_dir}/../keys/politicalai-lex.json")
app = firebase_admin.initialize_app(cred)
client = firestore.client(app=app)

message_history = FirestoreChatMessageHistory(
collection_name="lex-history",
session_id="default",
user_id="no-user-defined",
firestore_client=client,
firestore_client=firestoreClient,
)



# memory = ConversationBufferMemory(memory_key=f"chat_history", chat_memory=message_history, return_messages=True)
memory = ConversationBufferMemory(chat_memory=message_history, return_messages=True)
# memory.chat_memory = message_history

print(f"MESSAGES: {memory}")
## memory = ConversationBufferMemory(memory_key=f"chat_history", return_messages=True)
Expand Down
30 changes: 30 additions & 0 deletions app/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,16 @@
import hashlib


# carregar Firestore

import firebase_admin
from firebase_admin import credentials, firestore
script_dir = os.path.dirname(os.path.abspath(__file__))
cred = credentials.Certificate(f"{script_dir}/keys/politicalai-lex.json")
app = firebase_admin.initialize_app(cred)
firestoreClient = firestore.client(app=app)


# # Carregando agentes
# loaded_agents = {}
# for agent in ACTIVE_AGENTS:
Expand Down Expand Up @@ -74,6 +84,22 @@ def sms_reply():
whatsapp_number = request.form.get('From').split("whatsapp:")[-1]
hashnumber = hashlib.md5(whatsapp_number.encode()).hexdigest();

# TODO: salvar profileName do usuário no banco
# TODO: salvar lastMessage como timestamp do usuário
# TODO: incrementar total de mensagens

# TODO: usar firestoreClient para consulta
# TODO: consultar Firestore com o hashnumber do usuário
# TODO: verificar se usuário não está com `banned`
# TODO: se estiver como banned finalizar função e não responde nada

# TODO: carregar limite do usuário ou usar `default`
# TODO: verificar se usuário ultrapassou limite diario ou total ou se é ilimitado
# TODO: caso tenha ultrapassado ele retorna mensagem padrão
# TODO: caso não tenha ultrapassado limite diario ou total continua



print()
print()
print(f"WhatsApp {whatsapp_number}")
Expand Down Expand Up @@ -109,6 +135,8 @@ def sms_reply():
message_history.prepare_firestore() # Precisa disso para recarregar os dados com o ID novo
bot_response = current_agent.run(human_input=message_body) #, session_id=request.form['From'])
messages_to_send = split_message_by_line(bot_response)

# TODO: salvar no banco o consumo de token diário e total

for msg in messages_to_send:
resp.message(msg)
Expand Down Expand Up @@ -221,6 +249,8 @@ def async_transcribe_and_reply(media_url, current_agent, user_number, bot_number
bot_response = current_agent.run(human_input=message_body)
messages_to_send = split_message_by_line(bot_response)

# TODO: salvar no banco o consumo de token diário e total

for msg in messages_to_send:
twilio_client.messages.create(
body=msg,
Expand Down

0 comments on commit 961c48c

Please sign in to comment.