Spaces:
Sleeping
Sleeping
Download vector_search.py from Vignesh5656/transformation-api: direct link, hf CLI and curl.
- Browser
- Download file 8.92 kB
-
https://huggingface.co/spaces/Vignesh5656/transformation-api/resolve/main/vector_search.py
- Command line
-
hf download hf://spaces/Vignesh5656/transformation-api/vector_search.py
-
curl -L -o vector_search.py https://huggingface.co/spaces/Vignesh5656/transformation-api/resolve/main/vector_search.py
8.92 kB
| import os | |
| from datetime import datetime | |
| import base64 | |
| import json | |
| import random | |
| import math | |
| import time | |
| from dataclasses import dataclass | |
| from typing import List, Dict, Any, Tuple, Optional | |
| from dotenv import load_dotenv | |
| from text_collection import chats, ContextMessage | |
| #from util import getAuthToken, sendHttpRequest | |
| from util.horizon_helper import getAuthToken, sendHttpRequest | |
| from langchain.embeddings import HuggingFaceEmbeddings | |
| from opensearchpy import OpenSearch, RequestsHttpConnection | |
| from langgraph.graph import StateGraph | |
| from typing import Dict, Any | |
| load_dotenv() | |
| # ---------- Utilities and config ---------- | |
| EMBEDDING_MODEL = "ml_qwen" | |
| CHAT_MODEL = "gpt-4o" | |
| VISION_MODEL = "gpt-4o-mini" # same family supports vision via image_url content | |
| IMAGE_MODEL = "gpt-image-1" | |
| TTS_MODEL = "tts-1" | |
| STT_MODEL = "whisper-1" | |
| horizonAddress=os.getenv('HORIZON_GATEWAY', '') | |
| CHROMA_PATH = r".\Chroma_Metadata" | |
| initial_prompt = "You’re an AI agent tasked with answering questions regarding health insurance benefits for a number of different customer types." | |
| messages = [] | |
| HORIZON_CHAT_ENDPOINT= "/v2/text/chats?qos=accurate&preview=true" #This will be used by Vector DB search and other general searches | |
| HORIZON_DOC_CHAT_PDF_ENDPOINT = "/v2/document/chats?qos=accurate&preview=true&q=equals.id[]=2d953838-235f-4a57-8d96-b3c04d3b6a21%26equals.id[]=46a988e1-9f8d-4357-ba4c-d311104f545c%26equals.id[]=9722f96c-07cc-4b64-894a-00ce09e9beb1%26equals.id[]=3012049a-9eea-4069-ba25-166fe2eb10b8" | |
| HORIZON_DOC_CHAT_MD_ENDPOINT = "/v2/document/chats?qos=accurate&preview=true&q=equals.id[]=81bf2b26-2a9d-4fcd-aa88-5396f04ee8f6%26equals.id[]=a573dcbb-80b7-4a3a-a862-a8176dc08902%26equals.id[]=cbd17121-3fee-4486-a260-dafd94ec248a%26equals.id[]=4ac3389b-eb55-488b-bea7-3c73150c0717" | |
| HORIZON_DOC_TAG_PDF_ENDPOINT = "/v2/document/chats?qos=accurate&preview=true&q=any.tags.origin=CarelonBenefits_PDF" | |
| HORIZON_DOC_TAG_MD_ENDPOINT = "/v2/document/chats?qos=accurate&preview=true&q=any.tags.origin=CarelonBenefits_MD" | |
| HORIZON_DOC_INGESTION_ENDPOINT = "/v2/documents" | |
| SCHEMA_FILE= "./mapping/SCLMAS_DDL.sql" | |
| MAPPING_FILE= "./mapping/Mapping.xlsx" | |
| MAPPING_SHEET_NAME = "Sheet1" | |
| MAPPING_DEST_TABLE = "SCLMAS" | |
| content_template = '''Answer the following question: {question}. Use the following context to use as references: | |
| <context> | |
| {context} | |
| <context> | |
| ''' | |
| QDRANT_HOSTNAME= "localhost" | |
| QDRANT_PORT= 6333 | |
| QDRANT_COLLECTION_NAME= "benefit_docs" | |
| QPENSEARCH_HOSTNAME= "vpc-benefit-agent-opensearch-uwrtyvn7ct7ierh5pg7cfehtfa.us-east-2.es.amazonaws.com" | |
| QPENSEARCH_PORT= 433 | |
| QPENSEARCH_INDEX= "benefit_docs_v3" | |
| OPENSEARCH_USER = "benadmin" | |
| OPENSEARCH_PASS = "Opensearch@123" | |
| EMBED_MODEL_LOC = "ml_qwen\snapshots\c54f2e6e80b2d7b7de06f51cec4959f6b3e03418" | |
| K = 10 | |
| # Imports | |
| def load_vector_db(): | |
| print(f"Starting set up of vector store {datetime.now().strftime("%H:%M:%S")}") | |
| # Connect to Open Search | |
| # vector_store = OpenSearch( | |
| # hosts=[{'host': QPENSEARCH_HOSTNAME, | |
| # 'port': QPENSEARCH_PORT}], | |
| # http_auth=(OPENSEARCH_USER, OPENSEARCH_PASS), | |
| # use_ssl=True, | |
| # verify_certs=True, | |
| # connection_class=RequestsHttpConnection | |
| # ) | |
| store = OpenSearch( | |
| hosts=[{'host': 'vpc-benefit-agent-opensearch-uwrtyvn7ct7ierh5pg7cfehtfa.us-east-2.es.amazonaws.com', | |
| 'port': 443}], | |
| http_auth=('benadmin', 'Opensearch@123'), | |
| use_ssl=True, | |
| verify_certs=True, | |
| connection_class=RequestsHttpConnection | |
| ) | |
| print(f"Finished set up of vector store {datetime.now().strftime("%H:%M:%S")}") | |
| return store | |
| db = load_vector_db() | |
| def setup_embedding_model(): | |
| print(f"Starting the embedding model {datetime.now().strftime("%H:%M:%S")}") | |
| try: | |
| model = HuggingFaceEmbeddings(model_name=EMBED_MODEL_LOC) | |
| except Exception as e: | |
| print(f"Error loading embedding model: {e}") | |
| model = None | |
| print(f"Finished the embedding model {datetime.now().strftime("%H:%M:%S")}") | |
| return model | |
| embedding_model = setup_embedding_model() | |
| GraphState = Dict[str, Any] | |
| def start_node(state: GraphState) -> GraphState: | |
| print("Starting LangGraph flow...") | |
| return state | |
| # VectorDB Search Node | |
| def vector_db_search_node(state: GraphState) -> GraphState: | |
| question = state.get("question", "") | |
| par_code_selected = state.get("par_code_selected", "") | |
| # Embed the question | |
| query_vec = embedding_model.embed_query(question) | |
| # Build the search body | |
| body = { | |
| "size": K, | |
| "query": { | |
| "knn": { | |
| "embedding": { | |
| "vector": query_vec, | |
| "k": K, | |
| "filter": { | |
| "bool": { | |
| "must": [ | |
| { | |
| "term": {"metadata.parentcode.keyword": par_code_selected} | |
| } | |
| ] | |
| } | |
| } | |
| } | |
| } | |
| } | |
| } | |
| # Perform the search | |
| res = db.search(index=QPENSEARCH_INDEX, body=body) | |
| # Extract results | |
| results = [ | |
| { | |
| "score": hit["_score"], | |
| "text": hit["_source"].get("text", ""), | |
| "id": hit.get("_id"), | |
| } | |
| for hit in res["hits"]["hits"] | |
| ] | |
| # Combine context text | |
| context_text = "\n\n - -\n\n".join([doc["text"] for doc in results]) | |
| # Update state | |
| state["context_text"] = context_text | |
| state["vector_results"] = results | |
| return state | |
| def submit_to_llm_node(state: Dict[str, Any]) -> Dict[str, Any]: | |
| try: | |
| # Extract inputs from state | |
| context_text = state.get("context_text", "") | |
| question = state.get("question", "") | |
| sys_prompt = state.get("sys_prompt", "You are a helpful assistant.") | |
| endpoint = state.get("endpoint", "/v2/text/chats?qos=accurate&preview=true") | |
| # Format the user prompt using a template | |
| content_template = "Context:\n{context}\n\nQuestion:\n{question}" | |
| user_prompt = content_template.format(context=context_text, question=question) | |
| # Authenticate and prepare messages | |
| authToken = getAuthToken( | |
| os.getenv('HORIZON_CLIENT_ID', ''), | |
| os.getenv('HORIZON_CLIENT_SECRET', ''), | |
| os.getenv('HORIZON_GATEWAY', '') | |
| ) | |
| messageSys = ContextMessage() | |
| messageSys["role"] = "system" | |
| messageSys["content"] = sys_prompt | |
| messageUser = ContextMessage() | |
| messageUser["role"] = "user" | |
| messageUser["content"] = user_prompt | |
| messages = [messageSys, messageUser] | |
| payload = json.dumps({"messages": messages}) | |
| headers = { | |
| "Content-Type": "application/json", | |
| "Authorization": "Bearer " + authToken | |
| } | |
| response = sendHttpRequest( | |
| data=payload, | |
| header=headers, | |
| method="POST", | |
| address=horizonAddress, | |
| endpoint=endpoint | |
| ) | |
| json_data = response.text | |
| json_object = json.loads(json_data) | |
| # Extract and store the response | |
| state["llm_response"] = json_object['message']['content'] | |
| return state | |
| except Exception as e: | |
| print(f"Error in LLM submission: {e}") | |
| state["llm_response"] = "Error generating response." | |
| return state | |
| def end_node(state: GraphState) -> GraphState: | |
| print("Ending LangGraph flow...") | |
| return state | |
| graph = StateGraph(GraphState) | |
| # Add nodes | |
| graph.add_node("Start", start_node) | |
| graph.add_node("VectorDBSearch", vector_db_search_node) | |
| graph.add_node("SubmitToLLM", submit_to_llm_node) | |
| graph.add_node("END",end_node) | |
| # Define edges | |
| graph.set_entry_point("Start") | |
| graph.add_edge("Start", "VectorDBSearch") | |
| graph.add_edge("VectorDBSearch", "SubmitToLLM") | |
| graph.add_edge("SubmitToLLM","END") | |
| # Compile the graph | |
| langgraph_app = graph.compile() | |
| configured_responses = {} | |
| with open("./responses.json", "r", encoding='utf-8') as in_file: | |
| data = in_file.read() | |
| print(data) | |
| configured_responses = json.loads(data) | |
| class DocChunk: | |
| id: str | |
| text: str | |
| source: str | |
| embedding: List[float] | |
| def process_chat(user_prompt: str, parent_code: str, sys_prompt: str) -> str: | |
| if user_prompt.strip() in configured_responses.keys(): | |
| llm_response = configured_responses[user_prompt.strip()] | |
| sleep_time = random.randint(2500, 3500) | |
| time.sleep(float(sleep_time) / 1000.0) | |
| return llm_response | |
| initial_state = { | |
| "question": user_prompt, | |
| "sys_prompt": sys_prompt, | |
| "par_code_selected": parent_code | |
| } | |
| final_state = langgraph_app.invoke(initial_state) | |
| llm_response = final_state.get("llm_response", "No response generated.") | |
| return llm_response |