Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
8 |
+
def create_chat_app(api_key):
|
9 |
+
# Initialize the chat model
|
10 |
+
llm = ChatOpenAI(
|
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)
|
18 |
+
|
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 |
+
|
57 |
+
with gr.Row():
|
58 |
+
api_key = gr.Textbox(
|
59 |
+
label="OpenAI API Key",
|
60 |
+
placeholder="Enter your OpenAI API key",
|
61 |
+
type="password"
|
62 |
+
)
|
63 |
+
thread_id = gr.Textbox(
|
64 |
+
label="Thread ID",
|
65 |
+
value="default_thread",
|
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()
|