Spaces:
Sleeping
Sleeping
feat: add local llm
Browse filesSigned-off-by: Priyansh Saxena <priyena.programming@gmail.com>
Files changed (3)
- agent/nodes.py-25
- app.py+25-21
- rag/embeddings.py+5-3
4 unmodified lines56789101115 unmodified lines2728293031323334353612 unmodified lines495051525354556 unmodified lines62636465666768697071727374757677787980818222 unmodified lines1051061071081091101111121131141151161172 unmodified lines1201211221231241251265 unmodified lines1321331341351361371381391401411421431441451461471481491501511524 unmodified linesfrom agent.state import AgentStatefrom rag.retriever import retrieve_documentsfrom tools.lead_capture import mock_lead_capture<<<<<<< HEADfrom langchain_huggingface import HuggingFacePipelinefrom transformers import pipelineimport os15 unmodified lines)_local_llm = HuggingFacePipeline(pipeline=pipe)return _local_llm=======def get_llm():>>>>>>> 128a106 (Migration Phase 6: Autonomous agent core modules)return ChatOpenAI(model="gpt-4o-mini", temperature=0)class IntentResponse(BaseModel):12 unmodified lines("user", "{message}")])<<<<<<< HEADif hasattr(llm, "with_structured_output"):chain = prompt | llm.with_structured_output(IntentResponse)else:6 unmodified lines])chain = prompt | llm | parser=======chain = prompt | llm.with_structured_output(IntentResponse)>>>>>>> 128a106 (Migration Phase 6: Autonomous agent core modules)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']}"<<<<<<< HEADif hasattr(llm, "with_structured_output"):response = chain.invoke({"message": context_message})else:response = chain.invoke({"message": context_message, "format_instructions": parser.get_format_instructions()})=======response = chain.invoke({"message": context_message})>>>>>>> 128a106 (Migration Phase 6: Autonomous agent core modules)return {"detected_intent": response.intent}22 unmodified lines"message": state["current_message"]})<<<<<<< HEADcontent = response.content if hasattr(response, "content") else str(response)return {"response": content}=======return {"response": response.content}>>>>>>> 128a106 (Migration Phase 6: Autonomous agent core modules)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}")])<<<<<<< HEADif hasattr(llm, "with_structured_output"):extract_chain = extract_prompt | llm.with_structured_output(LeadExtractionResponse)5 unmodified lines("user", "{message}")])extract_chain = extract_prompt | llm | parser=======extract_chain = extract_prompt | llm.with_structured_output(LeadExtractionResponse)>>>>>>> 128a106 (Migration Phase 6: Autonomous agent core modules)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']}"<<<<<<< HEADif 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()})=======extracted = extract_chain.invoke({"message": context_message})>>>>>>> 128a106 (Migration Phase 6: Autonomous agent core modules)updates = {}if extracted.user_name and not state.get("user_name"):4 unmodified lines567891015 unmodified lines26272829303112 unmodified lines4445464748496 unmodified lines565758596061626364656667686922 unmodified lines92939495969798991002 unmodified lines1031041051061071085 unmodified lines1141151161171181191201211221231241251261274 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 os15 unmodified lines)_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:6 unmodified lines])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)5 unmodified lines("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()
agent/nodes.py-25
app.py+25-21
rag/embeddings.py+5-3