Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Ya está sincronizado el OpenIA con Whatsapp de acuerdo a una base de datos subida.
  • Loading branch information
EduardoLoz12 committed May 19, 2024
1 parent c9bcca9 commit 639ddae
Show file tree
Hide file tree
Showing 9 changed files with 115 additions and 56 deletions.
122 changes: 77 additions & 45 deletions app/services/openai_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,29 +10,37 @@
OPENAI_ASSISTANT_ID = os.getenv("OPENAI_ASSISTANT_ID")
client = OpenAI(api_key=OPENAI_API_KEY)

# assistant = client.beta.assistants.create(
# name="Carmesi AssistantAuto",
# instructions="You're a helpful WhatsApp assistant that can assist guests that buying products in Carmesi Store. Use your knowledge base to best respond to customer queries. If you don't know the answer, say simply that you cannot help with question and advice to contact the host directly. Be friendly and funny.",
# model="gpt-4o",
# tools=[{"type": "file_search"}],
# )
#
# # Create a vector store caled "Financial Statements"
# vector_store = client.beta.vector_stores.create(name="Carmesi DatabaseAuto")
#
# # Ready the files for upload to OpenAI
# file_paths = [r"C:\Users\E.Lozada\OneDrive\Documentos\GitHub\python-whatsapp-bot\data\airbnb-faq.pdf"]
# file_streams = [open(path, "rb") for path in file_paths]
#
# # Use the upload and poll SDK helper to upload the files, add them to the vector store,
# # and poll the status of the file batch for completion.
# file_batch = client.beta.vector_stores.file_batches.upload_and_poll(
# vector_store_id=vector_store.id, files=file_streams
# )
#
# # You can print the status and the file counts of the batch to see the result of this operation.
# print(file_batch.status)
# print(file_batch.file_counts)
#
# assistant = client.beta.assistants.update(
# assistant_id=assistant.id,
# tool_resources={"file_search": {"vector_store_ids": [vector_store.id]}},
# )

def upload_file(path):
# Upload a file with an "assistants" purpose
file = client.files.create(
file=open("../../data/airbnb-faq.pdf", "rb"), purpose="assistants"
)


def create_assistant(file):
"""
You currently cannot set the temperature for Assistant via the API.
"""
assistant = client.beta.assistants.create(
name="WhatsApp AirBnb Assistant",
instructions="You're a helpful WhatsApp assistant that can assist guests that are staying in our Paris AirBnb. Use your knowledge base to best respond to customer queries. If you don't know the answer, say simply that you cannot help with question and advice to contact the host directly. Be friendly and funny.",
tools=[{"type": "retrieval"}],
model="gpt-4-1106-preview",
file_ids=[file.id],
)
return assistant


# Use context manager to ensure the shelf file is closed properly
def check_if_thread_exists(wa_id):
with shelve.open("threads_db") as threads_shelf:
return threads_shelf.get(wa_id, None)
Expand All @@ -42,31 +50,9 @@ def store_thread(wa_id, thread_id):
with shelve.open("threads_db", writeback=True) as threads_shelf:
threads_shelf[wa_id] = thread_id


def run_assistant(thread, name):
# Retrieve the Assistant
assistant = client.beta.assistants.retrieve(OPENAI_ASSISTANT_ID)

# Run the assistant
run = client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant.id,
# instructions=f"You are having a conversation with {name}",
)

# Wait for completion
# https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps#:~:text=under%20failed_at.-,Polling%20for%20updates,-In%20order%20to
while run.status != "completed":
# Be nice to the API
time.sleep(0.5)
run = client.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id)

# Retrieve the Messages
messages = client.beta.threads.messages.list(thread_id=thread.id)
new_message = messages.data[0].content[0].text.value
logging.info(f"Generated message: {new_message}")
return new_message

# --------------------------------------------------------------
# Generate response
# --------------------------------------------------------------

def generate_response(message_body, wa_id, name):
# Check if there is already a thread_id for the wa_id
Expand Down Expand Up @@ -95,3 +81,49 @@ def generate_response(message_body, wa_id, name):
new_message = run_assistant(thread, name)

return new_message

# --------------------------------------------------------------
# Run assistant
# --------------------------------------------------------------

def run_assistant(thread, name):
# Retrieve the Assistant
assistant = client.beta.assistants.retrieve(OPENAI_ASSISTANT_ID)

# Run the assistant
run = client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant.id,
instructions=f"You are having a conversation with {name}",
)

# Wait for completion
# https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps#:~:text=under%20failed_at.-,Polling%20for%20updates,-In%20order%20to
while run.status != "completed":
# Be nice to the API
time.sleep(0.5)
run = client.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id)

# Retrieve the Messages
messages = list(client.beta.threads.messages.list(thread_id=thread.id, run_id=run.id))

message_content = messages[0].content[0].text
annotations = message_content.annotations
citations = []
for index, annotation in enumerate(annotations):
message_content.value = message_content.value.replace(annotation.text, f"[{index}]")
if file_citation := getattr(annotation, "file_citation", None):
cited_file = client.files.retrieve(file_citation.file_id)
citations.append(f"[{index}] {cited_file.filename}")

message_content = message_content.value

print(message_content)
return message_content

# --------------------------------------------------------------
# Test assistant
# --------------------------------------------------------------

#new_message = generate_response("direction?", "123", "John")

1 change: 1 addition & 0 deletions app/services/threads_db.bak
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
'123', (0, 46)
Binary file added app/services/threads_db.dat
Binary file not shown.
1 change: 1 addition & 0 deletions app/services/threads_db.dir
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
'123', (0, 46)
10 changes: 5 additions & 5 deletions app/utils/whatsapp_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ def get_text_message_input(recipient, text):
)


def generate_response(response):
#def generate_response(response):
# Return text in uppercase
return response.upper()
# return response.upper()


def send_message(data):
Expand Down Expand Up @@ -82,11 +82,11 @@ def process_whatsapp_message(body):
message_body = message["text"]["body"]

# TODO: implement custom function here
response = generate_response(message_body)
#response = generate_response(message_body)

# OpenAI Integration
#response = generate_response(message_body, wa_id, name)
#response = process_text_for_whatsapp(response)
response = generate_response(message_body, wa_id, name)
response = process_text_for_whatsapp(response)

data = get_text_message_input(current_app.config["RECIPIENT_WAID"], response)
send_message(data)
Expand Down
33 changes: 27 additions & 6 deletions start/assistants_quickstart.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,42 @@ def upload_file(path):
# --------------------------------------------------------------
# Create assistant
# --------------------------------------------------------------
def create_assistant(file):
def create_assistant():
"""
You currently cannot set the temperature for Assistant via the API.
"""
assistant = client.beta.assistants.create(
name="WhatsApp Carmesi Assistant",
instructions="You're a helpful WhatsApp assistant that can assist guests that are staying in our Paris AirBnb. Use your knowledge base to best respond to customer queries. If you don't know the answer, say simply that you cannot help with question and advice to contact the host directly. Be friendly and funny.",
tools=[{"type": "retrieval"}],
model="gpt-4-1106-preview",
file_ids=[file.id],
instructions="You're a helpful WhatsApp assistant that can assist guests that wants to buy something from Carmesi Store. Use your knowledge base to best respond to customer queries. If you don't know the answer, say simply that you cannot help with question and advice to contact the host directly. Be friendly and funny.",
tools=[{"type": "file_search"}],
model="gpt-4o",
)
return assistant

assistant = create_assistant()

assistant = create_assistant(file)

# Create a vector store caled "Financial Statements"
vector_store = client.beta.vector_stores.create(name="CarmesiDB")

# Ready the files for upload to OpenAI
file_paths = ["airbnb-faq.pdf"]
file_streams = [open(path, "rb") for path in file_paths]

# Use the upload and poll SDK helper to upload the files, add them to the vector store,
# and poll the status of the file batch for completion.
file_batch = client.beta.vector_stores.file_batches.upload_and_poll(
vector_store_id=vector_store.id, files=file_streams
)

# You can print the status and the file counts of the batch to see the result of this operation.
print(file_batch.status)
print(file_batch.file_counts)

assistant = client.beta.assistants.update(
assistant_id=assistant.id,
tool_resources={"file_search": {"vector_store_ids": [vector_store.id]}},
)


# --------------------------------------------------------------
Expand Down
2 changes: 2 additions & 0 deletions threads_db.bak
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
'51976976825', (0, 46)
'123', (512, 46)
Binary file added threads_db.dat
Binary file not shown.
2 changes: 2 additions & 0 deletions threads_db.dir
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
'51976976825', (0, 46)
'123', (512, 46)

0 comments on commit 639ddae

Please sign in to comment.