From 639ddae507c20cf21cf0069f7502968d6e175039 Mon Sep 17 00:00:00 2001 From: EduardoLoz12 Date: Sun, 19 May 2024 13:56:28 +0200 Subject: [PATCH] Push #2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ya está sincronizado el OpenIA con Whatsapp de acuerdo a una base de datos subida. --- app/services/openai_service.py | 122 +++++++++++++++++++++------------ app/services/threads_db.bak | 1 + app/services/threads_db.dat | Bin 0 -> 46 bytes app/services/threads_db.dir | 1 + app/utils/whatsapp_utils.py | 10 +-- start/assistants_quickstart.py | 33 +++++++-- threads_db.bak | 2 + threads_db.dat | Bin 0 -> 558 bytes threads_db.dir | 2 + 9 files changed, 115 insertions(+), 56 deletions(-) create mode 100644 app/services/threads_db.bak create mode 100644 app/services/threads_db.dat create mode 100644 app/services/threads_db.dir create mode 100644 threads_db.bak create mode 100644 threads_db.dat create mode 100644 threads_db.dir diff --git a/app/services/openai_service.py b/app/services/openai_service.py index 04f5829d..b250d00d 100644 --- a/app/services/openai_service.py +++ b/app/services/openai_service.py @@ -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) @@ -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 @@ -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") + diff --git a/app/services/threads_db.bak b/app/services/threads_db.bak new file mode 100644 index 00000000..ef912b1f --- /dev/null +++ b/app/services/threads_db.bak @@ -0,0 +1 @@ +'123', (0, 46) diff --git a/app/services/threads_db.dat b/app/services/threads_db.dat new file mode 100644 index 0000000000000000000000000000000000000000..5a86e40fbd8c0164fa5fe2589f43769d461192e2 GIT binary patch literal 46 wcmZo*nX1eH0X_018AYjyDe=JphQ^^4RcXndDfy*EMcyGP<=(DFrmj=;03TQl!vFvP literal 0 HcmV?d00001 diff --git a/app/services/threads_db.dir b/app/services/threads_db.dir new file mode 100644 index 00000000..ef912b1f --- /dev/null +++ b/app/services/threads_db.dir @@ -0,0 +1 @@ +'123', (0, 46) diff --git a/app/utils/whatsapp_utils.py b/app/utils/whatsapp_utils.py index a2691f95..0fc5d850 100644 --- a/app/utils/whatsapp_utils.py +++ b/app/utils/whatsapp_utils.py @@ -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): @@ -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) diff --git a/start/assistants_quickstart.py b/start/assistants_quickstart.py index 341ca714..b6cf5d8c 100644 --- a/start/assistants_quickstart.py +++ b/start/assistants_quickstart.py @@ -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]}}, +) # -------------------------------------------------------------- diff --git a/threads_db.bak b/threads_db.bak new file mode 100644 index 00000000..cc1e3648 --- /dev/null +++ b/threads_db.bak @@ -0,0 +1,2 @@ +'51976976825', (0, 46) +'123', (512, 46) diff --git a/threads_db.dat b/threads_db.dat new file mode 100644 index 0000000000000000000000000000000000000000..171b8206155c6e592452b38eb33c5033c7f820b7 GIT binary patch literal 558 zcmZo*nX1eH0X_018AYjyDe+zzVaDaoCh1O5Zlxx9F2Q-02F9Khevwo3pejeHVG{xk hSmM7tAU{3d$UVX{u+k*SGcBpGz|A8g!=-$R9spdX8zcY# literal 0 HcmV?d00001 diff --git a/threads_db.dir b/threads_db.dir new file mode 100644 index 00000000..cc1e3648 --- /dev/null +++ b/threads_db.dir @@ -0,0 +1,2 @@ +'51976976825', (0, 46) +'123', (512, 46)