msaifee commited on
Commit
bf6abd3
·
1 Parent(s): 6469ed2

Basic Agentic AI Chatbot

Browse files
app.py CHANGED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from src.langgraph_agenticai.main import load_langgraph_agenticai_app
2
+
3
+
4
+ if __name__=="__main__":
5
+ load_langgraph_agenticai_app()
src/langgraph_agenticai/LLMS/groqllm.py CHANGED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import streamlit as st
3
+ from langchain_groq import ChatGroq
4
+
5
+
6
+ class GroqLLM:
7
+ def __init__(self, user_controls_input):
8
+ self.user_controls_input = user_controls_input
9
+
10
+
11
+ def get_llm_model(self):
12
+ try:
13
+ groq_api_key = self.user_controls_input['GROQ_API_KEY']
14
+ selected_groq_model = self.user_controls_input['selected_groq_model']
15
+
16
+ llm = ChatGroq(api_key=groq_api_key, model= selected_groq_model)
17
+
18
+ except Exception as e:
19
+ raise ValueError(f"Error occured with Exception : {e}")
20
+
21
+ return llm
src/langgraph_agenticai/graph/graph_builder.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langgraph.graph import StateGraph,START, END, MessagesState
2
+ from langgraph.prebuilt import tools_condition, ToolNode
3
+ from langchain_core.prompts import ChatPromptTemplate
4
+ from src.langgraph_agenticai.state.state import State
5
+ from src.langgraph_agenticai.nodes.basic_chatbot_node import BasicChatbotNode
6
+
7
+ class GraphBuilder:
8
+
9
+ def __init__(self, model):
10
+ self.llm = model
11
+ self.graph_builder = StateGraph(State)
12
+
13
+
14
+ def basic_chatbot_build_graph(self):
15
+
16
+ """
17
+ Builds a basic chatbot graph using LangGraph.
18
+ This method initializes a chatbot node using the `BasicChatbotNode` class
19
+ and integrates it into the graph. The chatbot node is set as both the
20
+ entry and exit point of the graph.
21
+ """
22
+
23
+ self.basic_chatbot_node = BasicChatbotNode(self.llm)
24
+ self.graph_builder.add_node("chatbot", self.basic_chatbot_node.process)
25
+ self.graph_builder.add_edge(START, "chatbot")
26
+ self.graph_builder.add_edge("chatbot", END)
27
+
28
+
29
+ def setup_graph(self, usecase: str):
30
+ """
31
+ Sets up the graph for the selected use case.
32
+ """
33
+ if usecase == "Basic Chatbot":
34
+ self.basic_chatbot_build_graph()
35
+
36
+ if usecase == "Chatbot with Tool":
37
+ # self.chatbot_with_tools_build_graph()
38
+ pass
39
+ return self.graph_builder.compile()
src/langgraph_agenticai/main.py CHANGED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import json
3
+ from src.langgraph_agenticai.ui.streamlit_ui.loadui import LoadStreamlitUI
4
+ from src.langgraph_agenticai.LLMS.groqllm import GroqLLM
5
+ from src.langgraph_agenticai.graph.graph_builder import GraphBuilder
6
+ from src.langgraph_agenticai.ui.streamlit_ui.display_result import DisplayResultStreamlit
7
+
8
+ # MAIN Function START
9
+ def load_langgraph_agenticai_app():
10
+ """
11
+ Loads and runs the LangGraph AgenticAI application with Streamlit UI.
12
+ This function initializes the UI, handles user input, configures the LLM model,
13
+ sets up the graph based on the selected use case, and displays the output while
14
+ implementing exception handling for robustness.
15
+ """
16
+
17
+ # Load UI
18
+ ui = LoadStreamlitUI()
19
+ user_input = ui.load_streamlit_ui()
20
+
21
+ if not user_input:
22
+ st.error("Error: Failed to load user input from the UI.")
23
+ return
24
+
25
+ # Text input for user message
26
+ if st.session_state.IsFetchButtonClicked:
27
+ user_message = st.session_state.timeframe
28
+ else :
29
+ user_message = st.chat_input("Enter your message:")
30
+
31
+
32
+ if user_message:
33
+ try:
34
+ # Configure LLM
35
+ obj_llm_config = GroqLLM(user_controls_input=user_input)
36
+ model = obj_llm_config.get_llm_model()
37
+
38
+ if not model:
39
+ st.error("Error: LLM model could not be initialized.")
40
+ return
41
+
42
+ # Initialize and setup the graph based on the selected usecase
43
+ usecase = user_input.get('selected_usecase')
44
+ if not usecase:
45
+ st.error("Error: No use case selected")
46
+ return
47
+
48
+ ## Graph Builder
49
+ graph_builder=GraphBuilder(model)
50
+ try:
51
+ graph = graph_builder.setup_graph(usecase)
52
+ DisplayResultStreamlit(usecase,graph,user_message).display_result_on_ui()
53
+ except Exception as e:
54
+ st.error(f"Error: Graph setup failed - {e}")
55
+ return
56
+
57
+ except Exception as e:
58
+ raise ValueError(f"Error occured with Exception : {e}")
59
+
60
+
61
+
src/langgraph_agenticai/nodes/basic_chatbot_node.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from src.langgraph_agenticai.state.state import State
2
+
3
+ class BasicChatbotNode:
4
+ """
5
+ Basic chatbot implementation
6
+
7
+ """
8
+
9
+ def __init__(self, model):
10
+ self.llm = model
11
+
12
+ def process(self, state: State) -> dict:
13
+ """
14
+ Process the input state and generates a chatbot response
15
+ """
16
+
17
+ return{"messages": self.llm.invoke(state["messages"])}
src/langgraph_agenticai/state/state.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Annotated, Literal, Optional
2
+ from typing_extensions import TypedDict
3
+ from langgraph.graph.message import add_messages
4
+ from typing import TypedDict, Annotated, List
5
+ from langchain_core.messages import AIMessage, HumanMessage
6
+
7
+ class State(TypedDict):
8
+ """
9
+ Represents the structure of the state used in the graph
10
+
11
+ """
12
+
13
+ messages: Annotated[list, add_messages]
src/langgraph_agenticai/ui/streamlit_ui/display_result.py CHANGED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from langchain_core.messages import HumanMessage,AIMessage,ToolMessage
3
+ import json
4
+
5
+
6
+ class DisplayResultStreamlit:
7
+ def __init__(self,usecase,graph,user_message):
8
+ self.usecase= usecase
9
+ self.graph = graph
10
+ self.user_message = user_message
11
+
12
+ def display_result_on_ui(self):
13
+ usecase= self.usecase
14
+ graph = self.graph
15
+ user_message = self.user_message
16
+ if usecase =="Basic Chatbot":
17
+ for event in graph.stream({'messages':("user",user_message)}):
18
+ print(event.values())
19
+ for value in event.values():
20
+ print(value['messages'])
21
+ with st.chat_message("user"):
22
+ st.write(user_message)
23
+ with st.chat_message("assistant"):
24
+ st.write(value["messages"].content)
25
+
26
+ elif usecase=="Chatbot with Tool":
27
+ # Prepare state and invoke the graph
28
+ initial_state = {"messages": [user_message]}
29
+ res = graph.invoke(initial_state)
30
+ for message in res['messages']:
31
+ if type(message) == HumanMessage:
32
+ with st.chat_message("user"):
33
+ st.write(message.content)
34
+ elif type(message)==ToolMessage:
35
+ with st.chat_message("ai"):
36
+ st.write("Tool Call Start")
37
+ st.write(message.content)
38
+ st.write("Tool Call End")
39
+ elif type(message)==AIMessage and message.content:
40
+ with st.chat_message("assistant"):
41
+ st.write(message.content)
src/langgraph_agenticai/ui/streamlit_ui/loadui.py CHANGED
@@ -9,4 +9,58 @@ from src.langgraph_agenticai.ui.uiconfigfile import Config
9
  class LoadStreamlitUI:
10
  def __init__(self):
11
  self.config = Config() # config
12
- self.user_controls = {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  class LoadStreamlitUI:
10
  def __init__(self):
11
  self.config = Config() # config
12
+ self.user_controls = {}
13
+
14
+ def initialize_session(self):
15
+ return {
16
+ "current_step": "requirements",
17
+ "requirements": "",
18
+ "user_stories": "",
19
+ "po_feedback": "",
20
+ "generated_code": "",
21
+ "review_feedback": "",
22
+ "decision": None
23
+ }
24
+
25
+ def load_streamlit_ui(self):
26
+ st.set_page_config(page_title=self.config.get_page_title(), layout="wide")
27
+ st.header(self.config.get_page_title())
28
+ st.session_state.timeframe = ''
29
+ st.session_state.IsFetchButtonClicked = False
30
+ st.session_state.IsSDLC = False
31
+
32
+ with st.sidebar:
33
+ # Get options from config
34
+ llm_options = self.config.get_llm_options()
35
+ usecase_options = self.config.get_usecase_options()
36
+
37
+ # LLM selection
38
+ self.user_controls["selected_llm"] = st.selectbox("Select LLM", llm_options)
39
+
40
+ if self.user_controls["selected_llm"] == 'Groq':
41
+ # Model selection
42
+ model_options = self.config.get_groq_model_options()
43
+ self.user_controls["selected_groq_model"] = st.selectbox("Select Model", model_options)
44
+ # API key input
45
+ self.user_controls["GROQ_API_KEY"] = st.session_state["GROQ_API_KEY"] = st.text_input("API Key",
46
+ type="password")
47
+ # Validate API key
48
+ if not self.user_controls["GROQ_API_KEY"]:
49
+ st.warning("⚠️ Please enter your GROQ API key to proceed. Don't have? refer : https://console.groq.com/keys ")
50
+
51
+
52
+ # Use case selection
53
+ self.user_controls["selected_usecase"] = st.selectbox("Select Usecases", usecase_options)
54
+
55
+ if self.user_controls["selected_usecase"] =="Chatbot with Tool":
56
+ # API key input
57
+ os.environ["TAVILY_API_KEY"] = self.user_controls["TAVILY_API_KEY"] = st.session_state["TAVILY_API_KEY"] = st.text_input("TAVILY API KEY",
58
+ type="password")
59
+ # Validate API key
60
+ if not self.user_controls["TAVILY_API_KEY"]:
61
+ st.warning("⚠️ Please enter your TAVILY_API_KEY key to proceed. Don't have? refer : https://app.tavily.com/home")
62
+
63
+ if "state" not in st.session_state:
64
+ st.session_state.state = self.initialize_session()
65
+
66
+ return self.user_controls
src/langgraph_agenticai/ui/uiconfigfile.ini CHANGED
@@ -1,5 +1,5 @@
1
  [DEFAULT]
2
- PAGE_TITLE = LangGraph AgenticAI Application
3
  LLM_OPTIONS = Groq, OpenAI
4
  USECASE_OPTIONS = Basic Chatbot, Chatbot with Tools, Travel Planner, AI News, SDLC Workflow, Blog Generator, Appointment Receptionist
5
- GROQ_MODEL_OPTIONS = mixtral-8x7b-32768, llama3-8b-8192, llama3-70b-8192, gemma-7b-i
 
1
  [DEFAULT]
2
+ PAGE_TITLE = LangGraph: AgenticAI Application Usecases
3
  LLM_OPTIONS = Groq, OpenAI
4
  USECASE_OPTIONS = Basic Chatbot, Chatbot with Tools, Travel Planner, AI News, SDLC Workflow, Blog Generator, Appointment Receptionist
5
+ GROQ_MODEL_OPTIONS = gemma2-9b-it, llama3-8b-8192, llama3-70b-8192
src/langgraph_agenticai/ui/uiconfigfile.py CHANGED
@@ -1,18 +1,18 @@
1
  from configparser import ConfigParser
2
 
3
  class Config:
4
- def __init__(self,config_file=".src/langgraph_agenticai/ui/uiconfigfile.py"):
5
- self.config = ConfigParser()
6
  self.config.read(config_file)
7
-
8
  def get_llm_options(self):
9
- return self.config['DEFAULT'].get('LLM_OPTIONS').split(',')
10
 
11
  def get_usecase_options(self):
12
- return self.config['DEFAULT'].get('USECASE_OPTIONS').split(',')
13
-
14
  def get_groq_model_options(self):
15
- return self.config['DEFAULT'].get('GROQ_MODEL_OPTIONS').split(',')
16
-
17
  def get_page_title(self):
18
- return self.config['DEFAULT'].get('PAGE_TITLE')
 
1
  from configparser import ConfigParser
2
 
3
  class Config:
4
+ def __init__(self,config_file="src/langgraph_agenticai/ui/uiconfigfile.ini"):
5
+ self.config=ConfigParser()
6
  self.config.read(config_file)
7
+
8
  def get_llm_options(self):
9
+ return self.config["DEFAULT"].get("LLM_OPTIONS").split(", ")
10
 
11
  def get_usecase_options(self):
12
+ return self.config["DEFAULT"].get("USECASE_OPTIONS").split(", ")
13
+
14
  def get_groq_model_options(self):
15
+ return self.config["DEFAULT"].get("GROQ_MODEL_OPTIONS").split(", ")
16
+
17
  def get_page_title(self):
18
+ return self.config["DEFAULT"].get("PAGE_TITLE")