-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplayground.py
More file actions
220 lines (185 loc) · 6.08 KB
/
playground.py
File metadata and controls
220 lines (185 loc) · 6.08 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import os
import uuid
import psycopg
from psycopg.rows import dict_row
from dotenv import load_dotenv
from langgraph.graph import StateGraph, MessagesState, START, END
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.messages import HumanMessage
from langgraph.checkpoint.postgres import PostgresSaver
from langchain_core.runnables import RunnableConfig
# Load env vars
load_dotenv()
# Build Postgres connection string
POSTGRES_CONN_STRING = (
f"postgresql://{os.getenv('DB_USER')}:"
f"{os.getenv('DB_PASSWORD')}@"
f"{os.getenv('DB_HOST')}:"
f"{os.getenv('DB_PORT')}/"
f"{os.getenv('DB_NAME')}"
f"?sslmode={os.getenv('DB_SSLMODE', 'disable')}"
)
# ---------------------------
# App DB connection
# ---------------------------
app_db = psycopg.connect(
POSTGRES_CONN_STRING,
row_factory=dict_row # type: ignore[arg-type]
)
# ---------------------------
# Model
# ---------------------------
model = ChatGoogleGenerativeAI(
model="gemini-2.5-flash-lite",
api_key=os.getenv("GOOGLE_API_KEY"),
request_timeout=30,
)
# ---------------------------
# Graph node
# ---------------------------
def call_google_node(state: MessagesState):
messages = state["messages"]
response = model.invoke(messages)
return {"messages": messages + [response]}
# ---------------------------
# Graph
# ---------------------------
def build_graph(checkpointer):
g = StateGraph(MessagesState)
g.add_node("google_model", call_google_node)
g.add_edge(START, "google_model")
g.add_edge("google_model", END)
return g.compile(checkpointer=checkpointer)
# ---------------------------
# Helpers
# ---------------------------
def new_thread_id():
return f"branch-{uuid.uuid4().hex[:8]}"
def get_next_turn_index(conn, thread_id: str) -> int:
with conn.cursor() as cur:
cur.execute(
"""
SELECT COALESCE(MAX(turn_index), 0) + 1 AS next_turn
FROM ai_message_checkpoints
WHERE thread_id = %s
""",
(thread_id,)
)
row = cur.fetchone()
assert row is not None
return row["next_turn"]
def store_ai_message_checkpoint(
conn,
*,
thread_id: str,
ai_message_id: str,
checkpoint_id: str,
turn_index: int,
model_name: str | None = None,
parent_thread_id: str | None = None,
parent_ai_message_id: str | None = None,
):
with conn.cursor() as cur:
cur.execute(
"""
INSERT INTO ai_message_checkpoints (
thread_id,
ai_message_id,
checkpoint_id,
parent_thread_id,
parent_ai_message_id,
turn_index,
model_name
)
VALUES (%s, %s, %s, %s, %s, %s, %s)
""",
(
thread_id,
ai_message_id,
checkpoint_id,
parent_thread_id,
parent_ai_message_id,
turn_index,
model_name,
)
)
conn.commit()
# ---------------------------
# Fork logic
# ---------------------------
def fork_from_checkpoint(graph, source_thread_id, checkpoint_id):
state = graph.get_state({
"configurable": {
"thread_id": source_thread_id,
"checkpoint_id": checkpoint_id,
}
})
new_thread = new_thread_id()
# Seed state ONLY (no lineage written here)
graph.invoke(
state.values,
{"configurable": {"thread_id": new_thread}}
)
return new_thread
# ---------------------------
# REPL
# ---------------------------
def repl():
with PostgresSaver.from_conn_string(POSTGRES_CONN_STRING) as checkpointer:
graph = build_graph(checkpointer)
source_thread = input("Source thread_id (Enter for default): ").strip() or "default"
checkpoint_id = input("Checkpoint ID (Enter for latest): ").strip()
parent_thread_id = None
parent_ai_message_id = None
if checkpoint_id:
print(f"\nForking from {source_thread} @ {checkpoint_id}")
active_thread = fork_from_checkpoint(graph, source_thread, checkpoint_id)
with app_db.cursor() as cur:
cur.execute(
"""
SELECT ai_message_id
FROM ai_message_checkpoints
WHERE thread_id = %s AND checkpoint_id = %s
""",
(source_thread, checkpoint_id)
)
row = cur.fetchone()
if row is None:
raise RuntimeError("Checkpoint not found")
parent_ai_message_id = row["ai_message_id"]
parent_thread_id = source_thread
else:
active_thread = source_thread
print(f"Active thread: {active_thread}\n")
config: RunnableConfig = {
"configurable": {
"thread_id": active_thread
}
}
while True:
u = input("You: ").strip()
if u.lower() in ("exit", "quit", "stop"):
break
result = graph.invoke(
{"messages": [HumanMessage(content=u)]},
config=config
)
print("Bot:", result["messages"][-1].content)
state = graph.get_state(config)
cfg = state.config.get("configurable")
assert cfg is not None
checkpoint_id = cfg["checkpoint_id"]
last_ai = state.values["messages"][-1]
turn_index = get_next_turn_index(app_db, active_thread)
store_ai_message_checkpoint(
app_db,
thread_id=active_thread,
ai_message_id=last_ai.id,
checkpoint_id=checkpoint_id,
turn_index=turn_index,
model_name="gemini-2.5-flash-lite",
parent_thread_id=parent_thread_id if turn_index == 1 else None,
parent_ai_message_id=parent_ai_message_id if turn_index == 1 else None,
)
if __name__ == "__main__":
repl()