APRG commited on
Commit
e2599e3
verified
1 Parent(s): 333ab4f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +294 -59
app.py CHANGED
@@ -1,64 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
  )
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
1
+ #pip install langchain_google_genai langgraph gradio
2
+ import os
3
+ import typing
4
+ from typing import Annotated, Literal, Iterable
5
+ from typing_extensions import TypedDict
6
+
7
+ from langchain_google_genai import ChatGoogleGenerativeAI
8
+ from langgraph.graph import StateGraph, START, END
9
+ from langgraph.graph.message import add_messages
10
+ from langgraph.prebuilt import ToolNode
11
+ from langchain_core.tools import tool
12
+ from langchain_core.messages import AIMessage, ToolMessage, HumanMessage, BaseMessage, SystemMessage
13
+ from random import randint
14
+
15
+ from tkinter import messagebox
16
+ #messagebox.showinfo("Test", "Script run successfully")
17
+
18
  import gradio as gr
19
+ import logging
20
+
21
+ class OrderState(TypedDict):
22
+ """State representing the customer's order conversation."""
23
+ messages: Annotated[list, add_messages]
24
+ order: list[str]
25
+ finished: bool
26
+
27
+ # System instruction for the BaristaBot
28
+ BARISTABOT_SYSINT = (
29
+ "system",
30
+ "You are a BaristaBot, an interactive cafe ordering system. A human will talk to you about the "
31
+ "available products. Answer questions about menu items, help customers place orders, and "
32
+ "confirm details before finalizing. Use the provided tools to manage the order."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  )
34
 
35
+ WELCOME_MSG = "Welcome to the BaristaBot cafe. Type `q` to quit. How may I serve you today?"
36
+
37
+ # Initialize the Google Gemini LLM
38
+ llm = ChatGoogleGenerativeAI(model="gemini-1.5-flash-latest")
39
+
40
+ @tool
41
+ def get_menu() -> str:
42
+ """Provide the cafe menu."""
43
+ #messagebox.showinfo("Test", "Script run successfully")
44
+ with open("menu.txt", 'r', encoding = "UTF-8") as f:
45
+ return f.read()
46
+
47
+ @tool
48
+ def add_to_order(drink: str, modifiers: Iterable[str] = []) -> str:
49
+ """Adds the specified drink to the customer's order."""
50
+ return f"{drink} ({', '.join(modifiers) if modifiers else 'no modifiers'})"
51
+
52
+ @tool
53
+ def confirm_order() -> str:
54
+ """Asks the customer to confirm the order."""
55
+ return "Order confirmation requested"
56
+
57
+ @tool
58
+ def get_order() -> str:
59
+ """Returns the current order."""
60
+ return "Current order details requested"
61
+
62
+ @tool
63
+ def clear_order() -> str:
64
+ """Clears the current order."""
65
+ return "Order cleared"
66
+
67
+ @tool
68
+ def place_order() -> int:
69
+ """Sends the order to the kitchen."""
70
+ messagebox.showinfo("Test", "Order successful!")
71
+ return randint(2, 10) # Estimated wait time
72
+
73
+ def chatbot_with_tools(state: OrderState) -> OrderState:
74
+ """Chatbot with tool handling."""
75
+ logging.info(f"Messagelist sent to chatbot node: {[msg.content for msg in state.get('messages', [])]}")
76
+ defaults = {"order": [], "finished": False}
77
+
78
+ # Ensure we always have at least a system message
79
+ if not state.get("messages", []):
80
+ new_output = AIMessage(content=WELCOME_MSG)
81
+ return defaults | state | {"messages": [SystemMessage(content=BARISTABOT_SYSINT), new_output]}
82
+
83
+ try:
84
+ # Prepend system instruction if not already present
85
+ messages_with_system = [
86
+ SystemMessage(content=BARISTABOT_SYSINT)
87
+ ] + state.get("messages", [])
88
+
89
+ # Process messages through the LLM
90
+ new_output = llm_with_tools.invoke(messages_with_system)
91
+
92
+ return defaults | state | {"messages": [new_output]}
93
+ except Exception as e:
94
+ # Fallback if LLM processing fails
95
+ return defaults | state | {"messages": [AIMessage(content=f"I'm having trouble processing that. {str(e)}")]}
96
+
97
+ def order_node(state: OrderState) -> OrderState:
98
+ """Handles order-related tool calls."""
99
+ logging.info("order node")
100
+ tool_msg = state.get("messages", [])[-1]
101
+ order = state.get("order", [])
102
+ outbound_msgs = []
103
+ order_placed = False
104
+
105
+ for tool_call in tool_msg.tool_calls:
106
+ tool_name = tool_call["name"]
107
+ tool_args = tool_call["args"]
108
+
109
+ if tool_name == "add_to_order":
110
+ modifiers = tool_args.get("modifiers", [])
111
+ modifier_str = ", ".join(modifiers) if modifiers else "no modifiers"
112
+ order.append(f'{tool_args["drink"]} ({modifier_str})')
113
+ response = "\n".join(order)
114
+
115
+ elif tool_name == "confirm_order":
116
+ response = "Your current order:\n" + "\n".join(order) + "\nIs this correct?"
117
+
118
+ elif tool_name == "get_order":
119
+ response = "\n".join(order) if order else "(no order)"
120
+
121
+ elif tool_name == "clear_order":
122
+ order.clear()
123
+ response = "Order cleared"
124
+
125
+ elif tool_name == "place_order":
126
+ order_text = "\n".join(order)
127
+ order_placed = True
128
+ response = f"Order placed successfully!\nYour order:\n{order_text}\nEstimated wait: {randint(2, 10)} minutes"
129
+
130
+ else:
131
+ raise NotImplementedError(f'Unknown tool call: {tool_name}')
132
+
133
+ outbound_msgs.append(
134
+ ToolMessage(
135
+ content=response,
136
+ name=tool_name,
137
+ tool_call_id=tool_call["id"],
138
+ )
139
+ )
140
+
141
+ return {"messages": outbound_msgs, "order": order, "finished": order_placed}
142
+
143
+ def maybe_route_to_tools(state: OrderState) -> str:
144
+ """Route between chat and tool nodes."""
145
+ if not (msgs := state.get("messages", [])):
146
+ raise ValueError(f"No messages found when parsing state: {state}")
147
+
148
+ msg = msgs[-1]
149
+
150
+ if state.get("finished", False):
151
+ logging.info("from chatbot GOTO End node")
152
+ return END
153
+
154
+ elif hasattr(msg, "tool_calls") and len(msg.tool_calls) > 0:
155
+ if any(tool["name"] in tool_node.tools_by_name.keys() for tool in msg.tool_calls):
156
+ logging.info("from chatbot GOTO tools node")
157
+ return "tools"
158
+ else:
159
+ logging.info("from chatbot GOTO order node")
160
+ return "ordering"
161
+
162
+ else:
163
+ logging.info("from chatbot GOTO human node")
164
+ return "human"
165
+
166
+ def human_node(state: OrderState) -> OrderState:
167
+ """Handle user input."""
168
+ logging.info(f"Messagelist sent to human node: {[msg.content for msg in state.get('messages', [])]}")
169
+ last_msg = state["messages"][-1]
170
+
171
+ if last_msg.content.lower() in {"q", "quit", "exit", "goodbye"}:
172
+ state["finished"] = True
173
+
174
+ return state
175
+
176
+ def maybe_exit_human_node(state: OrderState) -> Literal["chatbot", "__end__"]:
177
+ """Determine if conversation should continue."""
178
+ if state.get("finished", False):
179
+ logging.info("from human GOTO End node")
180
+ return END
181
+ last_msg = state["messages"][-1]
182
+ if isinstance(last_msg, AIMessage):
183
+ logging.info("Chatbot response obtained, ending conversation")
184
+ return END
185
+ else:
186
+ logging.info("from human GOTO chatbot node")
187
+ return "chatbot"
188
+
189
+ # Prepare tools
190
+ auto_tools = [get_menu]
191
+ tool_node = ToolNode(auto_tools)
192
+
193
+ order_tools = [add_to_order, confirm_order, get_order, clear_order, place_order]
194
+
195
+ # Bind all tools to the LLM
196
+ llm_with_tools = llm.bind_tools(auto_tools + order_tools)
197
+
198
+ # Build the graph
199
+ graph_builder = StateGraph(OrderState)
200
+
201
+ # Add nodes
202
+ graph_builder.add_node("chatbot", chatbot_with_tools)
203
+ graph_builder.add_node("human", human_node)
204
+ graph_builder.add_node("tools", tool_node)
205
+ graph_builder.add_node("ordering", order_node)
206
+
207
+ # Add edges and routing
208
+ graph_builder.add_conditional_edges("chatbot", maybe_route_to_tools)
209
+ graph_builder.add_conditional_edges("human", maybe_exit_human_node)
210
+ graph_builder.add_edge("tools", "chatbot")
211
+ graph_builder.add_edge("ordering", "chatbot")
212
+ graph_builder.add_edge(START, "human")
213
+
214
+ # Compile the graph
215
+ chat_graph = graph_builder.compile()
216
+
217
+ def convert_history_to_messages(history: list) -> list[BaseMessage]:
218
+ """
219
+ Convert Gradio chat history to a list of Langchain messages.
220
+
221
+ Args:
222
+ - history: Gradio's chat history format
223
+
224
+ Returns:
225
+ - List of Langchain BaseMessage objects
226
+ """
227
+ messages = []
228
+ for human, ai in history:
229
+ if human:
230
+ messages.append(HumanMessage(content=human))
231
+ if ai:
232
+ messages.append(AIMessage(content=ai))
233
+ return messages
234
+
235
+ def gradio_chat(message: str, history: list) -> str:
236
+ """
237
+ Gradio-compatible chat function that manages the conversation state.
238
+
239
+ Args:
240
+ - message: User's input message
241
+ - history: Gradio's chat history
242
+
243
+ Returns:
244
+ - Bot's response as a string
245
+ """
246
+ logging.info(f"{len(history)} history so far: {history}")
247
+ # Ensure non-empty message
248
+ if not message or message.strip() == "":
249
+ message = "Hello, how can I help you today?"
250
+
251
+ # Convert history to Langchain messages
252
+ conversation_messages = []
253
+ for old_message in history:
254
+ if old_message["content"].strip():
255
+ if old_message["role"] == "user":
256
+ conversation_messages.append(HumanMessage(content=old_message["content"]))
257
+ if old_message["role"] == "assistant":
258
+ conversation_messages.append(AIMessage(content=old_message["content"]))
259
+
260
+ # Add current message
261
+ conversation_messages.append(HumanMessage(content=message))
262
+
263
+ # Create initial state with conversation history
264
+ conversation_state = {
265
+ "messages": conversation_messages,
266
+ "order": [],
267
+ "finished": False
268
+ }
269
+ logging.info(f"Conversation so far: {str(conversation_state)}")
270
+ try:
271
+ # Process the conversation through the graph
272
+ conversation_state = chat_graph.invoke(conversation_state, {"recursion_limit": 10})
273
+
274
+ # Extract the latest bot message
275
+ latest_message = conversation_state["messages"][-1]
276
+
277
+ # Return the bot's response content
278
+ logging.info(f"return: {latest_message.content}")
279
+ return latest_message.content
280
+
281
+ except Exception as e:
282
+ return f"An error occurred: {str(e)}"
283
+
284
+ # Gradio interface
285
+ def launch_baristabot():
286
+ gr.ChatInterface(
287
+ gradio_chat,
288
+ type="messages",
289
+ title="BaristaBot",
290
+ description="Your friendly AI cafe assistant",
291
+ theme="ocean"
292
+ ).launch()
293
 
294
  if __name__ == "__main__":
295
+ # initiate logging tool
296
+ logging.basicConfig(filename='log.log',
297
+ level=logging.INFO,
298
+ format='%(asctime)s - %(levelname)s - %(message)s')
299
+ launch_baristabot()