Deployed Repl randomly starts running in console

Question:

I have a deployed Repl, which means I shouldn’t need to run the app in the console. However, when I ‘stop’ it from running and then use my application (the app is a background worker that sends a webhook to Twilio when a text message is received at a particular number) by sending a text, I notice that it starts booting up again in the console. Ultimately it wont work unless its running in the console, but I thought that wasnt necessary if its deployed

Repl link/Link to where the bug appears:

https://replit.com/@JasonTange/TheGame-message-2

Screenshots, links, or other helpful context:

# Import libraries
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
import os
import sqlite3
from langchain.vectorstores import FAISS
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.chains import RetrievalQAWithSourcesChain
from langchain.chat_models import ChatOpenAI
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory
from langchain.chains.question_answering import load_qa_chain
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
from langchain.memory import ConversationBufferMemory
from langchain.chains import RetrievalQA
from transformers import AutoTokenizer, AutoModel
import requests

HUBSPOT_TOKEN = ""

def get_contact_by_phone(phone_number):
    url = "https://api.hubapi.com/crm/v3/objects/contacts/search"
    payload = {
        "filterGroups": [{
            "filters": [{
                "propertyName": "mobilephone",
                "operator": "EQ",
                "value": phone_number
            }]
        }],
        "properties": ["mobilephone", "message_history"],
        "limit": 1
    }
    headers = {
        'accept': "application/json",
        'content-type': "application/json",
        'authorization': f"Bearer {HUBSPOT_TOKEN}"
    }
    response = requests.post(url, json=payload, headers=headers)
    return response.json()

def update_contact_messages(contact_id, message_count, message_history):
    url = f"https://api.hubapi.com/crm/v3/objects/contacts/{contact_id}"
    payload = {
        "properties": {
            "of_messages": str(message_count),
            "message_history": message_history  # Add this line
        }
    }
    headers = {
        'accept': "application/json",
        'content-type': "application/json",
        'authorization': f"Bearer {HUBSPOT_TOKEN}"
    }
    response = requests.patch(url, json=payload, headers=headers)
    return response.json()

def create_contact(phone_number, message_history):
    url = "https://api.hubapi.com/crm/v3/objects/contacts"
    payload = {
        "properties": {
            "firstname": phone_number,
            "mobilephone": phone_number,
            "message_history": message_history  # Add this line
        }
    }
    headers = {
        'accept': "application/json",
        'content-type': "application/json",
        'authorization': f"Bearer {HUBSPOT_TOKEN}"
    }
    response = requests.post(url, json=payload, headers=headers)
    return response.json()

# Initialize SQLite Database
def init_db():
    with sqlite3.connect('message_counts.db') as conn:
        cursor = conn.cursor()
        cursor.execute('''
        CREATE TABLE IF NOT EXISTS message_counts (
            phone_number TEXT PRIMARY KEY,
            count INTEGER DEFAULT 0
        );
        ''')
        conn.commit()

init_db()

# Set OpenAI API Key
os.environ["OPENAI_API_KEY"] = ""

# Load Sentence Transformer model
model_name = "intfloat/e5-base-v2"
embeddings = HuggingFaceEmbeddings(model_name=model_name)

# Load tokenizer and model
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name)

# Load FAISS index
persist_directory = 'thegame'
VectorStore = FAISS.load_local(persist_directory, embeddings)

# Initialize language model
llm = ChatOpenAI(temperature=0.7, model_name='gpt-3.5-turbo')

template = """You are just like the character 'Hank Moody' in the show 'Californication'

{context}

Also, here are previous text messages: {chat_history}
Human: {human_input}
Chatbot:"""

prompt = PromptTemplate(
    input_variables=["chat_history", "human_input", "context"], template=template
)
memory = ConversationBufferMemory(memory_key="chat_history", input_key="human_input")
chain = load_qa_chain(
    llm=llm, chain_type="stuff", memory=memory, prompt=prompt
)

# Create Flask app instance
app = Flask(__name__)

@app.route('/api', methods=['POST'])
def api_endpoint():
    sender_phone_number = request.form.get('From')
    user_query = request.form.get('Body')

    with sqlite3.connect('message_counts.db') as conn:
        cursor = conn.cursor()
        cursor.execute("SELECT count FROM message_counts WHERE phone_number=?", (sender_phone_number,))
        row = cursor.fetchone()

        if row:
            current_count = row[0]
        else:
            current_count = 0

        if current_count >= 300:
            resp = MessagingResponse()
            resp.message("You have reached the maximum message limit. Please wait for some time.")
            return str(resp)

        if row:
            cursor.execute("UPDATE message_counts SET count = count + 1 WHERE phone_number=?", (sender_phone_number,))
        else:
            cursor.execute("INSERT INTO message_counts (phone_number, count) VALUES (?, 1)", (sender_phone_number,))

        conn.commit()

    if not user_query:
        return "User query is missing or empty!", 400

    docs = VectorStore.similarity_search(user_query, k=5)
    sources = [doc.metadata.get('source') for doc in docs]
    ans = chain({"input_documents": docs, "human_input": user_query}, return_only_outputs=True)

    contacts = get_contact_by_phone(sender_phone_number)

    # Initialize current_history with empty string
    current_history = ""

    if contacts.get('results'):
        contact = contacts['results'][0]
        properties = contact.get('properties', {})
        contact_id = contact.get('id')

        # Extract current history, if it exists
        message_history = properties.get('message_history') if properties else None
        if isinstance(message_history, dict):
            current_history = message_history.get('value', '')
    else:
        current_history = ""

    current_history += f"\nHuman: {user_query}\nChatbot: {ans['output_text']}"

    if contacts.get('results'):
        update_contact_messages(contact_id, current_count + 1, current_history)
    else:
        create_contact(sender_phone_number, current_history)

    resp = MessagingResponse()
    resp.message(ans['output_text'])
    return str(resp)

@app.route('/', methods=['GET'])
def root_endpoint():
    return "Welcome to the root endpoint!"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)

also more info - i’m currently using ‘Reserved VM’
(Dedicated 2 vCPU / 8 GiB RAM)

also from the logs it says: "
Disk usage in deployment machine is too high. Check the troubleshooting guide at https://docs.replit.com/hosting/deployments/troubleshooting. pct=91.38888693530754"

image

You should remove your Hub token from the image and change it.
(not sure about the issue sorry)

1 Like

thank you for the heads up!

Hey @JasonTange!

How are you accessing your Repl when you see that it starts booting up? What URL are you going to to view the output of your deployment?

1 Like

thanks @ShaneAtReplit - I set up this endpoint (https://thegame-message-3-openai.jasontange.repl.co/api) in Twilio so that when a user sends a text message to the Twilio phone number, the code processes that message through gpt and then sends a response

1 Like

your repl.co url links to the console repl, not the deployed version. You need a link that ends with replit.app as replit.app refers to deployed repls.

2 Likes

Did you remove your API key there before posting?

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.