Spaces:
Runtime error
Runtime error
Download app.py from Resaofd/resao-chat: direct link, hf CLI and curl.
- Browser
- Download file 13.6 kB
-
https://huggingface.co/spaces/Resaofd/resao-chat/resolve/main/app.py
- Command line
-
hf download hf://spaces/Resaofd/resao-chat/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Resaofd/resao-chat/resolve/main/app.py
13.6 kB
| from fastapi import FastAPI, HTTPException | |
| from pydantic import BaseModel | |
| import re | |
| import asyncio | |
| import os | |
| from langchain_core.messages import AIMessage | |
| # from langchain_community.document_loaders import TextLoader | |
| # from langchain.text_splitter import RecursiveCharacterTextSplitter | |
| from utils.config import Config | |
| from utils.prompt import Prompt | |
| from utils.loader import load_documents | |
| from utils.model import initialize_models | |
| from utils.retriever import RetrievalSystem | |
| from utils.retriever_1 import create_retrieval_system | |
| from langchain_core.prompts import ChatPromptTemplate | |
| from utils.utils import create_session, get_session, add_to_history, invoke_with_retry, get_priority_value, invoke_with_retry_payment | |
| # FastAPI instance | |
| app = FastAPI() | |
| # Charger l'historique existant | |
| from utils.utils import load_history | |
| import os | |
| # load_history() | |
| # Initialisation globale | |
| # os.environ['HF_TOKEN'] = Config.HF_TOKEN | |
| os.environ['HF_TOKEN'] = os.getenv("HF_TOKEN") | |
| # documents = load_documents(Config.DATA_PATH) | |
| # loader = TextLoader("E:\work\Vocal-Telma\TMSpeechTextML\chat\contexte-offre\offre.txt") | |
| # print(loader) | |
| # docs = loader.load() | |
| # print(docs) | |
| # # Split text into chunks | |
| # text_splitter = RecursiveCharacterTextSplitter() | |
| # documents = text_splitter.split_documents(docs) | |
| # print(documents) | |
| llm, embeddings = initialize_models(Config.MISTRAL_API_KEY) | |
| # llm, embeddings = initialize_models(os.getenv("MISTRAL_API_KEY")) | |
| # Prompt template | |
| # prompt_template = ChatPromptTemplate.from_template("""Answer the following question based only on the provided context: | |
| # <context> | |
| # {context} | |
| # </context> | |
| # Question: {input} | |
| # Choose one of these case scenarios to answer the question: | |
| # Case 1: Greeting Only | |
| # If the user's input is a greeting (e.g., "hello", "hi", "bonjour", "salama", "hola", "ciao", "namaste", "as-salamu alaykum", or similar expressions in any language) and does not mention any product, offer, or specific subject, respond with this JSON structure: | |
| # {{ | |
| # "messages":"Salama,inona no azoko hanampiana anao?" | |
| # }} | |
| # Important Notes: | |
| # Do not include any product or offer details in this case. | |
| # Do not indicate which case was chosen. | |
| # Do not provide any explanation—just the response. | |
| # Case 2: Specific Product Purchase | |
| # If the user explicitly mentions buying a specific product or offer, such as hividy MORA 500, provide the item code of the specific offer in structured JSON format. | |
| # If the user's input includes both a greeting and a specific product request (e.g., salama, hividy MORA 500), provide the item code of the specific offer in structured JSON format. | |
| # Example Input: hividy MORA 500; salama, hividy MORA 500 | |
| # Example Response: | |
| # {{ | |
| # "offre": "MR5" | |
| # }} | |
| # Important Notes: | |
| # Do not include details of unrelated products or offers. | |
| # Do not indicate which case was chosen. | |
| # Do not provide any explanation—just the response. | |
| # Case 3: General Product Inquiry | |
| # If the user asks for information about a product or offer without specifying a particular one (e.g., hividy MORA or salama, hividy MORA), respond by providing: | |
| # the response should still return the specific product in JSON format | |
| # Example Input: hividy MORA; salama, hividy MORA, inona izany mora izany | |
| # Example Response: | |
| # Example Response: | |
| # {{ | |
| # "offre": "MORA" | |
| # }} | |
| # Important Notes: | |
| # The product returned should be one of the product in the context | |
| # Do not include unrelated products or offers. | |
| # Do not indicate which case was chosen. | |
| # Do not provide any explanation—just the response. | |
| # Case 4: Ask all product available | |
| # If the user mentions buying offer but not provide the offer or product, (e.g. hividy offre, hividy tolotra), provide this structured json format. | |
| # Example Input: hividy offre; salama, hividy MORA 500 | |
| # Example Response: | |
| # {{ | |
| # "offre": "all" | |
| # }} | |
| # Important Notes: | |
| # Do not indicate which case was chosen. | |
| # Do not provide any explanation—just the response. | |
| # """) | |
| # ask_validation_template = ChatPromptTemplate.from_template(""" | |
| # Question: {input} | |
| # Identify whether the user's input {input} includes a validation or refusal term based on the following criteria: | |
| # - If the input contains a validation term (e.g., "ok", "eny", "oui", "valide", "yes", "ie", "eka","okok","mety") or any similar word, respond with the following JSON structure: | |
| # {{"validation": "true"}}. | |
| # - If the input contains a refusal term (e.g., "tsia", "tsy", "tsi", "non valide", "no", "nan", "not ok", "aaa") or any similar word, respond with the following JSON structure: | |
| # {{"validation": "false"}}. | |
| # If no validation or refusal term is found, do not provide any output. | |
| # """) | |
| ask_validation_template = ChatPromptTemplate.from_template(""" | |
| Question: {input} | |
| Determine whether the user's input, "{input}", indicates a **validation** (agreement or confirmation) or a **refusal** (disagreement or rejection). Use the following criteria: | |
| - **Validation**: If the input contains words or phrases indicating agreement, confirmation, or acceptance (e.g., "ok", "eny", "oui", "valide", "yes", "ie", "eka", "okok", "mety"), or similar expressions, respond with the JSON structure: | |
| {{"validation": "true"}}. | |
| - **Refusal**: If the input contains words or phrases indicating disagreement, rejection, or invalidation (e.g., "tsia", "tsy", "tsi", "non valide", "no", "nan", "not ok", "aaa"), or similar expressions, respond with the JSON structure: | |
| {{"validation": "false"}}. | |
| - **Contextual Understanding**: If the input does not exactly match the listed terms but clearly conveys agreement or refusal based on meaning, tone, or similar phrasing—even in another language—deduce the intent and respond accordingly. | |
| - **Fallback Case**: Regardless of the user's exact words, if the input seems semantically or contextually closer to **confirmation**, return: | |
| {{"validation": "true"}}. | |
| If it seems closer to **refusal**, return: | |
| {{"validation": "false"}}. | |
| - **Language Agnosticism**: Assume the input can be in any language and interpret the intent based on its contextual meaning rather than direct translation. | |
| Always prioritize the intent conveyed in the user's input over exact matches to the listed examples. | |
| """) | |
| # retrieval_chain = create_retrieval_system(documents, embeddings, llm, prompt_template) | |
| # Create an instance of RetrievalSystem | |
| retrieval_system = RetrievalSystem() | |
| retrieval_system.initialize() | |
| # Access the retrieval chain | |
| retrieval_chain = retrieval_system.get_retrieval_chain() | |
| async def query_with_timeout(retrieval_chain, query, timeout=10): | |
| try: | |
| response = await asyncio.wait_for( | |
| invoke_with_retry(retrieval_chain, input_query=query), | |
| timeout=timeout | |
| ) | |
| return response | |
| except asyncio.TimeoutError: | |
| raise HTTPException(status_code=408, detail="Request timeout") | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def query_with_timeout_payment(model, formatted_input, timeout=10): | |
| """ | |
| Wrapper to invoke the model with a timeout. | |
| Args: | |
| model: The language model. | |
| formatted_input: Formatted input for the model. | |
| timeout: Maximum time (in seconds) to wait for a response. | |
| Returns: | |
| The model's response or raises a timeout exception. | |
| """ | |
| try: | |
| response = await asyncio.wait_for( | |
| invoke_with_retry_payment(model, formatted_input), | |
| timeout=timeout | |
| ) | |
| return response | |
| except asyncio.TimeoutError: | |
| raise HTTPException(status_code=408, detail="Request timeout") | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| # Input schema | |
| class Query(BaseModel): | |
| input_query: str | |
| session_id: str | None = None | |
| # @app.get("/") | |
| # async def root(): | |
| # return {"message": "API is up and running. Use /docs to access Swagger UI."} | |
| async def ask_question(query: Query): | |
| session_id = query.session_id | |
| if not session_id: | |
| session_id = create_session() | |
| session = get_session(session_id) | |
| if session is None: | |
| raise HTTPException(status_code=404, detail="Invalid session ID") | |
| try: | |
| # Traiter la requête utilisateur | |
| # response = invoke_with_retry(retrieval_chain, input_query=query.input_query) | |
| response = await query_with_timeout(retrieval_chain,query.input_query, timeout=10) | |
| answer = response["answer"] | |
| print(answer) | |
| match = re.search(r"{[^}]*}", response["answer"]) | |
| if match: | |
| json_content = match.group() | |
| print(json_content) | |
| print(type(json_content)) | |
| # Récupérer la valeur de la première clé trouvée | |
| result = get_priority_value(json_content, Config.priority_keys) | |
| print(result) | |
| else: | |
| print("No JSON found!") | |
| # Ajouter l'entrée et la sortie à l'historique | |
| add_to_history(session_id, query.input_query, answer,result) | |
| # if key=="messages": | |
| # return {"session_id": session_id, "answer": answer,"messages":result} | |
| # else: | |
| # return {"session_id": session_id, "answer": answer,"offre":result} | |
| return {"session_id": session_id, "answer": answer,"offre":result} | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def ask_paiement(query: Query): | |
| session_id = query.session_id | |
| if not session_id: | |
| session_id = create_session() | |
| session = get_session(session_id) | |
| if session is None: | |
| raise HTTPException(status_code=404, detail="Invalid session ID") | |
| try: | |
| # print("tonga ato") | |
| # print(query.input_query) | |
| # formatted_input = Prompt.ask_payment_template.format(input=query.input_query) | |
| # print("tonga ato") | |
| # Traiter la requête utilisateur | |
| # response = invoke_with_retry_payment(llm, formatted_input) | |
| formatted_input = Prompt.ask_payment_template.format(input=query.input_query) | |
| # Process the query with timeout | |
| response = await query_with_timeout_payment(llm, formatted_input, timeout=10) | |
| # Parse response content and payment-related details | |
| content, result = None, None | |
| # print("tonga ato") | |
| if isinstance(response, AIMessage): | |
| content = response.content | |
| print("Response Content:", content) | |
| match = re.search(r"\{[^}]*\}", content) | |
| if match: | |
| json_content = match.group() | |
| print(json_content) | |
| print(type(json_content)) | |
| # Get the value of the first key found | |
| result = get_priority_value(json_content, Config.priority_keys) | |
| print(result) | |
| else: | |
| print("No JSON found!") | |
| else: | |
| print("Unexpected response format:", response) | |
| # Ajouter l'entrée et la sortie à l'historique | |
| add_to_history(session_id, query.input_query, content,result) | |
| return {"session_id": session_id, "answer": content,"payment":result} | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def final_validation(query: Query): | |
| session_id = query.session_id | |
| if not session_id: | |
| session_id = create_session() | |
| session = get_session(session_id) | |
| if session is None: | |
| raise HTTPException(status_code=404, detail="Invalid session ID") | |
| try: | |
| # print("tonga ato") | |
| # print(query.input_query) | |
| # formatted_input = ask_validation_template.format(input=query.input_query) | |
| # print(formatted_input) | |
| # # print("tonga ato") | |
| # # Traiter la requête utilisateur | |
| # response = invoke_with_retry_payment(llm, formatted_input) | |
| formatted_input = ask_validation_template.format(input=query.input_query) | |
| # Process the query with timeout | |
| response = await query_with_timeout_payment(llm, formatted_input, timeout=10) | |
| # Parse response content and payment-related details | |
| content, result = None, None | |
| # print("tonga ato") | |
| if isinstance(response, AIMessage): | |
| content = response.content | |
| print("Response Content:", content) | |
| match = re.search(r"\{[^}]*\}", content) | |
| if match: | |
| json_content = match.group() | |
| print(json_content) | |
| print(type(json_content)) | |
| # Get the value of the first key found | |
| result = get_priority_value(json_content, Config.priority_keys) | |
| print(result) | |
| else: | |
| print("No JSON found!") | |
| else: | |
| print("Unexpected response format:", response) | |
| print() | |
| # Ajouter l'entrée et la sortie à l'historique | |
| add_to_history(session_id, query.input_query, content,result) | |
| return {"session_id": session_id, "answer": content,"validation":result} | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run("app:app", host="127.0.0.1", port=7860, reload=True) | |