Spaces:
Sleeping
Sleeping
Download app.py from mrmamon/chatwithme: direct link, hf CLI and curl.
- Browser
- Download file 8.14 kB
-
https://huggingface.co/spaces/mrmamon/chatwithme/resolve/main/app.py
- Command line
-
hf download hf://spaces/mrmamon/chatwithme/app.py
-
curl -L -o app.py https://huggingface.co/spaces/mrmamon/chatwithme/resolve/main/app.py
8.14 kB
| import pickle | |
| import gradio as gr | |
| from haystack import Pipeline, component | |
| from haystack.components.embedders import OpenAITextEmbedder, OpenAIDocumentEmbedder | |
| from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever | |
| from haystack.document_stores.in_memory import InMemoryDocumentStore | |
| from haystack.components.builders import PromptBuilder | |
| from haystack.components.generators import OpenAIGenerator | |
| from haystack.components.fetchers import LinkContentFetcher | |
| from haystack.components.converters import HTMLToDocument | |
| from haystack.components.preprocessors import DocumentSplitter | |
| from haystack.components.writers import DocumentWriter | |
| from haystack import Document | |
| from typing import List | |
| from datetime import datetime | |
| from google.cloud import firestore, storage | |
| from google.oauth2 import service_account | |
| import threading | |
| import uuid | |
| import json | |
| import pickle | |
| import os | |
| app_version = '2.2' | |
| document_store = InMemoryDocumentStore() | |
| with open('az_th.pkl', 'rb') as file: | |
| document_store = pickle.load(file) | |
| prompt = """ | |
| {% if previous_answer %} | |
| Context: | |
| {% for doc in documents %} | |
| {{ doc.content }} | |
| URL: {{ doc.meta['url'] }} | |
| {% endfor %} | |
| Previous Answer: | |
| {{ previous_answer }} | |
| Is this correct for the question: {{ query }}? | |
| Ensure: | |
| - Answer is accurate, solely based on the context. | |
| - Directly addresses the question. | |
| - Includes references to relevant URL(s). | |
| - Written in {{ language }}. | |
| - No external information included. | |
| **Instructions:** | |
| - If satisfied, write 'DONE' on a single line, then provide the final answer. | |
| - If not, revise your answer. | |
| - **No preambles or notes before your answer.** | |
| Answer: | |
| {% else %} | |
| Using the context, answer the question, referencing relevant URL(s). | |
| Your answer should be in {{ language }}. | |
| Ensure: | |
| - Accuracy based solely on the context. | |
| - Directly addresses the question: {{ query }}. | |
| - Includes references to relevant URL(s). | |
| - No external information. | |
| **Instructions:** | |
| - Provide your answer in the following format: | |
| ``` | |
| "Your answer here." | |
| URL(s): | |
| [URL 1] | |
| [URL 2] | |
| ``` | |
| - **Do not include preambles, justifications, or notes before your answer.** | |
| Context: | |
| {% for doc in documents %} | |
| {{ doc.content }} | |
| URL: {{ doc.meta['url'] }} | |
| {% endfor %} | |
| Question: {{ query }} | |
| Answer: | |
| {% endif %} | |
| """ | |
| class AnswerValidator: | |
| def run(self, replies: List[str]): | |
| if 'DONE' in replies[0]: | |
| final_answer = replies[0].replace('DONE', '').strip() | |
| return {"final_answer": final_answer,"log_answer": final_answer} | |
| else: | |
| print("Reflecting on the answer\n", replies[0]) | |
| return {"previous_answer": replies[0]} | |
| class FirestoreLogger: | |
| def __init__(self, collection_name='interaction_logs', bucket_name='chatwithme-35c9d.appspot.com'): | |
| service_account_info = json.loads(os.environ['chatwithme_services']) | |
| credentials = service_account.Credentials.from_service_account_info(service_account_info) | |
| self.client = firestore.Client(credentials=credentials, project=credentials.project_id) | |
| self.collection_name = collection_name | |
| self.storage_client = storage.Client(credentials=credentials, project=credentials.project_id) | |
| self.bucket_name = bucket_name | |
| self.bucket = self.storage_client.bucket(self.bucket_name) | |
| def run(self, query: str, replies: str, contexts: List[Document]): | |
| user_question = query | |
| rag_answer = replies | |
| log_id = str(uuid.uuid4()) | |
| log_data = { | |
| 'id': log_id, | |
| 'user_question': user_question, | |
| 'rag_answer': rag_answer, | |
| 'timestamp': datetime.utcnow(), | |
| 'app_version': app_version | |
| } | |
| self.log_to_firestore_and_upload(log_data, contexts) | |
| return {"log_status": log_id} | |
| def log_to_firestore_and_upload(self, log_data, contexts): | |
| try: | |
| doc_ref = self.client.collection(self.collection_name).document(log_data['id']) | |
| doc_ref.set(log_data) | |
| contexts_pickle = pickle.dumps(contexts) | |
| blob_path = f'contexts/{log_data["id"]}' | |
| blob = self.bucket.blob(blob_path) | |
| blob.upload_from_string(contexts_pickle, content_type='application/octet-stream') | |
| except Exception as e: | |
| print('Error logging to Firestore or uploading to Cloud Storage:', e) | |
| query_embedder = OpenAITextEmbedder(model='text-embedding-3-large') | |
| retriever = InMemoryEmbeddingRetriever(document_store=document_store) | |
| prompt_builder = PromptBuilder(template=prompt) | |
| generator = OpenAIGenerator(model="gpt-4o-mini") | |
| answers_validator = AnswerValidator() | |
| logger_node = FirestoreLogger(collection_name='interaction_logs',bucket_name='chatwithme-35c9d.appspot.com') | |
| rag = Pipeline() | |
| rag.add_component("query_embedder", query_embedder) | |
| rag.add_component("retriever", retriever) | |
| rag.add_component("prompt", prompt_builder) | |
| rag.add_component("answers_validator",answers_validator) | |
| rag.add_component("generator", generator) | |
| rag.add_component("logger", logger_node) | |
| rag.connect("query_embedder.embedding", "retriever.query_embedding") | |
| rag.connect("retriever.documents", "prompt.documents") | |
| rag.connect("retriever.documents", "logger.contexts") | |
| rag.connect("prompt.prompt", "generator.prompt") | |
| rag.connect("generator.replies", "answers_validator.replies") | |
| rag.connect("answers_validator.previous_answer", "prompt.previous_answer") | |
| rag.connect("answers_validator.log_answer", "logger.replies") | |
| service_account_info = json.loads(os.environ['chatwithme_services']) | |
| credentials = service_account.Credentials.from_service_account_info(service_account_info) | |
| firestore_client = firestore.Client(credentials=credentials, project=credentials.project_id) | |
| def log_like_data(log_data): | |
| try: | |
| collection_name = 'likes_logs' | |
| doc_ref = firestore_client.collection(collection_name).document() | |
| doc_ref.set(log_data) | |
| print(f"Logged like data: {log_data}") | |
| except Exception as e: | |
| print('Error logging like data to Firestore:', e) | |
| def respond(user_message, chat_history, log_id_mapping): | |
| if log_id_mapping is None: | |
| log_id_mapping = {} | |
| result = rag.run( | |
| { | |
| "query_embedder": {"text": user_message}, | |
| "retriever": {"top_k": 5}, | |
| "prompt": {"query": user_message, "language": "Thai"}, | |
| "logger": {"query": user_message}, | |
| } | |
| ) | |
| final_answer = result['answers_validator']['final_answer'] | |
| log_id = result['logger']['log_status'] | |
| log_id_mapping[final_answer] = log_id | |
| chat_history.append((user_message, final_answer)) | |
| # Return the updated chat history, log_id_mapping, and an empty string to clear the Textbox | |
| return chat_history, log_id_mapping, '' | |
| def vote(data: gr.LikeData, log_id_mapping): | |
| bot_response = data.value | |
| log_id = log_id_mapping.get(bot_response) | |
| log_data = { | |
| 'response': bot_response, | |
| 'liked': data.liked, | |
| 'timestamp': datetime.utcnow(), | |
| 'app_version': app_version, | |
| 'log_id': log_id | |
| } | |
| threading.Thread(target=log_like_data, args=(log_data,)).start() | |
| with gr.Blocks() as demo: | |
| log_id_mapping = gr.State({}) | |
| title = gr.Label("คุยกับ AZ Bot 🤖!",container=False) | |
| chatbot = gr.Chatbot(label="Chat with AZ Bot") | |
| msg = gr.Textbox(placeholder="ถามเรื่อง AZ มาเลย!", label="Chat with AZ Bot") | |
| send_button = gr.Button("Send") | |
| send_button.click( | |
| respond, | |
| inputs=[msg, chatbot, log_id_mapping], | |
| outputs=[chatbot, log_id_mapping, msg], | |
| ) | |
| msg.submit( | |
| respond, | |
| inputs=[msg, chatbot, log_id_mapping], | |
| outputs=[chatbot, log_id_mapping, msg], | |
| ) | |
| chatbot.like(vote, inputs=[log_id_mapping], outputs=[]) | |
| demo.launch() |