Kiki0203 commited on
Commit
29f5753
Β·
verified Β·
1 Parent(s): 7fd2ec5

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -74
app.py CHANGED
@@ -1,13 +1,13 @@
1
  """
2
- LangGraph + Groq + Gradio General Assistant Chatbot
3
- Ready for Hugging Face Spaces (no audioop dependency)
4
  """
5
 
6
  import os
7
- import gradio as gr
8
  from typing import Annotated
9
  from typing_extensions import TypedDict
10
 
 
11
  from langchain_groq import ChatGroq
12
  from langchain_core.messages import HumanMessage, AIMessage, SystemMessage, BaseMessage
13
  from langgraph.graph import StateGraph, START, END
@@ -30,21 +30,18 @@ def build_graph(api_key: str, model: str, system_prompt: str):
30
  )
31
 
32
  def chatbot_node(state: State) -> dict:
33
- messages = state["messages"]
34
- # Prepend system message each call (stateless node)
35
- full_messages = [SystemMessage(content=system_prompt)] + messages
36
  response = llm.invoke(full_messages)
37
  return {"messages": [response]}
38
 
39
- graph_builder = StateGraph(State)
40
- graph_builder.add_node("chatbot", chatbot_node)
41
- graph_builder.add_edge(START, "chatbot")
42
- graph_builder.add_edge("chatbot", END)
43
-
44
- return graph_builder.compile()
45
 
46
 
47
- # ── Gradio chat function ─────────────────────────────────────────────────────
48
 
49
  def respond(
50
  message: str,
@@ -55,14 +52,14 @@ def respond(
55
  max_history: int,
56
  ):
57
  if not api_key.strip():
58
- yield "⚠️ Please enter your Groq API key in the sidebar."
59
  return
60
 
61
  if not message.strip():
62
  yield ""
63
  return
64
 
65
- # Convert Gradio history β†’ LangChain messages
66
  lc_messages: list[BaseMessage] = []
67
  for entry in history[-(max_history * 2):]:
68
  if entry["role"] == "user":
@@ -76,13 +73,12 @@ def respond(
76
 
77
  try:
78
  result = graph.invoke({"messages": lc_messages})
79
- ai_msg = result["messages"][-1]
80
- yield ai_msg.content
81
  except Exception as e:
82
  yield f"❌ Error: {str(e)}"
83
 
84
 
85
- # ── UI ───────────────────────────────────────────────────────────────────────
86
 
87
  MODELS = [
88
  "llama-3.3-70b-versatile",
@@ -96,83 +92,56 @@ DEFAULT_SYSTEM = (
96
  "Answer clearly and concisely. If you don't know something, say so honestly."
97
  )
98
 
 
 
99
  with gr.Blocks(
100
  title="LangGraph Γ— Groq Assistant",
101
  theme=gr.themes.Soft(primary_hue="violet", neutral_hue="slate"),
102
- css="""
103
- #col-left { border-right: 1px solid #e2e8f0; }
104
- .gr-button-primary { background: linear-gradient(135deg, #7c3aed, #4f46e5) !important; }
105
- footer { display: none !important; }
106
- """,
107
  ) as demo:
108
 
 
109
  gr.Markdown(
110
- """
111
- # πŸ€– LangGraph Γ— Groq Assistant
112
- A stateful conversational AI powered by **LangGraph** graphs and **Groq** inference.
113
- """
114
  )
115
 
116
- with gr.Row():
117
- # ── Sidebar ──────────────────────────────────────────────────────────
118
- with gr.Column(scale=1, elem_id="col-left"):
119
- gr.Markdown("### βš™οΈ Configuration")
120
-
121
- api_key = gr.Textbox(
 
 
 
 
 
 
 
 
122
  label="Groq API Key",
123
  placeholder="gsk_...",
124
  type="password",
125
  info="Get yours free at console.groq.com",
126
- )
127
-
128
- model = gr.Dropdown(
129
  choices=MODELS,
130
  value=MODELS[0],
131
  label="Model",
132
- )
133
-
134
- system_prompt = gr.Textbox(
135
  label="System Prompt",
136
  value=DEFAULT_SYSTEM,
137
- lines=4,
138
- info="Persona / instructions for the assistant",
139
- )
140
-
141
- max_history = gr.Slider(
142
  minimum=1,
143
  maximum=20,
144
  value=10,
145
  step=1,
146
  label="Max history turns",
147
- info="How many past turns to include in context",
148
- )
149
-
150
- gr.Markdown(
151
- """
152
- ---
153
- **Stack**
154
- - πŸ”— [LangGraph](https://github.com/langchain-ai/langgraph)
155
- - ⚑ [Groq](https://groq.com)
156
- - πŸ–₯️ [Gradio](https://gradio.app)
157
- """
158
- )
159
-
160
- # ── Chat ─────────────────────────────────────────────────────────────
161
- with gr.Column(scale=3):
162
- chatbot = gr.ChatInterface(
163
- fn=respond,
164
- type="messages",
165
- additional_inputs=[api_key, model, system_prompt, max_history],
166
- examples=[
167
- ["What is LangGraph and how does it differ from LangChain?"],
168
- ["Explain quantum entanglement in simple terms."],
169
- ["Write a short Python function to reverse a linked list."],
170
- ["What are the pros and cons of microservices architecture?"],
171
- ],
172
- submit_btn="Send ➀",
173
- retry_btn="πŸ” Retry",
174
- undo_btn="↩ Undo",
175
- clear_btn="πŸ—‘οΈ Clear",
176
- )
177
 
178
  demo.launch()
 
1
  """
2
+ LangGraph + Groq + Gradio 5 General Assistant Chatbot
3
+ Ready for Hugging Face Spaces (Python 3.13 compatible)
4
  """
5
 
6
  import os
 
7
  from typing import Annotated
8
  from typing_extensions import TypedDict
9
 
10
+ import gradio as gr
11
  from langchain_groq import ChatGroq
12
  from langchain_core.messages import HumanMessage, AIMessage, SystemMessage, BaseMessage
13
  from langgraph.graph import StateGraph, START, END
 
30
  )
31
 
32
  def chatbot_node(state: State) -> dict:
33
+ full_messages = [SystemMessage(content=system_prompt)] + state["messages"]
 
 
34
  response = llm.invoke(full_messages)
35
  return {"messages": [response]}
36
 
37
+ builder = StateGraph(State)
38
+ builder.add_node("chatbot", chatbot_node)
39
+ builder.add_edge(START, "chatbot")
40
+ builder.add_edge("chatbot", END)
41
+ return builder.compile()
 
42
 
43
 
44
+ # ── Chat function ─────────────────────────────────────────────────────────────
45
 
46
  def respond(
47
  message: str,
 
52
  max_history: int,
53
  ):
54
  if not api_key.strip():
55
+ yield "⚠️ Please enter your Groq API key in the settings panel below."
56
  return
57
 
58
  if not message.strip():
59
  yield ""
60
  return
61
 
62
+ # Convert Gradio openai-style history β†’ LangChain messages
63
  lc_messages: list[BaseMessage] = []
64
  for entry in history[-(max_history * 2):]:
65
  if entry["role"] == "user":
 
73
 
74
  try:
75
  result = graph.invoke({"messages": lc_messages})
76
+ yield result["messages"][-1].content
 
77
  except Exception as e:
78
  yield f"❌ Error: {str(e)}"
79
 
80
 
81
+ # ── Constants ─────────────────────────────────────────────────────────────────
82
 
83
  MODELS = [
84
  "llama-3.3-70b-versatile",
 
92
  "Answer clearly and concisely. If you don't know something, say so honestly."
93
  )
94
 
95
+ # ── UI ────────────────────────────────────────────────────────────────────────
96
+
97
  with gr.Blocks(
98
  title="LangGraph Γ— Groq Assistant",
99
  theme=gr.themes.Soft(primary_hue="violet", neutral_hue="slate"),
 
 
 
 
 
100
  ) as demo:
101
 
102
+ gr.Markdown("# πŸ€– LangGraph Γ— Groq Assistant")
103
  gr.Markdown(
104
+ "A stateful conversational AI powered by **LangGraph** graphs and **Groq** inference."
 
 
 
105
  )
106
 
107
+ # Gradio 5 ChatInterface β€” retry/undo/clear are built into the Chatbot widget,
108
+ # submit_btn takes a str (not gr.Button), no retry_btn/undo_btn/clear_btn params.
109
+ chat = gr.ChatInterface(
110
+ fn=respond,
111
+ type="messages",
112
+ submit_btn="Send ➀",
113
+ examples=[
114
+ "What is LangGraph and how does it differ from LangChain?",
115
+ "Explain quantum entanglement in simple terms.",
116
+ "Write a short Python function to reverse a linked list.",
117
+ "What are the pros and cons of microservices architecture?",
118
+ ],
119
+ additional_inputs=[
120
+ gr.Textbox(
121
  label="Groq API Key",
122
  placeholder="gsk_...",
123
  type="password",
124
  info="Get yours free at console.groq.com",
125
+ ),
126
+ gr.Dropdown(
 
127
  choices=MODELS,
128
  value=MODELS[0],
129
  label="Model",
130
+ ),
131
+ gr.Textbox(
 
132
  label="System Prompt",
133
  value=DEFAULT_SYSTEM,
134
+ lines=3,
135
+ ),
136
+ gr.Slider(
 
 
137
  minimum=1,
138
  maximum=20,
139
  value=10,
140
  step=1,
141
  label="Max history turns",
142
+ ),
143
+ ],
144
+ additional_inputs_accordion=gr.Accordion(label="βš™οΈ Settings", open=False),
145
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
 
147
  demo.launch()