pycityagent 1.0.0__py3-none-any.whl → 1.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -33,6 +33,41 @@ class MemoryType:
33
33
  LTM = 1
34
34
  WM = 2
35
35
 
36
+ class Memory(BrainFunction):
37
+ """
38
+ 记忆模板类
39
+ The template class of Memory: defined as a BrainFunction
40
+ """
41
+ def __init__(self, agent, type:MemoryType) -> None:
42
+ super().__init__(agent)
43
+ self.type = type
44
+
45
+ def Forward(self, x):
46
+ """
47
+ 数据工作流
48
+ The data workflow
49
+ """
50
+
51
+ def MemorySave(self):
52
+ """
53
+ 记忆存储
54
+ Save Memory
55
+ """
56
+
57
+ def MemoryLoad(self, x):
58
+ """
59
+ 记忆恢复
60
+ Load Memory
61
+ """
62
+
63
+ class WMemory(Memory):
64
+ def __init__(self, agent) -> None:
65
+ super().__init__(agent, MemoryType.WM)
66
+
67
+ class LTMemory(Memory):
68
+ def __init__(self, agent) -> None:
69
+ super().__init__(agent, MemoryType.LTM)
70
+
36
71
  class MemoryRetrive:
37
72
  """
38
73
  用于从LTM中获取对应信息
@@ -42,11 +77,16 @@ class MemoryRetrive:
42
77
  - source (str): the name of source LTM
43
78
  - out (str): the output name of retrived information
44
79
  - user_func (function): the defined function used for retriving
80
+ - des (str): description of this Retrive module
45
81
  """
46
- def __init__(self, source:str, out:str, user_func) -> None:
82
+ def __init__(self, source:str, out:str, user_func, des:str="None") -> None:
47
83
  self.source = source
48
84
  self.out = out
49
85
  self.user_func = user_func
86
+ self.des = des
87
+
88
+ def __str__(self) -> str:
89
+ return self.des
50
90
 
51
91
  class MemoryReason:
52
92
  """
@@ -56,12 +96,17 @@ class MemoryReason:
56
96
  Args:
57
97
  - out (str): the output name of memory reason
58
98
  - user_func (function): the defined function used for reasoning
99
+ - des (str): description of this Reason module
59
100
  - retrivees (Optional[list[MemoryRetrive]]): a list of MemoryRetrive block that help to get related information from LTM
60
101
  """
61
- def __init__(self, out:str, user_func, retrives:Optional[list[MemoryRetrive]]=None) -> None:
102
+ def __init__(self, out:str, user_func, des:str, retrives:Optional[list[MemoryRetrive]]=None) -> None:
62
103
  self.out = out
63
104
  self.user_func = user_func
64
105
  self.retrives = retrives
106
+ self.des = des
107
+
108
+ def __str__(self) -> str:
109
+ return self.des
65
110
 
66
111
  class MemoryPersistence:
67
112
  """
@@ -71,25 +116,38 @@ class MemoryPersistence:
71
116
  Args:
72
117
  - target (str): the name of target LTM
73
118
  - user_func (function): the defined function used for persistence
119
+ - des (str): description of the Persistence module
74
120
  """
75
- def __init__(self, target: str, user_func) -> None:
121
+ def __init__(self, target: str, user_func, des:str) -> None:
76
122
  self.target = target # 指代的是目标记忆体
77
123
  self.user_func = user_func # 用户注入的可执行函数
124
+ self.des = des
125
+
126
+ def __str__(self) -> str:
127
+ return self.des
78
128
 
79
129
  class MemoryController:
80
130
  """
81
131
  记忆管理器
82
132
  Memory Controller
83
133
  """
84
- def __init__(self, agent, memory_config:dict=None) -> None:
134
+ def __init__(self, agent) -> None:
85
135
  self._agent = agent
86
136
  self._soul = agent._soul
87
- if memory_config != None:
88
- pass
89
- else:
90
- self._wm = WorkingMemory(agent)
91
- self._spatial = SpatialMemory(agent)
92
- self._social = SocialMemory(agent)
137
+ self._wm = WorkingMemory(agent)
138
+ self._spatial = SpatialMemory(agent)
139
+ self._social = SocialMemory(agent)
140
+
141
+ def add_LTM(self, name:str, ltm: LTMemory):
142
+ """
143
+ 添加LTM
144
+ Add a LTM
145
+
146
+ Args:
147
+ - name (str): the attribute name, you can use the LTM by '.name'
148
+ - ltm (LTMemory)
149
+ """
150
+ setattr(self, name, ltm)
93
151
 
94
152
  async def Forward(self):
95
153
  """
@@ -140,88 +198,28 @@ class MemoryController:
140
198
  def Hub(self):
141
199
  return self._agent._hub
142
200
 
143
- class Memory(BrainFunction):
144
- """
145
- 记忆模板类
146
- The template class of Memory: defined as a BrainFunction
147
- """
148
- def __init__(self, agent, type:MemoryType) -> None:
149
- super().__init__(agent)
150
- self.type = type
151
-
152
- def Forward(self, x):
153
- """
154
- 数据工作流
155
- The data workflow
156
- """
157
-
158
- def MemorySave(self):
159
- """
160
- 记忆存储
161
- Save Memory
162
- """
163
-
164
- def MemoryLoad(self, x):
165
- """
166
- 记忆恢复
167
- Load Memory
168
- """
169
-
170
- class WorkingMemory(Memory):
201
+ class WorkingMemory(WMemory):
171
202
  """
172
203
  当前工作记忆
173
204
  Working Memory
174
205
  """
175
206
  def __init__(self, agent) -> None:
176
- super().__init__(agent, MemoryType.WM)
207
+ super().__init__(agent)
177
208
  self.sence = None
178
209
  """
179
210
  用于存储感知内容
180
211
  Store the sence content
181
212
  """
213
+
182
214
  self.scheduler = Scheduler(agent)
183
215
  """
184
216
  关联的规划器
185
217
  The related Scheduler
186
218
  """
187
- self.Reason = {}
188
- """
189
- 用于存储Reason结果的buffer: key值为MemoryReason.out
190
- """
191
-
192
- # * agent social
193
- self.agent_converse_buffer = defaultdict(lambda: BASE_CONVERSE_DIALOG+[
194
- {'role': 'system', 'content': f'''[角色基本信息]: {self._agent.Image.get_profile()}'''},
195
- {'role': 'system', 'content': f'''[角色的空间知识]: {self._agent.Brain.Memory.Spatial.to_dialog_str()}'''},
196
- {'role': 'system', 'content': f'''[角色的社交关系]: {self._agent.Brain.Memory.Social.to_dialog_str()}'''}
197
- ])
198
- """
199
- 存储当前仍未结束的对话内容
200
- Store the content of working conversation
201
- """
202
219
 
203
- self.hello_dialog = [
204
- {'role': 'system', 'content': '你将基于用户提供的基本信息以及周围人物信息, 预测用户当前对哪个人最感兴趣, 是否会和该人物进行对话, 以及进行对话的理由'},
205
- {'role': 'system', 'content': '其中基本信息包含用户的个人信息, 周围人物信息包含他人的基本信息以及用户对该人物的了解'},
206
- {'role': 'system', 'content': '你只需要提供一个整数(该整数为对应人物的id)即可(请勿包含其他冗余信息)'},
207
- {'role': 'system', 'content': '''你的回答需要严格按照以下格式给出(请勿包含其他冗余信息):
208
- {"id": 感兴趣人物的id, "conve": 是否进行对话, 可选集合为[是, 否], 'explaination': 进行或不进行对话的理由}'''}
209
- ]
210
- """
211
- Agent主动打招呼的system role dialog
212
- The basic system role dialog used for saying hello
213
- """
214
-
215
- self.msg_agent_unhandle = {} # dict of unhandle agent messages
216
- """
217
- 存储未处理消息
218
- Store unhandled agent messages
219
- """
220
-
221
- self.msg_agent_still = {} # still on converse person_id
220
+ self.Reason = {}
222
221
  """
223
- 存储正在进行对话的person_id
224
- Store the target person_id of conversations that still working
222
+ 用于存储Reason结果的buffer: key值为Memory.Reason.out
225
223
  """
226
224
 
227
225
  # * user message related
@@ -230,16 +228,19 @@ class WorkingMemory(Memory):
230
228
  当前的目标
231
229
  Agent's current target
232
230
  """
231
+
233
232
  self.has_user_command = False
234
233
  """
235
234
  是否有用户指令
236
235
  Whether there have user commond
237
236
  """
238
- self.user_converse_buffer = BASE_CONVERSE_DIALOG+[{'role': 'system', 'content': self._agent.Image.get_profile()}]
237
+
238
+ self.user_converse_buffer = BASE_CONVERSE_DIALOG+[{'role': 'system', 'content': ""}]
239
239
  """
240
240
  存储用户对话信息
241
241
  Store user conversation content
242
242
  """
243
+
243
244
  self.understanding_prompt = [
244
245
  {'role': 'system', 'content': '请你根据用户的输入内容,判断用户向你发起对话的用意并返回结果,返回的结果只能是[对话]或[控制]中的一个'},
245
246
  {'role': 'system', 'content': '其中[对话]表示用户只是想与你进行常规对话;[控制]表示用户想要控制你的行动'},
@@ -256,12 +257,48 @@ class WorkingMemory(Memory):
256
257
  存储未处理的用户消息
257
258
  Store unhandled user messages
258
259
  """
260
+
259
261
  self.msg_user_processing = [] # processing user messages
260
262
  """
261
263
  存储正在处理的用户信息
262
264
  Store working user messages
263
265
  """
264
266
 
267
+ # * agent social
268
+ self.agent_converse_buffer = defaultdict(lambda: BASE_CONVERSE_DIALOG+[
269
+ {'role': 'system', 'content': f'''[角色基本信息]: {self._agent.Image.get_profile()}'''},
270
+ {'role': 'system', 'content': f'''[角色的空间知识]: {self._agent.Brain.Memory.Spatial.to_dialog_str()}'''},
271
+ {'role': 'system', 'content': f'''[角色的社交关系]: {self._agent.Brain.Memory.Social.to_dialog_str()}'''}
272
+ ])
273
+ """
274
+ 存储当前仍未结束的对话内容
275
+ Store the content of working conversation
276
+ """
277
+
278
+ self.hello_dialog = [
279
+ {'role': 'system', 'content': '你将基于用户提供的基本信息以及周围人物信息, 预测用户当前对哪个人最感兴趣, 是否会和该人物进行对话, 以及进行对话的理由'},
280
+ {'role': 'system', 'content': '其中基本信息包含用户的个人信息, 周围人物信息包含他人的基本信息以及用户对该人物的了解'},
281
+ {'role': 'system', 'content': '你只需要提供一个整数(该整数为对应人物的id)即可(请勿包含其他冗余信息)'},
282
+ {'role': 'system', 'content': '''你的回答需要严格按照以下格式给出(请勿包含其他冗余信息):
283
+ {"id": 感兴趣人物的id, "conve": 是否进行对话, 可选集合为[是, 否], 'explaination': 进行或不进行对话的理由}'''}
284
+ ]
285
+ """
286
+ Agent主动打招呼的system role dialog
287
+ The basic system role dialog used for saying hello
288
+ """
289
+
290
+ self.msg_agent_unhandle = {} # dict of unhandle agent messages
291
+ """
292
+ 存储未处理消息
293
+ Store unhandled agent messages
294
+ """
295
+
296
+ self.msg_agent_still = {} # still on converse person_id
297
+ """
298
+ 存储正在进行对话的person_id
299
+ Store the target person_id of conversations that still working
300
+ """
301
+
265
302
  # * config
266
303
  self.enable_user_interaction = True
267
304
  self.enable_economy = True
@@ -269,7 +306,7 @@ class WorkingMemory(Memory):
269
306
 
270
307
  # * 信息提取
271
308
  self.retrive = {
272
- 'getfamilier': MemoryRetrive('Social', 'familiers', getfamilier)
309
+ 'getfamilier': MemoryRetrive('Social', 'familiers', getfamilier, "source: social(LTM), destination: familiers")
273
310
  }
274
311
  """
275
312
  记忆索引模块集合
@@ -281,28 +318,28 @@ class WorkingMemory(Memory):
281
318
  # * reason - 推理/判断功能
282
319
  self.reason = {
283
320
  'idle': [
284
- MemoryReason("hasUserControl", hasUserControl),
285
- MemoryReason("startTrip", startTrip),
286
- MemoryReason("agent_message_handle_resp", handleConve, [self.retrive['getfamilier']]),
287
- MemoryReason("startConve", startConve),
288
- MemoryReason("startShop", startShop)
321
+ MemoryReason("hasUserControl", hasUserControl, "(idle) weather has user control"),
322
+ MemoryReason("startTrip", startTrip, "(idle) weather to start trip"),
323
+ MemoryReason("agent_message_handle_resp", handleConve, "(idle) reason the responce for agent messages", [self.retrive['getfamilier']]),
324
+ MemoryReason("startConve", startConve, "(idle) weather start conversing with other agent"),
325
+ MemoryReason("startShop", startShop, "(idle) weather start shopping")
289
326
  ],
290
327
  'trip': [
291
- MemoryReason("hasUserControl", hasUserControl),
292
- MemoryReason("routeFailed", routeFailed),
293
- MemoryReason("tripArrived", tripArrived)
328
+ MemoryReason("hasUserControl", hasUserControl, "(trip) weather has user control"),
329
+ MemoryReason("routeFailed", routeFailed, "(trip) weather route failed"),
330
+ MemoryReason("tripArrived", tripArrived, "(trip) weather arrived at the destination of current trip")
294
331
  ],
295
332
  'conve': [
296
- MemoryReason("hasUserControl", hasUserControl),
297
- MemoryReason("agent_message_handle_resp", handleConve, [self.retrive['getfamilier']]),
298
- MemoryReason("endConve", endConve),
333
+ MemoryReason("hasUserControl", hasUserControl, "(conve) weather has user control"),
334
+ MemoryReason("agent_message_handle_resp", handleConve, "(conve) reason reason the responce for agent messages", [self.retrive['getfamilier']]),
335
+ MemoryReason("endConve", endConve, "(conve) weather end conversation"),
299
336
  ],
300
337
  'shop': [
301
- MemoryReason("hasUserControl", hasUserControl),
302
- MemoryReason("endShop", endShop)
338
+ MemoryReason("hasUserControl", hasUserControl, "(shop) weather has user control"),
339
+ MemoryReason("endShop", endShop, "(shop) weather end shop")
303
340
  ],
304
341
  'controled': [
305
- MemoryReason("endUserControl", endUserControl)
342
+ MemoryReason("endUserControl", endUserControl, "(controled) weather end user control")
306
343
  ]
307
344
  }
308
345
  """
@@ -315,13 +352,63 @@ class WorkingMemory(Memory):
315
352
 
316
353
  # * persistence - 记忆持久化
317
354
  self.persistence = [
318
- MemoryPersistence('Spatial', spacialPersistence)
355
+ MemoryPersistence('Spatial', spacialPersistence, "source: WM, destination: spatial(LTM)")
319
356
  ]
320
357
  """
321
358
  记忆持久化模块集合
322
359
  The collection of MemoryPersistence blocks
323
360
  """
324
361
 
362
+ def reset_retrive(self):
363
+ """
364
+ 重置WM的retrive模块
365
+ """
366
+ self.retrive = {}
367
+
368
+ def add_retrive(self, name:str, retrive:MemoryRetrive):
369
+ """
370
+ 添加索引模块
371
+
372
+ Args:
373
+ - name (str): the name of the retrive module
374
+ - retrive (MemoryRetrive)
375
+ """
376
+ self.retrive[name] = retrive
377
+
378
+ def reset_reason(self):
379
+ """
380
+ 重置WM的推理模块
381
+ """
382
+ self.reason = {}
383
+
384
+ def add_reason(self, state:str, reason:MemoryReason):
385
+ """
386
+ 添加Reason模块
387
+
388
+ Args:
389
+ - state (str): 该推理模块会在什么状态下被激活
390
+ - reason (MemoryReason)
391
+ """
392
+ if state in self.reason.keys():
393
+ self.reason[state].append(reason)
394
+ else:
395
+ self.reason[state] = [reason]
396
+
397
+ def reset_persistence(self):
398
+ """
399
+ 重置WM的persistence模块
400
+ """
401
+ self.persistence = []
402
+
403
+ def add_persistence(self, persistence:MemoryPersistence):
404
+ """
405
+ 添加持久化模块
406
+
407
+ Args:
408
+ - persistence (MemoryPersistence)
409
+ """
410
+ self.persistence.append(persistence)
411
+
325
412
  async def Forward(self):
326
413
  """
327
414
  WM主工作流
@@ -369,15 +456,18 @@ class WorkingMemory(Memory):
369
456
 
370
457
  async def runReason(self):
371
458
  '''推理模块执行'''
372
- reason_line = self.reason[self._agent.state]
373
- for reason in reason_line:
374
- if reason.retrives == None:
375
- self.Reason[reason.out] = await reason.user_func(self)
376
- else:
377
- retrives = {}
378
- for retrive in reason.retrives:
379
- retrives[retrive.out] = await retrive.user_func(getattr(self.LTM, retrive.source))
380
- self.Reason[reason.out] = await reason.user_func(self, retrives)
459
+ if self._agent.state in self.reason:
460
+ reason_line = self.reason[self._agent.state]
461
+ for reason in reason_line:
462
+ if reason.retrives == None:
463
+ self.Reason[reason.out] = await reason.user_func(self)
464
+ else:
465
+ retrives = {}
466
+ for retrive in reason.retrives:
467
+ retrives[retrive.out] = await retrive.user_func(getattr(self.LTM, retrive.source))
468
+ self.Reason[reason.out] = await reason.user_func(self, retrives)
469
+ else:
470
+ print("Warning: No reason line for current agent's state")
381
471
 
382
472
  async def runPersistence(self):
383
473
  '''持久化模块执行'''
@@ -386,13 +476,17 @@ class WorkingMemory(Memory):
386
476
  await persis.user_func(self, mem)
387
477
 
388
478
  def set_user_converse_background(self):
389
- self.user_converse_buffer[2]['content'] = self._agent.Image.get_profile()
479
+ self.user_converse_buffer[3]['content'] = self._agent.Image.get_profile()
390
480
 
391
481
  @property
392
482
  def LTM(self):
393
483
  return self._agent.Brain.Memory
484
+
485
+ @property
486
+ def Image(self):
487
+ return self._agent.Image
394
488
 
395
- class SpatialMemory(Memory):
489
+ class SpatialMemory(LTMemory):
396
490
  """
397
491
  空间记忆 (LTM)
398
492
  SpatialMemory (LTM)
@@ -406,7 +500,7 @@ class SpatialMemory(Memory):
406
500
  - relation (str): the relation between Agent and the location, '我在这里任职' for instance
407
501
  """
408
502
  def __init__(self, agent) -> None:
409
- super().__init__(agent, MemoryType.LTM)
503
+ super().__init__(agent)
410
504
  self.constant = []
411
505
  """
412
506
  以列表形式存储的空间记忆: 基于文件载入的
@@ -480,7 +574,7 @@ class SpatialMemory(Memory):
480
574
  temp = self.constant + self.sence
481
575
  return json.dumps(temp, indent=0)
482
576
 
483
- class SocialMemory(Memory):
577
+ class SocialMemory(LTMemory):
484
578
  """
485
579
  社交记忆 (LTM)
486
580
  Social Memory (LTM)
@@ -493,7 +587,7 @@ class SocialMemory(Memory):
493
587
  - learned (str): the information that Agent learned about the target person, '他最近在学习AI' for instance
494
588
  """
495
589
  def __init__(self, agent) -> None:
496
- super().__init__(agent, MemoryType.LTM)
590
+ super().__init__(agent)
497
591
  self.familiers = []
498
592
  """
499
593
  以列表形式存储社交记忆