Upload app.py with huggingface_hub
Browse files7 unmodified lines89101112131410 unmodified lines2526272829303120 unmodified lines52535455565722 unmodified lines808182838485868788899058 unmodified lines14915015115215315415515615715815913 unmodified lines17317417517617717817918018118218318418518618718818919019119219319419519619719819920064 unmodified lines2652662672682692702712722732741 unmodified line276277278279280281282283284285286287288289290291292293294295296297155 unmodified lines453454455456457458459120 unmodified lines5805815825835845855865875885895907 unmodified linesfrom langchain_core.documents import Document # Document data structuresfrom langchain_core.runnables import RunnablePassthrough # LangChain core library for running pipelinesfrom langchain_core.output_parsers import StrOutputParser # String output parserfrom langchain.prompts import ChatPromptTemplate # Template for chat promptsfrom langchain.chains.query_constructor.base import AttributeInfo # Base classes for query constructionfrom langchain.retrievers.self_query.base import SelfQueryRetriever # Base classes for self-querying retrieversfrom langchain.retrievers.document_compressors import LLMChainExtractor, CrossEncoderReranker # Document compressors10 unmodified lines)from langchain_core.tools import toolfrom langchain.agents import create_tool_calling_agent, AgentExecutorfrom langchain_core.prompts import ChatPromptTemplatefrom langchain_openai import ChatOpenAI# LangChain OpenAI imports20 unmodified linesimport streamlit as stfrom datetime import datetime#====================================SETUP=====================================## Fetch secrets from Hugging Face Spaces22 unmodified lines# Initialize the Chat OpenAI modelllm = ChatOpenAI(base_url=openai_api_base,openai_api_key=openai_api_key,model="gpt-4o-mini",streaming=False)# This initializes the Chat OpenAI model with the provided endpoint, API key, deployment name, and a temperature setting of 0 (to control response variability).58 unmodified lines# Initialize the Chroma vector store for retrieving documentsvector_store = Chroma(collection_name="nutritional_hypotheticals",persist_directory="./nutritional_db",embedding_function=embedding_model)# Create a retriever from the vector store13 unmodified linesDict: The updated state with the retrieved context."""print("---------retrieve_context---------")query = state['expanded_query'] # Complete the code to define the key for the expanded query#print("Query used for retrieval:", query) # Debugging: Print the query# Retrieve documents from the vector storedocs = retriever.invoke(query)print("Retrieved documents:", docs) # Debugging: Print the raw docs object# Extract both page_content and metadata from each documentcontext= [{"content": doc.page_content, # The actual content of the document"metadata": doc.metadata # The metadata (e.g., source, page number, etc.)}for doc in docs]state['context'] = context # Complete the code to define the key for storing the contextprint("Extracted context with metadata:", context) # Debugging: Print the extracted context#print(f"Groundedness loop count: {state['groundedness_loop_count']}")return statedef craft_response(state: Dict) -> Dict: #Blank #3 for app.py"""Generates a response using the retrieved context, focusing on nutrition disorders.64 unmodified linesIntermediate values indicate partial groundedness.'''groundedness_prompt = ChatPromptTemplate.from_messages([("system", system_message),("user", "Context: {context}\nResponse: {response}\n\nGroundedness score:")])# chain = groundedness_prompt | llm | StrOutputParser()# groundedness_score = float(chain.invoke({1 unmodified line# "response": state['response'] # Complete the code to define the response# }))# Build the context string separatelycontext_str = "\n".join(doc["content"] for doc in state["context"])# Build the input payload for the groundedness chaingroundedness_input = {"context": context_str,"response": state["response"], # Complete the code to define the response}# Run the chain and parse the groundedness scorechain = groundedness_prompt | llm | StrOutputParser()groundedness_score = float(chain.invoke(groundedness_input))print("groundedness_score: ", groundedness_score)state['groundedness_loop_count'] += 1print("#########Groundedness Incremented###########")state['groundedness_score'] = groundedness_score155 unmodified linesfrom langgraph.graph import END, StateGraph, STARTdef create_workflow() -> StateGraph: #Blank #11 for app.py"""Creates the updated workflow for the AI nutrition agent."""120 unmodified linesself.memory = MemoryClient(api_key= mem0_api_key) # Complete the code to define the memory client API key# Initialize the OpenAI client using the provided credentialsself.client = ChatOpenAI(model_name="gpt-4o-mini", # Specify the model to use (e.g., GPT-4 optimized version)api_key=openai_api_key, # API key for authenticationbase_url = openai_api_base,temperature=0 # Controls randomness in responses; 0 ensures deterministic results)# Define tools available to the chatbot, such as web search7 unmodified lines89101112131410 unmodified lines2526272829303120 unmodified lines525354555657585922 unmodified lines82838485868788899091929394959697989910058 unmodified lines15916016116216316416516616716816917017117217317417517617717817918018118213 unmodified lines19619719819920020120220320420520620720820921021121221321421521621721821922064 unmodified lines2852862872882892902912922932942952962972982993003013023033043053061 unmodified line308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338155 unmodified lines494495496497498499500120 unmodified lines6216226236246256266276286296306316326336346356366376387 unmodified linesfrom langchain_core.documents import Document # Document data structuresfrom langchain_core.runnables import RunnablePassthrough # LangChain core library for running pipelinesfrom langchain_core.output_parsers import StrOutputParser # String output parser#from langchain.prompts import ChatPromptTemplate #imported belowfrom langchain.chains.query_constructor.base import AttributeInfo # Base classes for query constructionfrom langchain.retrievers.self_query.base import SelfQueryRetriever # Base classes for self-querying retrieversfrom langchain.retrievers.document_compressors import LLMChainExtractor, CrossEncoderReranker # Document compressors10 unmodified lines)from langchain_core.tools import toolfrom langchain.agents import create_tool_calling_agent, AgentExecutorfrom langchain_core.prompts import ChatPromptTemplate # Template for chat promptsfrom langchain_openai import ChatOpenAI# LangChain OpenAI imports20 unmodified linesimport streamlit as stfrom datetime import datetimeimport shutil#====================================SETUP=====================================## Fetch secrets from Hugging Face Spaces22 unmodified lines# Initialize the Chat OpenAI model# llm = ChatOpenAI(# base_url=openai_api_base,# openai_api_key=openai_api_key,# model="gpt-4o-mini",# streaming=False# )llm = ChatOpenAI(base_url=openai_api_base,openai_api_key=openai_api_key,model="gpt-4o-mini",temperature=0,streaming=False,)# This initializes the Chat OpenAI model with the provided endpoint, API key, deployment name, and a temperature setting of 0 (to control response variability).58 unmodified lines# Initialize the Chroma vector store for retrieving documents# vector_store = Chroma(# collection_name="nutritional_hypotheticals",# persist_directory="./nutritional_db",# embedding_function=embedding_model# )# HuggingFace expects to create this so remove the old oneDB_DIR = "./nutritional_db"if os.path.exists(DB_DIR):shutil.rmtree(DB_DIR)vector_store = Chroma(collection_name="nutritional_hypotheticals",persist_directory=DB_DIR,embedding_function=embedding_model,)# Create a retriever from the vector store13 unmodified linesDict: The updated state with the retrieved context."""print("---------retrieve_context---------")query = state.get('expanded_query', state.get('query', ''))docs = retriever.invoke(query)# Ensure docs is iterable and has contentcontext = []for doc in docs:content = getattr(doc, 'page_content', str(doc))metadata = getattr(doc, 'metadata', {})context.append({"content": content, "metadata": metadata})state['context'] = contextif not context:print(f"[INFO] No documents found for query: {query}")return statedef craft_response(state: Dict) -> Dict: #Blank #3 for app.py"""Generates a response using the retrieved context, focusing on nutrition disorders.64 unmodified linesIntermediate values indicate partial groundedness.'''# Build the context string separatelycontext_str = "\n".join(doc["content"] for doc in state.get("context", []))response_str = state.get("response", "")if not context_str:print("No context available, setting groundedness_score=0")state['groundedness_score'] = 0.0# state['groundedness_loop_count'] += 1state['groundedness_loop_count'] = state.get('groundedness_loop_count', 0) + 1return stategroundedness_prompt = ChatPromptTemplate.from_messages([("system", system_message),("user", "Context: {context}\nResponse: {response}\n\nGroundedness score:")])# chain = groundedness_prompt | llm | StrOutputParser()# groundedness_score = float(chain.invoke({1 unmodified line# "response": state['response'] # Complete the code to define the response# }))# Build the input payload for the groundedness chain# groundedness_input = {# "context": context_str,# "response": state["response"], # Complete the code to define the response# }# Run the chain and parse the groundedness scorechain = groundedness_prompt | llm | StrOutputParser()# groundedness_score = float(chain.invoke(groundedness_input))groundedness_score = float(chain.invoke({"context": context_str,"response": response_str}))# if not context:# print(f"[INFO] No documents found for query: {query}")if not state.get('context'):print("[INFO] No documents in state['context']")print("groundedness_score: ", groundedness_score)# state['groundedness_loop_count'] += 1state['groundedness_loop_count'] = state.get('groundedness_loop_count', 0) + 1print("#########Groundedness Incremented###########")state['groundedness_score'] = groundedness_score155 unmodified lines#from langgraph.graph import END, StateGraph, STARTdef create_workflow() -> StateGraph: #Blank #11 for app.py"""Creates the updated workflow for the AI nutrition agent."""120 unmodified linesself.memory = MemoryClient(api_key= mem0_api_key) # Complete the code to define the memory client API key# Initialize the OpenAI client using the provided credentials# self.client = ChatOpenAI(# model_name="gpt-4o-mini", # Specify the model to use (e.g., GPT-4 optimized version)# api_key=openai_api_key, # API key for authentication# base_url = openai_api_base,# temperature=0 # Controls randomness in responses; 0 ensures deterministic results# )self.client = ChatOpenAI(base_url=openai_api_base,openai_api_key=openai_api_key,model="gpt-4o-mini",temperature=0,)# Define tools available to the chatbot, such as web search
app.py+83-35