-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathfirst_graph.py
More file actions
100 lines (73 loc) · 2.91 KB
/
first_graph.py
File metadata and controls
100 lines (73 loc) · 2.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
from langchain.chat_models import init_chat_model
from langgraph.graph import StateGraph, START, END
from typing_extensions import TypedDict, Annotated
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, AIMessage, BaseMessage, SystemMessage
import operator
from dotenv import load_dotenv
load_dotenv()
class ConversationState(TypedDict):
messages: Annotated[list, operator.add]
sentiment: str
response_count: int
def create_conversation_graph():
llm = init_chat_model("gpt-4o-mini", temperature=0.7)
# Define node function
def analyze_sentiment(state: ConversationState) -> dict:
"""Analyze the sentiment of the last message."""
last_message = state["messages"][-1]
response = llm.invoke(
[
SystemMessage(
content="Classify sentiment as: positive, negative, or neutral. Reply with just the word."
),
HumanMessage(content=last_message),
]
)
return {"sentiment": response.content.lower().strip()}
def generate_response(state: ConversationState) -> dict:
"""Generate appropriate response based on sentiment."""
sentiment = state["sentiment"]
last_message = state["messages"][-1]
system_prompts = {
"positive": "Respond enthusiastically and build on their positive energy.",
"negative": "Respond empathetically and offer support.",
"neutral": "Respond helpfully and informatively.",
}
prompt = system_prompts.get(sentiment, system_prompts["neutral"])
response = llm.invoke(
[SystemMessage(content=prompt), HumanMessage(content=last_message)]
)
return {"messages": [f"AI: {response.content}"], "response_count": 1}
# Create graph
graph = StateGraph(ConversationState)
# Add nodes
graph.add_node("analyze_sentiment", analyze_sentiment)
graph.add_node("generate_response", generate_response)
# Add edges
graph.add_edge(START, "analyze_sentiment")
graph.add_edge("analyze_sentiment", "generate_response")
graph.add_edge("generate_response", END)
app = graph.compile()
return app
def demo_conversation():
app = create_conversation_graph()
# Simulate a conversation
test_messages = [
"I just got promoted at work! I'm so excited!",
"My computer crashed and I lost all my work...",
"What's the weather like today?",
]
print("Conversation Graph Demo:\n")
for msg in test_messages:
result = app.invoke({
"messages": [f"Human: {msg}"],
"sentiment": "",
"response_count": 0
})
print(f"Input: {msg}")
print(f"Sentiment: {result['sentiment']}")
print(f"Response: {result['messages'][-1]}")
print("-" * 40)
if __name__ == "__main__":
demo_conversation()