Repository navigation
Expand file tree
/
Copy pathsession.py
More file actions
272 lines (209 loc) · 9.39 KB
/
Copy pathsession.py
File metadata and controls
272 lines (209 loc) · 9.39 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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
from agently import Agently
from agently.core import Session
Agently.set_settings(
"OpenAICompatible",
{
"base_url": "http://localhost:11434/v1",
"model": "qwen2.5:7b",
},
)
agent = Agently.create_agent()
def basic_session_on_off():
print("\n=== Example 1: Session On / Off ===")
agent.activate_session(session_id="demo_on_off")
print("[Ask to remember]")
agent.input("Remember this: I need to buy eggs tomorrow.").streaming_print()
print("[Session ON]")
agent.input("What should I buy tomorrow?").streaming_print()
agent.deactivate_session()
print("[Session OFF]")
agent.input("What should I buy tomorrow?").streaming_print()
# basic_session_on_off()
def session_isolation_by_id():
print("\n=== Example 2: Session Isolation by ID ===")
agent.activate_session(session_id="trip_a")
agent.input("Remember this trip note: destination is Tokyo.").streaming_print()
agent.activate_session(session_id="trip_b")
agent.input("Remember this trip note: destination is Paris.").streaming_print()
print("[Check trip_b]")
agent.input("What is my destination?").streaming_print()
agent.activate_session(session_id="trip_a")
print("[Check trip_a]")
agent.input("What is my destination?").streaming_print()
# session_isolation_by_id()
def session_record_with_input_reply_keys():
print("\n=== Example 3: Record With input_keys/reply_keys (.info + .input) ===")
agent.activate_session(session_id="demo_key_record")
agent.set_settings("session.input_keys", ["info.task", "info.style", "input.lang"])
agent.set_settings("session.reply_keys", ["summary", "keywords"])
result = (
agent.info(
{
"task": "Summarize Agently in one sentence.",
"style": "technical",
}
)
.input({"lang": "en", "extra": "ignore_me"})
.output(
{
"summary": (str,),
"keywords": [(str,)],
"extra": (str,),
}
)
.get_data()
)
print("[Parsed Result]")
print(result)
assert agent.activated_session is not None
print("[Recorded Session History]")
for idx, message in enumerate(agent.activated_session.full_context):
print(f"{idx + 1}. {message.role}:\n{message.content}")
# Reset to default recording behavior for next examples.
agent.set_settings("session.input_keys", None)
agent.set_settings("session.reply_keys", None)
# session_record_with_input_reply_keys()
def session_export_and_restore():
print("\n=== Example 4: Export and Restore Session ===")
agent.activate_session(session_id="demo_export")
agent.input("Remember this recovery code: X-2025-ABCD").streaming_print()
assert agent.activated_session is not None
exported_json = agent.activated_session.get_json_session()
print("[Exported JSON Preview]")
print(exported_json)
restored = Session(settings=agent.settings)
restored.load_json_session(exported_json)
restored_id = "demo_export_restored"
restored.id = restored_id
agent.sessions[restored_id] = restored
agent.activate_session(session_id=restored_id)
print("[Restored Session Check]")
agent.input("What recovery code did I ask you to remember?").streaming_print()
# session_export_and_restore()
def session_custom_handlers():
print("\n=== Example 5: Custom Session Handlers ===")
agent.activate_session(session_id="demo_custom_handlers")
assert agent.activated_session is not None
session = agent.activated_session
def analysis_handler(full_context, context_window, memo, session_settings):
_ = full_context
_ = memo
_ = session_settings
if len(context_window) > 2:
return "keep_last_two"
return None
def keep_last_two_handler(full_context, context_window, memo, session_settings):
_ = full_context
_ = memo
_ = session_settings
return None, list(context_window[-2:]), {"strategy": "keep_last_two"}
session.register_analysis_handler(analysis_handler)
session.register_resize_handler("keep_last_two", keep_last_two_handler)
agent.add_chat_history({"role": "user", "content": "turn-1"})
agent.add_chat_history({"role": "assistant", "content": "turn-2"})
agent.add_chat_history({"role": "user", "content": "turn-3"})
agent.add_chat_history({"role": "assistant", "content": "turn-4"})
print("[Full Context]")
for idx, message in enumerate(session.full_context):
print(f"{idx + 1}. {message.role}: {message.content}")
print("[Context Window After Custom Handler]")
for idx, message in enumerate(session.context_window):
print(f"{idx + 1}. {message.role}: {message.content}")
print("[Memo]")
print(session.memo)
# session_custom_handlers()
def session_custom_handlers_with_real_request():
print("\n=== Example 6: Custom Handlers With Real Request ===")
agent.activate_session(session_id="demo_custom_handlers_live")
assert agent.activated_session is not None
session = agent.activated_session
def analysis_handler(full_context, context_window, memo, session_settings):
_ = full_context
_ = memo
_ = session_settings
if len(context_window) > 4:
return "keep_last_four"
return None
def keep_last_four_handler(full_context, context_window, memo, session_settings):
_ = full_context
_ = memo
_ = session_settings
kept = list(context_window[-4:])
return None, kept, {"strategy": "keep_last_four", "kept_count": len(kept)}
session.register_analysis_handler(analysis_handler)
session.register_resize_handler("keep_last_four", keep_last_four_handler)
print("[Turn 1]")
agent.input("Remember my favorite city is Chengdu.").streaming_print()
print("[Turn 2]")
agent.input("Also remember my favorite food is hotpot.").streaming_print()
print("[Turn 3]")
agent.input("What city and food did I ask you to remember?").streaming_print()
print("[Session State]")
print(f"full_context: {len(session.full_context)}")
print(f"context_window: {len(session.context_window)}")
print(f"memo: {session.memo}")
# session_custom_handlers_with_real_request()
def session_custom_handlers_with_memo_in_real_request():
print("\n=== Example 7: Custom Handlers With Memo In Real Request ===")
agent.activate_session(session_id="demo_custom_handlers_with_memo")
assert agent.activated_session is not None
session = agent.activated_session
def analysis_handler(full_context, context_window, memo, session_settings):
_ = full_context
_ = memo
_ = session_settings
if len(context_window) > 4:
return "keep_last_four"
else:
return None
async def keep_last_four_handler(full_context, context_window, memo, session_settings):
_ = full_context
_ = session_settings
kept = list(context_window[-4:])
memo_request = agent.create_temp_request()
new_memo = await (
memo_request
.input({"messages": context_window[:-4], "history_memo": memo})
.instruct("Recreate key points memo dict of {input.messages} and {input.history_memo}")
.output(
{
"key_points": {
"<point_title>": (str, "point content"),
"...": "...",
}
}
)
.async_start(ensure_keys=["key_points"])
)
return None, kept, new_memo["key_points"]
session.register_analysis_handler(analysis_handler)
session.register_resize_handler("keep_last_four", keep_last_four_handler)
print("[Turn 1]")
agent.input("Remember my favorite city is Chengdu.").streaming_print()
print("[Turn 2]")
agent.input("Also remember my favorite food is hotpot.").streaming_print()
print("[Turn 3]")
agent.input("What city and food did I ask you to remember?").streaming_print()
print("[Session State]")
print(f"full_context: {len(session.full_context)}")
print(f"context_window: {len(session.context_window)}")
print(f"memo: {session.memo}")
session_custom_handlers_with_memo_in_real_request()
# Expected output shape (content is variable — requires local Ollama):
# The final active example (session_custom_handlers_with_memo_in_real_request)
# prints turn-by-turn replies and session state:
# full_context: 6 (all turns stored)
# context_window: 4 (kept last 4 after resize)
# memo: {'key_points': {...}} (LLM-generated summary of dropped turns)
#
# How it works:
# Session stores conversation turns and passes a context_window to the model.
# activate_session(session_id=...) attaches a named session; deactivate_session()
# detaches it. session_id isolation means different IDs never share history.
# input_keys / reply_keys filter which prompt fields and output keys are recorded.
# get_json_session() / load_json_session() export and restore the full turn list.
# Custom handlers: register_analysis_handler() decides whether to resize the window
# (returns a resize strategy name or None); register_resize_handler(name, fn)
# implements that strategy — receives (full_context, context_window, memo, settings)
# and returns (new_full_context, new_window, new_memo). Async handlers may call
# agent.create_temp_request() to run a summarization step during compression.