DexterSptizu commited on
Commit
3720552
·
verified ·
1 Parent(s): f767699

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -20
app.py CHANGED
@@ -1,7 +1,7 @@
1
  import os
2
  import gradio as gr
3
  from langchain_openai import ChatOpenAI
4
- from langchain_core.messages import HumanMessage
5
  from langgraph.checkpoint.memory import MemorySaver
6
  from langgraph.graph import START, MessagesState, StateGraph
7
 
@@ -11,7 +11,7 @@ def create_chat_app(api_key):
11
  model="gpt-4o-mini",
12
  api_key=api_key,
13
  temperature=0
14
- )[1]
15
 
16
  # Define the graph
17
  workflow = StateGraph(state_schema=MessagesState)
@@ -19,38 +19,53 @@ def create_chat_app(api_key):
19
  # Define the function that calls the model
20
  def call_model(state: MessagesState):
21
  response = llm.invoke(state["messages"])
22
- return {"messages": response}[1]
23
 
24
  # Add node and edge to graph
25
  workflow.add_edge(START, "model")
26
- workflow.add_node("model", call_model)[1]
27
 
28
  # Add memory
29
  memory = MemorySaver()
30
- return workflow.compile(checkpointer=memory)[1]
31
 
32
  def chat(message, history, api_key, thread_id):
33
  if not api_key:
34
- return "Please enter your OpenAI API key first."
35
 
36
  try:
37
- # Create chat application if not exists
38
  app = create_chat_app(api_key)
39
 
40
  # Configure thread
41
- config = {"configurable": {"thread_id": thread_id}}[1]
42
 
43
- # Prepare input message
44
- input_messages = [HumanMessage(message)]
 
 
 
 
 
 
 
 
45
 
46
  # Get response
47
- output = app.invoke({"messages": input_messages}, config)[1]
 
 
 
 
 
48
 
49
- return output["messages"][-1].content
50
  except Exception as e:
51
- return f"Error: {str(e)}"
 
 
 
52
 
53
- # Create Gradio interface
54
  with gr.Blocks() as demo:
55
  gr.Markdown("# LangChain Chat with Message History")
56
 
@@ -66,10 +81,15 @@ with gr.Blocks() as demo:
66
  placeholder="Enter a unique thread ID"
67
  )
68
 
69
- chatbot = gr.ChatInterface(
70
- fn=lambda message, history: chat(message, history, api_key.value, thread_id.value),
71
- title="Chat with GPT-4o-mini"
72
- )[2]
 
 
 
 
 
73
 
74
- # Launch the application
75
- demo.launch()
 
1
  import os
2
  import gradio as gr
3
  from langchain_openai import ChatOpenAI
4
+ from langchain_core.messages import HumanMessage, AIMessage
5
  from langgraph.checkpoint.memory import MemorySaver
6
  from langgraph.graph import START, MessagesState, StateGraph
7
 
 
11
  model="gpt-4o-mini",
12
  api_key=api_key,
13
  temperature=0
14
+ )
15
 
16
  # Define the graph
17
  workflow = StateGraph(state_schema=MessagesState)
 
19
  # Define the function that calls the model
20
  def call_model(state: MessagesState):
21
  response = llm.invoke(state["messages"])
22
+ return {"messages": response}
23
 
24
  # Add node and edge to graph
25
  workflow.add_edge(START, "model")
26
+ workflow.add_node("model", call_model)
27
 
28
  # Add memory
29
  memory = MemorySaver()
30
+ return workflow.compile(checkpointer=memory)
31
 
32
  def chat(message, history, api_key, thread_id):
33
  if not api_key:
34
+ return "", [{"role": "assistant", "content": "Please enter your OpenAI API key first."}]
35
 
36
  try:
37
+ # Create chat application
38
  app = create_chat_app(api_key)
39
 
40
  # Configure thread
41
+ config = {"configurable": {"thread_id": thread_id}}
42
 
43
+ # Convert history to messages format
44
+ messages = []
45
+ for msg in history:
46
+ if msg["role"] == "user":
47
+ messages.append(HumanMessage(content=msg["content"]))
48
+ elif msg["role"] == "assistant":
49
+ messages.append(AIMessage(content=msg["content"]))
50
+
51
+ # Add current message
52
+ messages.append(HumanMessage(content=message))
53
 
54
  # Get response
55
+ output = app.invoke({"messages": messages}, config)
56
+ response = output["messages"][-1].content
57
+
58
+ # Update history
59
+ history.append({"role": "user", "content": message})
60
+ history.append({"role": "assistant", "content": response})
61
 
62
+ return "", history
63
  except Exception as e:
64
+ error_message = f"Error: {str(e)}"
65
+ history.append({"role": "user", "content": message})
66
+ history.append({"role": "assistant", "content": error_message})
67
+ return "", history
68
 
 
69
  with gr.Blocks() as demo:
70
  gr.Markdown("# LangChain Chat with Message History")
71
 
 
81
  placeholder="Enter a unique thread ID"
82
  )
83
 
84
+ chatbot = gr.Chatbot(type="messages")
85
+ msg = gr.Textbox(label="Message", placeholder="Type your message here...")
86
+ clear = gr.ClearButton([msg, chatbot])
87
+
88
+ msg.submit(
89
+ chat,
90
+ inputs=[msg, chatbot, api_key, thread_id],
91
+ outputs=[msg, chatbot]
92
+ )
93
 
94
+ if __name__ == "__main__":
95
+ demo.launch()