Spaces:
Build error
Build error
Basic Agentic AI Chatbot
Browse filesFiles changed (10)
- app.py+5
- src/langgraph_agenticai/LLMS/groqllm.py+21
- src/langgraph_agenticai/graph/graph_builder.pyAdded+39
- src/langgraph_agenticai/main.py+61
- src/langgraph_agenticai/nodes/basic_chatbot_node.pyAdded+17
- src/langgraph_agenticai/state/state.pyAdded+13
- src/langgraph_agenticai/ui/streamlit_ui/display_result.py+41
- src/langgraph_agenticai/ui/streamlit_ui/loadui.py+55-1
- src/langgraph_agenticai/ui/uiconfigfile.ini+2-2
- src/langgraph_agenticai/ui/uiconfigfile.py+9-9
12345from src.langgraph_agenticai.main import load_langgraph_agenticai_appif __name__=="__main__":load_langgraph_agenticai_app()
123456789101112131415161718192021import osimport streamlit as stfrom langchain_groq import ChatGroqclass GroqLLM:def __init__(self, user_controls_input):self.user_controls_input = user_controls_inputdef get_llm_model(self):try:groq_api_key = self.user_controls_input['GROQ_API_KEY']selected_groq_model = self.user_controls_input['selected_groq_model']llm = ChatGroq(api_key=groq_api_key, model= selected_groq_model)except Exception as e:raise ValueError(f"Error occured with Exception : {e}")return llm
123456789101112131415161718192021222324252627282930313233343536373839from langgraph.graph import StateGraph,START, END, MessagesStatefrom langgraph.prebuilt import tools_condition, ToolNodefrom langchain_core.prompts import ChatPromptTemplatefrom src.langgraph_agenticai.state.state import Statefrom src.langgraph_agenticai.nodes.basic_chatbot_node import BasicChatbotNode
class GraphBuilder: def __init__(self, model): self.llm = model self.graph_builder = StateGraph(State) def basic_chatbot_build_graph(self): """ Builds a basic chatbot graph using LangGraph. This method initializes a chatbot node using the `BasicChatbotNode` class and integrates it into the graph. The chatbot node is set as both the entry and exit point of the graph. """ self.basic_chatbot_node = BasicChatbotNode(self.llm) self.graph_builder.add_node("chatbot", self.basic_chatbot_node.process) self.graph_builder.add_edge(START, "chatbot") self.graph_builder.add_edge("chatbot", END) def setup_graph(self, usecase: str): """ Sets up the graph for the selected use case. """ if usecase == "Basic Chatbot": self.basic_chatbot_build_graph()
if usecase == "Chatbot with Tool": # self.chatbot_with_tools_build_graph() pass return self.graph_builder.compile()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061import streamlit as stimport jsonfrom src.langgraph_agenticai.ui.streamlit_ui.loadui import LoadStreamlitUIfrom src.langgraph_agenticai.LLMS.groqllm import GroqLLMfrom src.langgraph_agenticai.graph.graph_builder import GraphBuilderfrom src.langgraph_agenticai.ui.streamlit_ui.display_result import DisplayResultStreamlit# MAIN Function STARTdef load_langgraph_agenticai_app():"""Loads and runs the LangGraph AgenticAI application with Streamlit UI.This function initializes the UI, handles user input, configures the LLM model,sets up the graph based on the selected use case, and displays the output whileimplementing exception handling for robustness."""# Load UIui = LoadStreamlitUI()user_input = ui.load_streamlit_ui()if not user_input:st.error("Error: Failed to load user input from the UI.")return# Text input for user messageif st.session_state.IsFetchButtonClicked:user_message = st.session_state.timeframeelse :user_message = st.chat_input("Enter your message:")if user_message:try:# Configure LLMobj_llm_config = GroqLLM(user_controls_input=user_input)model = obj_llm_config.get_llm_model()if not model:st.error("Error: LLM model could not be initialized.")return# Initialize and setup the graph based on the selected usecaseusecase = user_input.get('selected_usecase')if not usecase:st.error("Error: No use case selected")return## Graph Buildergraph_builder=GraphBuilder(model)try:graph = graph_builder.setup_graph(usecase)DisplayResultStreamlit(usecase,graph,user_message).display_result_on_ui()except Exception as e:st.error(f"Error: Graph setup failed - {e}")returnexcept Exception as e:raise ValueError(f"Error occured with Exception : {e}")
1234567891011121314151617from src.langgraph_agenticai.state.state import State
class BasicChatbotNode: """ Basic chatbot implementation """ def __init__(self, model): self.llm = model def process(self, state: State) -> dict: """ Process the input state and generates a chatbot response """ return{"messages": self.llm.invoke(state["messages"])}12345678910111213from typing import Annotated, Literal, Optionalfrom typing_extensions import TypedDictfrom langgraph.graph.message import add_messagesfrom typing import TypedDict, Annotated, Listfrom langchain_core.messages import AIMessage, HumanMessage
class State(TypedDict): """ Represents the structure of the state used in the graph
""" messages: Annotated[list, add_messages]1234567891011121314151617181920212223242526272829303132333435363738394041import streamlit as stfrom langchain_core.messages import HumanMessage,AIMessage,ToolMessageimport jsonclass DisplayResultStreamlit:def __init__(self,usecase,graph,user_message):self.usecase= usecaseself.graph = graphself.user_message = user_messagedef display_result_on_ui(self):usecase= self.usecasegraph = self.graphuser_message = self.user_messageif usecase =="Basic Chatbot":for event in graph.stream({'messages':("user",user_message)}):print(event.values())for value in event.values():print(value['messages'])with st.chat_message("user"):st.write(user_message)with st.chat_message("assistant"):st.write(value["messages"].content)elif usecase=="Chatbot with Tool":# Prepare state and invoke the graphinitial_state = {"messages": [user_message]}res = graph.invoke(initial_state)for message in res['messages']:if type(message) == HumanMessage:with st.chat_message("user"):st.write(message.content)elif type(message)==ToolMessage:with st.chat_message("ai"):st.write("Tool Call Start")st.write(message.content)st.write("Tool Call End")elif type(message)==AIMessage and message.content:with st.chat_message("assistant"):st.write(message.content)
8 unmodified lines91011128 unmodified linesclass LoadStreamlitUI:def __init__(self):self.config = Config() # configself.user_controls = {}8 unmodified lines91011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465668 unmodified linesclass LoadStreamlitUI:def __init__(self):self.config = Config() # configself.user_controls = {}def initialize_session(self):return {"current_step": "requirements","requirements": "","user_stories": "","po_feedback": "","generated_code": "","review_feedback": "","decision": None}def load_streamlit_ui(self):st.set_page_config(page_title=self.config.get_page_title(), layout="wide")st.header(self.config.get_page_title())st.session_state.timeframe = ''st.session_state.IsFetchButtonClicked = Falsest.session_state.IsSDLC = Falsewith st.sidebar:# Get options from configllm_options = self.config.get_llm_options()usecase_options = self.config.get_usecase_options()# LLM selectionself.user_controls["selected_llm"] = st.selectbox("Select LLM", llm_options)if self.user_controls["selected_llm"] == 'Groq':# Model selectionmodel_options = self.config.get_groq_model_options()self.user_controls["selected_groq_model"] = st.selectbox("Select Model", model_options)# API key inputself.user_controls["GROQ_API_KEY"] = st.session_state["GROQ_API_KEY"] = st.text_input("API Key",type="password")# Validate API keyif not self.user_controls["GROQ_API_KEY"]:st.warning("⚠️ Please enter your GROQ API key to proceed. Don't have? refer : https://console.groq.com/keys ")# Use case selectionself.user_controls["selected_usecase"] = st.selectbox("Select Usecases", usecase_options)if self.user_controls["selected_usecase"] =="Chatbot with Tool":# API key inputos.environ["TAVILY_API_KEY"] = self.user_controls["TAVILY_API_KEY"] = st.session_state["TAVILY_API_KEY"] = st.text_input("TAVILY API KEY",type="password")# Validate API keyif not self.user_controls["TAVILY_API_KEY"]:st.warning("⚠️ Please enter your TAVILY_API_KEY key to proceed. Don't have? refer : https://app.tavily.com/home")if "state" not in st.session_state:st.session_state.state = self.initialize_session()return self.user_controls
12345[DEFAULT]PAGE_TITLE = LangGraph AgenticAI ApplicationLLM_OPTIONS = Groq, OpenAIUSECASE_OPTIONS = Basic Chatbot, Chatbot with Tools, Travel Planner, AI News, SDLC Workflow, Blog Generator, Appointment ReceptionistGROQ_MODEL_OPTIONS = mixtral-8x7b-32768, llama3-8b-8192, llama3-70b-8192, gemma-7b-i12345[DEFAULT]PAGE_TITLE = LangGraph: AgenticAI Application UsecasesLLM_OPTIONS = Groq, OpenAIUSECASE_OPTIONS = Basic Chatbot, Chatbot with Tools, Travel Planner, AI News, SDLC Workflow, Blog Generator, Appointment ReceptionistGROQ_MODEL_OPTIONS = gemma2-9b-it, llama3-8b-8192, llama3-70b-8192
123456789101112131415161718from configparser import ConfigParserclass Config:def __init__(self,config_file=".src/langgraph_agenticai/ui/uiconfigfile.py"):self.config = ConfigParser()self.config.read(config_file)def get_llm_options(self):return self.config['DEFAULT'].get('LLM_OPTIONS').split(',')def get_usecase_options(self):return self.config['DEFAULT'].get('USECASE_OPTIONS').split(',')def get_groq_model_options(self):return self.config['DEFAULT'].get('GROQ_MODEL_OPTIONS').split(',')def get_page_title(self):return self.config['DEFAULT'].get('PAGE_TITLE')123456789101112131415161718from configparser import ConfigParserclass Config:def __init__(self,config_file="src/langgraph_agenticai/ui/uiconfigfile.ini"):self.config=ConfigParser()self.config.read(config_file)def get_llm_options(self):return self.config["DEFAULT"].get("LLM_OPTIONS").split(", ")def get_usecase_options(self):return self.config["DEFAULT"].get("USECASE_OPTIONS").split(", ")def get_groq_model_options(self):return self.config["DEFAULT"].get("GROQ_MODEL_OPTIONS").split(", ")def get_page_title(self):return self.config["DEFAULT"].get("PAGE_TITLE")
app.py+5
src/langgraph_agenticai/LLMS/groqllm.py+21
src/langgraph_agenticai/graph/graph_builder.pyAdded+39
src/langgraph_agenticai/main.py+61
src/langgraph_agenticai/nodes/basic_chatbot_node.pyAdded+17
src/langgraph_agenticai/state/state.pyAdded+13
src/langgraph_agenticai/ui/streamlit_ui/display_result.py+41
src/langgraph_agenticai/ui/streamlit_ui/loadui.py+55-1
src/langgraph_agenticai/ui/uiconfigfile.ini+2-2
src/langgraph_agenticai/ui/uiconfigfile.py+9-9