Spaces:
Sleeping
Sleeping
google-labs-jules[bot] archc0der commited on
Commit ·
9d2e886
1
Parent(s): c987214
feat: integrate local HF fallback models and enhance Streamlit UI
Browse files- Adds support for a local HuggingFace Qwen model (0.5B-Instruct) when OPENAI_API_KEY is not provided
- Adds support for local HuggingFace embeddings (sentence-transformers)
- Enhances Streamlit UI with a minimalist, modern dark theme
- Updates requirements to include transformers, pytorch, and HF dependencies
Co-authored-by: archc0der <119496494+archc0der@users.noreply.github.com>
Files changed (4)
- agent/nodes.py+53-5
- app.py+25-21
- rag/embeddings.py+5-3
- requirements.txt+5
4 unmodified lines5678910111212 unmodified lines25262728293031323334353622 unmodified lines596061626364652 unmodified lines6869707172737475767778794 unmodified linesfrom agent.state import AgentStatefrom rag.retriever import retrieve_documentsfrom tools.lead_capture import mock_lead_capturedef get_llm():return ChatOpenAI(model="gpt-4o-mini", temperature=0)class IntentResponse(BaseModel):12 unmodified lines("user", "{message}")])chain = prompt | llm.with_structured_output(IntentResponse)history_str = "\n".join([f"{msg['role']}: {msg['content']}" for msg in state.get("conversation_history", [])[-3:]])context_message = f"Recent history:\n{history_str}\n\nCurrent message:\n{state['current_message']}"response = chain.invoke({"message": context_message})return {"detected_intent": response.intent}22 unmodified lines"message": state["current_message"]})return {"response": response.content}def process_lead(state: AgentState) -> AgentState:llm = get_llm()2 unmodified lines("system", "Extract the user's name, email, and creator platform (e.g. YouTube, TikTok, Instagram) from the message if present. Return null for fields not found."),("user", "{message}")])extract_chain = extract_prompt | llm.with_structured_output(LeadExtractionResponse)history_str = "\n".join([f"{msg['role']}: {msg['content']}" for msg in state.get("conversation_history", [])[-3:]])context_message = f"Recent history:\n{history_str}\n\nCurrent message:\n{state['current_message']}"extracted = extract_chain.invoke({"message": context_message})updates = {}if extracted.user_name and not state.get("user_name"):4 unmodified lines567891011121314151617181920212223242526272829303112 unmodified lines444546474849505152535455565758596061626364656667686922 unmodified lines92939495969798991002 unmodified lines1031041051061071081091101111121131141151161171181191201211221231241251261274 unmodified linesfrom agent.state import AgentStatefrom rag.retriever import retrieve_documentsfrom tools.lead_capture import mock_lead_capturefrom langchain_huggingface import HuggingFacePipelinefrom transformers import pipelineimport os_local_llm = Nonedef get_llm():global _local_llmif not os.environ.get("OPENAI_API_KEY"):if _local_llm is None:pipe = pipeline("text-generation",model="Qwen/Qwen2.5-0.5B-Instruct",max_new_tokens=512,device="cpu",trust_remote_code=True,return_full_text=False)_local_llm = HuggingFacePipeline(pipeline=pipe)return _local_llmreturn ChatOpenAI(model="gpt-4o-mini", temperature=0)class IntentResponse(BaseModel):12 unmodified lines("user", "{message}")])if hasattr(llm, "with_structured_output"):chain = prompt | llm.with_structured_output(IntentResponse)else:from langchain.output_parsers import PydanticOutputParserparser = PydanticOutputParser(pydantic_object=IntentResponse)prompt = ChatPromptTemplate.from_messages([("system", "You are an intent classification assistant for AutoStream. Analyze the user's message and determine the intent. Categories: GREETING, PRODUCT_QUERY, PRICING_QUERY, HIGH_INTENT_LEAD, UNKNOWN. A 'HIGH_INTENT_LEAD' is when a user explicitly expresses interest in signing up, buying, or trying out a plan.\n\n{format_instructions}"),("user", "{message}")])chain = prompt | llm | parserhistory_str = "\n".join([f"{msg['role']}: {msg['content']}" for msg in state.get("conversation_history", [])[-3:]])context_message = f"Recent history:\n{history_str}\n\nCurrent message:\n{state['current_message']}"if hasattr(llm, "with_structured_output"):response = chain.invoke({"message": context_message})else:response = chain.invoke({"message": context_message, "format_instructions": parser.get_format_instructions()})return {"detected_intent": response.intent}22 unmodified lines"message": state["current_message"]})content = response.content if hasattr(response, "content") else str(response)return {"response": content}def process_lead(state: AgentState) -> AgentState:llm = get_llm()2 unmodified lines("system", "Extract the user's name, email, and creator platform (e.g. YouTube, TikTok, Instagram) from the message if present. Return null for fields not found."),("user", "{message}")])if hasattr(llm, "with_structured_output"):extract_chain = extract_prompt | llm.with_structured_output(LeadExtractionResponse)else:from langchain.output_parsers import PydanticOutputParserparser = PydanticOutputParser(pydantic_object=LeadExtractionResponse)extract_prompt = ChatPromptTemplate.from_messages([("system", "Extract the user's name, email, and creator platform (e.g. YouTube, TikTok, Instagram) from the message if present. Return null for fields not found.\n\n{format_instructions}"),("user", "{message}")])extract_chain = extract_prompt | llm | parserhistory_str = "\n".join([f"{msg['role']}: {msg['content']}" for msg in state.get("conversation_history", [])[-3:]])context_message = f"Recent history:\n{history_str}\n\nCurrent message:\n{state['current_message']}"if hasattr(llm, "with_structured_output"):extracted = extract_chain.invoke({"message": context_message})else:extracted = extract_chain.invoke({"message": context_message, "format_instructions": parser.get_format_instructions()})updates = {}if extracted.user_name and not state.get("user_name"):
3 unmodified lines456789101112131415161718192021222324259 unmodified lines35363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878810 unmodified lines991001011021033 unmodified linesfrom agent.graph import appfrom agent.state import AgentStateload_dotenv()st.set_page_config(page_title="AutoStream AI Sales Assistant", page_icon="🤖", layout="centered")st.markdown("""<style>.stChatFloatingInputContainer {bottom: 20px;}</style>""", unsafe_allow_html=True)if "messages" not in st.session_state:st.session_state.messages = []9 unmodified linesresponse="")st.session_state.messages.append({"role": "assistant", "content": "Hello! I'm the AutoStream assistant. I can answer questions about our features and pricing. How can I help you today?"})if not os.environ.get("OPENAI_API_KEY"):st.warning("⚠️ OPENAI_API_KEY is not set. Please set it in your environment to use the agent.")st.title("🤖 AutoStream AI Sales Assistant")st.markdown("Ask me about AutoStream features and pricing, or sign up for a plan!")for message in st.session_state.messages:with st.chat_message(message["role"]):st.markdown(message["content"])if prompt := st.chat_input("What would you like to know?"):st.session_state.messages.append({"role": "user", "content": prompt})with st.chat_message("user"):st.markdown(prompt)st.session_state.agent_state["current_message"] = promptwith st.chat_message("assistant"):with st.spinner("Thinking..."):try:result_state = app.invoke(st.session_state.agent_state)st.session_state.agent_state = result_stateresponse = result_state["response"]st.session_state.agent_state["conversation_history"].append({"role": "user", "content": prompt})st.session_state.agent_state["conversation_history"].append({"role": "assistant", "content": response})if len(st.session_state.agent_state["conversation_history"]) > 12:st.session_state.agent_state["conversation_history"] = st.session_state.agent_state["conversation_history"][-12:]st.markdown(response)with st.expander("Agent Reasoning & State"):st.write(f"**Detected Intent:** `{result_state.get('detected_intent', 'UNKNOWN')}`")if result_state.get("retrieved_documents") and result_state.get("detected_intent") in ["PRODUCT_QUERY", "PRICING_QUERY"]:st.write(f"**RAG Retrieval:** Found {len(result_state['retrieved_documents'])} relevant knowledge chunks.")10 unmodified linesresponse = f"An error occurred: {str(e)}"st.error(response)st.session_state.messages.append({"role": "assistant", "content": response})3 unmodified lines45678910111213141516171819202122232425262728293031323334353637383940419 unmodified lines5152535455565758596061626364656667686970717273747576777879808182838485868788899091929310 unmodified lines1041051061073 unmodified linesfrom agent.graph import appfrom agent.state import AgentStateload_dotenv()st.set_page_config(page_title="AutoStream AI Sales Assistant", page_icon="🎬", layout="centered")# Custom CSS for minimalist, cooler UIst.markdown("""<style>.stChatFloatingInputContainer {bottom: 20px;}.main {background-color: #0E1117;}h1 {color: #E2E8F0;font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;font-weight: 700;text-align: center;margin-bottom: 2rem;}.subtitle {color: #94A3B8;text-align: center;margin-bottom: 2rem;font-size: 1.1rem;}.stAlert {border-radius: 8px;}</style>""", unsafe_allow_html=True)if "messages" not in st.session_state:st.session_state.messages = []9 unmodified linesresponse="")st.session_state.messages.append({"role": "assistant", "content": "Hello! I'm the AutoStream assistant. I can answer questions about our features and pricing. How can I help you today?"})st.markdown("<h1>🎬 AutoStream Assistant</h1>", unsafe_allow_html=True)st.markdown("<div class='subtitle'>Ask about features and pricing, or sign up for a plan instantly!</div>", unsafe_allow_html=True)if not os.environ.get("OPENAI_API_KEY"):st.info("ℹ️ OPENAI_API_KEY is not set. The system will fall back to a local Qwen model and HuggingFace embeddings.")for message in st.session_state.messages:with st.chat_message(message["role"]):st.markdown(message["content"])if prompt := st.chat_input("What would you like to know?"):st.session_state.messages.append({"role": "user", "content": prompt})with st.chat_message("user"):st.markdown(prompt)st.session_state.agent_state["current_message"] = promptwith st.chat_message("assistant"):with st.spinner("Thinking..."):try:result_state = app.invoke(st.session_state.agent_state)st.session_state.agent_state = result_stateresponse = result_state["response"]st.session_state.agent_state["conversation_history"].append({"role": "user", "content": prompt})st.session_state.agent_state["conversation_history"].append({"role": "assistant", "content": response})if len(st.session_state.agent_state["conversation_history"]) > 12:st.session_state.agent_state["conversation_history"] = st.session_state.agent_state["conversation_history"][-12:]st.markdown(response)with st.expander("Agent Reasoning & State", expanded=False):st.write(f"**Detected Intent:** `{result_state.get('detected_intent', 'UNKNOWN')}`")if result_state.get("retrieved_documents") and result_state.get("detected_intent") in ["PRODUCT_QUERY", "PRICING_QUERY"]:st.write(f"**RAG Retrieval:** Found {len(result_state['retrieved_documents'])} relevant knowledge chunks.")10 unmodified linesresponse = f"An error occurred: {str(e)}"st.error(response)st.session_state.messages.append({"role": "assistant", "content": response})
1234567from langchain_openai import OpenAIEmbeddingsdef get_embeddings():"""Returns the embedding model used for the RAG pipeline."""return OpenAIEmbeddings()123456789from langchain_openai import OpenAIEmbeddingsfrom langchain_huggingface import HuggingFaceEmbeddingsimport osdef get_embeddings():if not os.environ.get("OPENAI_API_KEY"):return HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")return OpenAIEmbeddings()
8 unmodified lines910118 unmodified linespytestpytest-mockstreamlit8 unmodified lines9101112131415168 unmodified linespytestpytest-mockstreamlittransformerslangchain-huggingfacehuggingface-hubsentence-transformerstorch
agent/nodes.py+53-5
app.py+25-21
rag/embeddings.py+5-3
requirements.txt+5