Download db_agent.py from uiynyny/llama3RAG: direct link, hf CLI and curl.
- Browser
- Download file 12.1 kB
-
https://huggingface.co/spaces/uiynyny/llama3RAG/resolve/main/db_agent.py
- Command line
-
hf download hf://spaces/uiynyny/llama3RAG/db_agent.py
-
curl -L -o db_agent.py https://huggingface.co/spaces/uiynyny/llama3RAG/resolve/main/db_agent.py
12.1 kB
| from typing import List, Optional | |
| import os | |
| import logging | |
| from dotenv import load_dotenv | |
| from langchain_core.prompts import ChatPromptTemplate | |
| from langchain_pinecone import PineconeVectorStore | |
| from langchain_huggingface import HuggingFaceEmbeddings | |
| from langchain_nvidia_ai_endpoints import ChatNVIDIA | |
| from pinecone import Pinecone | |
| load_dotenv() | |
| logger = logging.getLogger(__name__) | |
| PINECONE_HOST = (os.getenv("PINECONE_HOST") or "").strip().strip('"').strip("'") | |
| PINECONE_API_KEY = (os.getenv("PINECONE_API_KEY") or "").strip().strip('"').strip("'") | |
| PINECONE_INDEX_NAME = (os.getenv("PINECONE_INDEX_NAME") or "metabodb").strip().strip('"').strip("'") | |
| # NVIDIA retired the hosted Nemotron 3 Super function (404 Function not found). | |
| RETIRED_CHAT_MODELS = { | |
| "nvidia/nemotron-3-super-120b-a12b": "nvidia/nemotron-3.5-super-vl-120b-a12b", | |
| } | |
| DEFAULT_CHAT_MODEL = "nvidia/nemotron-3-ultra-550b-a55b" | |
| def resolve_chat_model(name: Optional[str]) -> str: | |
| requested = (name or "").strip().strip('"').strip("'") or DEFAULT_CHAT_MODEL | |
| return RETIRED_CHAT_MODELS.get(requested, requested) | |
| MODEL = resolve_chat_model(os.getenv("CHAT_MODEL")) | |
| ENABLE_THINKING = os.getenv("ENABLE_THINKING", "0") == "1" | |
| STREAM_KWARGS = {"chat_template_kwargs": {"enable_thinking": ENABLE_THINKING}} | |
| REQUEST_TIMEOUT = int(os.getenv("REQUEST_TIMEOUT", "60")) | |
| _client = None | |
| _vector_store = None | |
| _pinecone = None | |
| def get_llm_client(): | |
| global _client | |
| if _client is None: | |
| _client = ChatNVIDIA( | |
| model=MODEL, | |
| base_url=os.getenv("MODEL_API_BASE_URL", "https://integrate.api.nvidia.com/v1"), | |
| api_key=os.getenv("MODEL_API_KEY"), | |
| timeout=REQUEST_TIMEOUT, | |
| ) | |
| return _client | |
| def get_vector_store(): | |
| global _vector_store, _pinecone | |
| if _vector_store is not None: | |
| return _vector_store | |
| if not PINECONE_HOST or not PINECONE_API_KEY: | |
| logger.warning("Pinecone configuration is missing (PINECONE_HOST or PINECONE_API_KEY). Vector RAG will be skipped.") | |
| return None | |
| try: | |
| _pinecone = Pinecone(api_key=PINECONE_API_KEY) | |
| _vector_store = PineconeVectorStore( | |
| index=_pinecone.Index(PINECONE_INDEX_NAME, host=PINECONE_HOST), | |
| embedding=HuggingFaceEmbeddings(), | |
| ) | |
| return _vector_store | |
| except Exception as e: | |
| logger.error(f"Failed to initialize Pinecone vector store: {e}") | |
| return None | |
| def _message_content(message): | |
| if isinstance(message, dict): | |
| content = message.get("content") | |
| additional = message.get("additional_kwargs") or {} | |
| reasoning = message.get("reasoning_content") | |
| else: | |
| content = getattr(message, "content", None) | |
| additional = getattr(message, "additional_kwargs", None) or {} | |
| reasoning = getattr(message, "reasoning_content", None) | |
| if isinstance(content, list): | |
| content = "".join( | |
| part.get("text", "") if isinstance(part, dict) else str(part) | |
| for part in content | |
| ) | |
| if isinstance(content, str) and content.strip(): | |
| return content | |
| if isinstance(reasoning, str) and reasoning.strip(): | |
| return reasoning | |
| reasoning = additional.get("reasoning_content") if isinstance(additional, dict) else None | |
| return reasoning if isinstance(reasoning, str) else "" | |
| def _response_text(response): | |
| if hasattr(response, "content") or hasattr(response, "additional_kwargs"): | |
| return _message_content(response) | |
| if hasattr(response, "choices"): | |
| return _message_content(response.choices[0].message) | |
| return "" | |
| def _stream_complete(messages, max_tokens: int = 4096): | |
| """Yield visible response text from one model request.""" | |
| client_instance = get_llm_client() | |
| chunks = [] | |
| for response in client_instance.stream( | |
| messages, config={"max_tokens": max_tokens}, **STREAM_KWARGS | |
| ): | |
| content = _response_text(response) | |
| if content.strip(): | |
| chunks.append(content) | |
| yield content | |
| if not chunks: | |
| raise RuntimeError( | |
| "The language model returned an empty response. " | |
| "Check your inference-provider credits/quota and try again." | |
| ) | |
| def _complete(messages, max_tokens: int = 4096): | |
| """Run a chat completion and return the complete visible response.""" | |
| return "".join(_stream_complete(messages, max_tokens=max_tokens)).strip() | |
| # Module-level aliases for backwards compatibility | |
| class _ClientProxy: | |
| def __getattr__(self, name): | |
| return getattr(get_llm_client(), name) | |
| client = _ClientProxy() | |
| vector_store = None # Lazily loaded via get_vector_store() | |
| QA_PROMPT = """ | |
| You are Omiver, a highly skilled nutritionist and expert in metabolomics with extensive knowledge in compounds, nutrition info of food and knowledgeable in metabolomics. | |
| Here are some context about the question: | |
| •How often can (Chosen Profile) alter their profile information? | |
| •With access to Omiver’s platform, (Chosen Profile) will be able to alter their information at any time! This includes their dietary preferences, allergies, and performance goals. Their biomarker profile will also be updated based on their frequency of testing. | |
| •What biomarkers are evaluated in Omiver’s testing kit? | |
| •Omiver looks at 200+ biomarkers to determine the ideal meal plan and exercise routine for you or your client. While we cannot detail all biomarkers, our test encompasses metabolite categories including vitamins, lipids, amino acids. | |
| How are Omiver's meal plans generated? | |
| •Omiver combines standard nutritional guidelines, up-to-date scientific literature, and expert-vetted recipes to create a meal plan that works for your unique lifestyle habits and performance goals. We take into account your dietary preferences and allergies to provide a holistic diet that will allow you to meet your nutrition goals. | |
| •Can Omivers meal plan options be amended in the platform? | |
| •You can submit feedback including amendments to our recommendations through Omiver's platforms. After you submit feedback, we will verify with our experts to ensure that the changes suggested match the necessary requirements based on your/your client's individual profile. We will factor in your changes into our model to ensure that your preferences are recorded and implemented for future reports. | |
| •How does the meal plan recommendations reflect biomarker results? | |
| •Through your biomarker assessment data, we evaluate the condition of your metabolic profile. If there are any abnormalities present, Omiver will provide specific guidance to improve the concentrations of these metabolite biomarkers | |
| How are Omiver's exercise routines generated? | |
| •Omiver combines up-to-date scientific literature on athletic performance and muscle anatomy, and expert-vetted training plans to provide evidence-informed training plans that works for your unique lifestyle habits and performance goals. We factor in your weekly fitness regimen and external feedback to provide a regimen that will allow you to meet your fitness goals. | |
| •Can Omiver's exercise routines be amended in the platform? | |
| •You can submit feedback including amendments to our recommendations through Omiver's platforms. After you submit feedback, we will verify with our experts to ensure that the changes suggested match the necessary requirements based on your/your client's individual profile. We will factor in your changes into our model to ensure that your preferences are recorded and implemented for future reports. | |
| •How does the exercise routine recommendations reflect biomarker results? | |
| •Through your biomarker assessment data, we evaluate the condition of your metabolic profile. If there are any abnormalities present, Omiver will provide specific guidance to improve the concentrations of these metabolite biomarkers | |
| ==== | |
| Based on the information given: {user_context}, respond to the question with table or list format if needed. and keep the result within a paragraph and concise. | |
| --- | |
| Answer the following question: {question} | |
| """ | |
| REPORT_PROMPT = """ | |
| You are Omiver, a highly skilled nutritionist and expert in metabolomics with extensive knowledge in compounds, nutrition info of food and metabolomics. | |
| ==== | |
| The user information is given here: {user_context}, | |
| Context of the conversation: {context} | |
| Additional compound and food information retrieved: {hmdb_info} | |
| You will analyze the client's information and context of the conversation and give answers from your findings and knowledge regarding their diet preferences, exercise preferences, goals, and biometric information including but not limited to race, sexuality, age, weight, height, etc. as thinking process. | |
| Give an answer for each question from the user with reasons and explanations according to the client's circumstance and information. Use table format as required. | |
| You will give no advice or suggestions that can be construed as medical advice as you don’t have the legal authority to do so. This cannot be violated. | |
| --- | |
| Answer the question based on the above context: {question} | |
| """ | |
| def qa(query_text, person_info, stream=False): | |
| prompt_template = ChatPromptTemplate.from_template(QA_PROMPT) | |
| prompt = prompt_template.format( | |
| user_context=person_info, question=query_text[-1]) | |
| messages = [ | |
| {"role": "user", "content": prompt} | |
| ] | |
| return _stream_complete(messages) if stream else _complete(messages) | |
| def query_rag(query_text: List[str], person_info, stream=False): | |
| vs = get_vector_store() | |
| if vs is not None: | |
| try: | |
| results = vs.similarity_search_with_score(query_text[-1], k=5) | |
| except Exception as e: | |
| logger.error(f"Vector search failed: {e}") | |
| results = [] | |
| else: | |
| results = [] | |
| previous_conversation = "\n\n---\n\n".join(query_text[:-1]) | |
| if len(previous_conversation) > 4000: | |
| previous_conversation = previous_conversation[-4000:] | |
| context_text = "previous conversation:" + previous_conversation + \ | |
| "\n\n---\n\n".join([doc.page_content for doc, _score in results]) | |
| prompt_template = ChatPromptTemplate.from_template(REPORT_PROMPT) | |
| prompt = prompt_template.format( | |
| user_context=person_info, context=context_text, hmdb_info="empty", question=query_text[-1]) | |
| messages = [ | |
| {"role": "user", "content": prompt} | |
| ] | |
| if stream: | |
| return _stream_complete(messages, max_tokens=999999) | |
| answer = _complete(messages) | |
| sources = [doc.metadata.get("id", None) for doc, _score in results] | |
| formatted_response = f"Response: {answer}\nSources: {sources}" | |
| return answer | |
| def generate_report(query_text: List[str], person_info: str): | |
| if not query_text: | |
| raise ValueError("query_text must contain at least one prompt element.") | |
| question = ( | |
| "{client} Give an analysis for this client. Tune the output to be more " | |
| "Use the html style to give Biomarker Delta Analysis between each test run and in header followed by time ascending order. " | |
| "To pick the metabolites to display in Point1, focus on those with both 1) the most notable changes and 2) those which have the best indication of being associated with different important physiological changes related to exercise and diet. " | |
| "Point1: Biomarker Delta Analysis - Give the biomarker name and formula, don't include m/z. " | |
| "Point2: Broad insights from metabolomic panels " | |
| "Point3: Diet Plan " | |
| "Point4: Exercise & Physical Activity Plan " | |
| "Then give a Metabolomics Insight which synthesizes the conclusions from all of the metabolites and contextual information to generate an accurate picture of what is likely happening within the person. Focus on the most important and pertinent and don't list too many different outputs. " | |
| "Finally give a Diet Plan for breakfast (DO NOT USE WORD PRECISION), lunch, and dinner, snacks for the whole week and Exercise Plan. Each with reasons." | |
| ).format(client=person_info) | |
| query_text = list(query_text) + [question] | |
| return query_rag(query_text, person_info) | |