pycityagent 1.0.0__tar.gz

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.
Files changed (53) hide show
  1. pycityagent-1.0.0/LICENSE +21 -0
  2. pycityagent-1.0.0/PKG-INFO +181 -0
  3. pycityagent-1.0.0/README.md +134 -0
  4. pycityagent-1.0.0/pycityagent/__init__.py +4 -0
  5. pycityagent-1.0.0/pycityagent/ac/__init__.py +6 -0
  6. pycityagent-1.0.0/pycityagent/ac/ac.py +50 -0
  7. pycityagent-1.0.0/pycityagent/ac/action.py +14 -0
  8. pycityagent-1.0.0/pycityagent/ac/controled.py +13 -0
  9. pycityagent-1.0.0/pycityagent/ac/converse.py +31 -0
  10. pycityagent-1.0.0/pycityagent/ac/idle.py +17 -0
  11. pycityagent-1.0.0/pycityagent/ac/shop.py +80 -0
  12. pycityagent-1.0.0/pycityagent/ac/trip.py +37 -0
  13. pycityagent-1.0.0/pycityagent/agent.py +318 -0
  14. pycityagent-1.0.0/pycityagent/brain/__init__.py +10 -0
  15. pycityagent-1.0.0/pycityagent/brain/brain.py +52 -0
  16. pycityagent-1.0.0/pycityagent/brain/brainfc.py +10 -0
  17. pycityagent-1.0.0/pycityagent/brain/memory.py +541 -0
  18. pycityagent-1.0.0/pycityagent/brain/persistence/__init__.py +0 -0
  19. pycityagent-1.0.0/pycityagent/brain/persistence/social.py +1 -0
  20. pycityagent-1.0.0/pycityagent/brain/persistence/spatial.py +14 -0
  21. pycityagent-1.0.0/pycityagent/brain/reason/__init__.py +0 -0
  22. pycityagent-1.0.0/pycityagent/brain/reason/shop.py +37 -0
  23. pycityagent-1.0.0/pycityagent/brain/reason/social.py +148 -0
  24. pycityagent-1.0.0/pycityagent/brain/reason/trip.py +67 -0
  25. pycityagent-1.0.0/pycityagent/brain/reason/user.py +122 -0
  26. pycityagent-1.0.0/pycityagent/brain/retrive/__init__.py +0 -0
  27. pycityagent-1.0.0/pycityagent/brain/retrive/social.py +6 -0
  28. pycityagent-1.0.0/pycityagent/brain/scheduler.py +408 -0
  29. pycityagent-1.0.0/pycityagent/brain/sence.py +375 -0
  30. pycityagent-1.0.0/pycityagent/brain/static.py +415 -0
  31. pycityagent-1.0.0/pycityagent/cc/__init__.py +5 -0
  32. pycityagent-1.0.0/pycityagent/cc/cc.py +102 -0
  33. pycityagent-1.0.0/pycityagent/cc/conve.py +6 -0
  34. pycityagent-1.0.0/pycityagent/cc/idle.py +20 -0
  35. pycityagent-1.0.0/pycityagent/cc/shop.py +6 -0
  36. pycityagent-1.0.0/pycityagent/cc/trip.py +13 -0
  37. pycityagent-1.0.0/pycityagent/cc/user.py +13 -0
  38. pycityagent-1.0.0/pycityagent/hubconnector/__init__.py +3 -0
  39. pycityagent-1.0.0/pycityagent/hubconnector/hubconnector.py +137 -0
  40. pycityagent-1.0.0/pycityagent/image/__init__.py +3 -0
  41. pycityagent-1.0.0/pycityagent/image/image.py +158 -0
  42. pycityagent-1.0.0/pycityagent/simulator.py +161 -0
  43. pycityagent-1.0.0/pycityagent/st/__init__.py +4 -0
  44. pycityagent-1.0.0/pycityagent/st/st.py +96 -0
  45. pycityagent-1.0.0/pycityagent/urbanllm/__init__.py +3 -0
  46. pycityagent-1.0.0/pycityagent/urbanllm/urbanllm.py +132 -0
  47. pycityagent-1.0.0/pycityagent.egg-info/PKG-INFO +181 -0
  48. pycityagent-1.0.0/pycityagent.egg-info/SOURCES.txt +51 -0
  49. pycityagent-1.0.0/pycityagent.egg-info/dependency_links.txt +1 -0
  50. pycityagent-1.0.0/pycityagent.egg-info/requires.txt +10 -0
  51. pycityagent-1.0.0/pycityagent.egg-info/top_level.txt +1 -0
  52. pycityagent-1.0.0/pyproject.toml +43 -0
  53. pycityagent-1.0.0/setup.cfg +4 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 FIBLAB
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,181 @@
1
+ Metadata-Version: 2.1
2
+ Name: pycityagent
3
+ Version: 1.0.0
4
+ Summary: LLM-based城市模拟器agent构建库
5
+ Author-email: Yuwei Yan <pinkgranite86@gmail.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2024 FIBLAB
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/tsinghua-fib-lab/pycityagent
29
+ Project-URL: Repository, https://github.com/tsinghua-fib-lab/pycityagent.git
30
+ Project-URL: Issues, https://github.com/tsinghua-fib-lab/pycityagent/issues
31
+ Keywords: agent,city,LLM
32
+ Classifier: Programming Language :: Python :: 3
33
+ Classifier: Operating System :: OS Independent
34
+ Requires-Python: >=3.8
35
+ Description-Content-Type: text/markdown
36
+ License-File: LICENSE
37
+ Requires-Dist: dashscope>=1.14.0
38
+ Requires-Dist: geojson>=3.1.0
39
+ Requires-Dist: numpy>=1.26.3
40
+ Requires-Dist: openai>=1.8.0
41
+ Requires-Dist: Pillow>=10.2.0
42
+ Requires-Dist: pycitysim>=1.8.0
43
+ Requires-Dist: citystreetview>=1.1.0
44
+ Requires-Dist: PyYAML>=6.0.1
45
+ Requires-Dist: Requests>=2.31.0
46
+ Requires-Dist: transitions>=0.9.0
47
+
48
+ # Pycityagent
49
+
50
+ # Table of Contents
51
+ * [Introduction](#Introduction)
52
+ * [The Whole Framework of CityAgent](#The-Whole-Framework-of-CityAgent)
53
+ * [The Workflow of CityAgent](#The-Workflow-of-CityAgent)
54
+ * [Hands On - By An Easy Demo](#Hands-On---By-An-Easy-Demo)
55
+
56
+ <!-- TOC -->
57
+
58
+ ## Introduction
59
+ ### Framework of CityAgent
60
+ - ![framwork](./static/framework.png)
61
+
62
+ ### Workflow of CityAgent
63
+ - ![workflow](./static/workflow.png)
64
+
65
+ ## Hands On - By An Easy Demo
66
+ ### Apply for your App
67
+ - You first need to register your account in the [Opencity website](https://opencity.fiblab.net/)
68
+ - Login to the console, create your own app.
69
+ - Get your app_id and app_secret
70
+ - ![app](./static/app.png)
71
+
72
+ ### Get your Config
73
+ - There are three parts of a config file: **llm_request**, **citysim_request** and **apphub_request**
74
+ ```yaml
75
+ llm_request:
76
+ text_request:
77
+ request_type: qwen
78
+ api_key: xxx
79
+ model: xxx
80
+ img_understand_request:
81
+ request_type: qwen
82
+ api_key: xxx
83
+ model: xxx
84
+ img_generate_request:
85
+ request_type: qwen
86
+ api_key: xxx
87
+ model: xxx
88
+
89
+ citysim_request:
90
+ simulator:
91
+ server: https://api-opencity-2x.fiblab.net:58081
92
+ map_request:
93
+ mongo_coll: map_beijing_extend_20240205
94
+ cache_dir: ./cache
95
+ streetview_request:
96
+ engine: baidumap / googlemap
97
+ mapAK: your baidumap AK (if baidumap)
98
+ proxy: your googlemap proxy (if googlemap, optional)
99
+
100
+ apphub_request:
101
+ hub_url: https://api-opencity-2x.fiblab.net:58080
102
+ app_id: your APP ID
103
+ app_secret: your APP Secret
104
+ profile_image: the profile image of your agent
105
+ ```
106
+ - Forget about **citysim_request**, let's focus on the other two.
107
+
108
+ #### LLM_REQUEST
109
+ - As you can tell, the whole CityAgent is based on the LLM, by now, there are three different parts of config items: **text_request**, **img_understand_request** and **img_generate_request**
110
+ - By now, we support [**qwen**](https://tongyi.aliyun.com/) and [**openai**](https://openai.com/)
111
+ - `Notice: Our environments are basically conducted with qwen. If you prefer to use openai, then you may encounter hardships. AND fell free to issue us.`
112
+ - Get your **api_key** and chooce your **model**s
113
+
114
+ ### CITYSIM_REQUEST
115
+ - There are no need to change the 'simulator' and 'map_request' config
116
+ - 'streetview_request': this is the config used for streetview
117
+ - By now, we support 'baidumap' and 'googlemap'
118
+ - If you use 'baidumap', then you need to apply for a mapAK
119
+ - If you use 'googlemap', then you can config your own proxy by 'proxy' attribute
120
+
121
+ #### APPHUB_REQUEST
122
+ - This is basically used to connect with the backend.
123
+ - Put your **app_id** and **app_secret** here.
124
+
125
+ ### Installation
126
+ - Install from **pip** easily.
127
+ ```shell
128
+ pip install pycityagent
129
+ ```
130
+
131
+ ### CODE and RUN
132
+ - Check the **example** folder and copy files from it (`Remember replace the config file`)
133
+ - Look at the Demo:
134
+ ```python
135
+ import yaml
136
+ from pycityagent.simulator import Simulator
137
+ from pycityagent.urbanllm import LLMConfig, UrbanLLM
138
+ import asyncio
139
+ import time
140
+
141
+ async def main():
142
+ # load your config
143
+ with open('config_template.yaml', 'r') as file:
144
+ config = yaml.safe_load(file)
145
+
146
+ # get the simulator object
147
+ smi = Simulator(config['citysim_request'])
148
+
149
+ # get the person by person_id, return agent
150
+ agent = await smi.GetAgent("name_of_agent", 8)
151
+
152
+ # Help you build unique agent by scratch/profile
153
+ agent.Image.load_scratch('scratch_template.json')
154
+
155
+ # Load Memory and assist the agent to understand "Opencity"
156
+ agent.Brain.Memory.Spatial.MemoryLoad('spatial_knowledge_template.json')
157
+ agent.Brain.Memory.Social.MemoryLoad('social_background_template.json')
158
+
159
+ # Connect to apphub so you can interact with your agent in front end
160
+ agent.ConnectToHub(config['apphub_request'])
161
+
162
+ # Creat the soul (a LLM processor actually)
163
+ llmConfig = LLMConfig(config['llm_request'])
164
+ soul = UrbanLLM(llmConfig)
165
+
166
+ # Add the soul to your agent
167
+ agent.add_soul(soul)
168
+
169
+ # Start and have fun with it!!!
170
+ while True:
171
+ await agent.Run()
172
+ time.sleep(1)
173
+
174
+ if __name__ == '__main__':
175
+ asyncio.run(main())
176
+ ```
177
+
178
+ ### Congratulations
179
+ - Following this "Hands On" guide, you have easily created an agent by your hand!
180
+ - You can observe your AGENT in your console or in the [Opencity website](https://opencity.fiblab.net/).
181
+ - HAVE FUN WITH IT!
@@ -0,0 +1,134 @@
1
+ # Pycityagent
2
+
3
+ # Table of Contents
4
+ * [Introduction](#Introduction)
5
+ * [The Whole Framework of CityAgent](#The-Whole-Framework-of-CityAgent)
6
+ * [The Workflow of CityAgent](#The-Workflow-of-CityAgent)
7
+ * [Hands On - By An Easy Demo](#Hands-On---By-An-Easy-Demo)
8
+
9
+ <!-- TOC -->
10
+
11
+ ## Introduction
12
+ ### Framework of CityAgent
13
+ - ![framwork](./static/framework.png)
14
+
15
+ ### Workflow of CityAgent
16
+ - ![workflow](./static/workflow.png)
17
+
18
+ ## Hands On - By An Easy Demo
19
+ ### Apply for your App
20
+ - You first need to register your account in the [Opencity website](https://opencity.fiblab.net/)
21
+ - Login to the console, create your own app.
22
+ - Get your app_id and app_secret
23
+ - ![app](./static/app.png)
24
+
25
+ ### Get your Config
26
+ - There are three parts of a config file: **llm_request**, **citysim_request** and **apphub_request**
27
+ ```yaml
28
+ llm_request:
29
+ text_request:
30
+ request_type: qwen
31
+ api_key: xxx
32
+ model: xxx
33
+ img_understand_request:
34
+ request_type: qwen
35
+ api_key: xxx
36
+ model: xxx
37
+ img_generate_request:
38
+ request_type: qwen
39
+ api_key: xxx
40
+ model: xxx
41
+
42
+ citysim_request:
43
+ simulator:
44
+ server: https://api-opencity-2x.fiblab.net:58081
45
+ map_request:
46
+ mongo_coll: map_beijing_extend_20240205
47
+ cache_dir: ./cache
48
+ streetview_request:
49
+ engine: baidumap / googlemap
50
+ mapAK: your baidumap AK (if baidumap)
51
+ proxy: your googlemap proxy (if googlemap, optional)
52
+
53
+ apphub_request:
54
+ hub_url: https://api-opencity-2x.fiblab.net:58080
55
+ app_id: your APP ID
56
+ app_secret: your APP Secret
57
+ profile_image: the profile image of your agent
58
+ ```
59
+ - Forget about **citysim_request**, let's focus on the other two.
60
+
61
+ #### LLM_REQUEST
62
+ - As you can tell, the whole CityAgent is based on the LLM, by now, there are three different parts of config items: **text_request**, **img_understand_request** and **img_generate_request**
63
+ - By now, we support [**qwen**](https://tongyi.aliyun.com/) and [**openai**](https://openai.com/)
64
+ - `Notice: Our environments are basically conducted with qwen. If you prefer to use openai, then you may encounter hardships. AND fell free to issue us.`
65
+ - Get your **api_key** and chooce your **model**s
66
+
67
+ ### CITYSIM_REQUEST
68
+ - There are no need to change the 'simulator' and 'map_request' config
69
+ - 'streetview_request': this is the config used for streetview
70
+ - By now, we support 'baidumap' and 'googlemap'
71
+ - If you use 'baidumap', then you need to apply for a mapAK
72
+ - If you use 'googlemap', then you can config your own proxy by 'proxy' attribute
73
+
74
+ #### APPHUB_REQUEST
75
+ - This is basically used to connect with the backend.
76
+ - Put your **app_id** and **app_secret** here.
77
+
78
+ ### Installation
79
+ - Install from **pip** easily.
80
+ ```shell
81
+ pip install pycityagent
82
+ ```
83
+
84
+ ### CODE and RUN
85
+ - Check the **example** folder and copy files from it (`Remember replace the config file`)
86
+ - Look at the Demo:
87
+ ```python
88
+ import yaml
89
+ from pycityagent.simulator import Simulator
90
+ from pycityagent.urbanllm import LLMConfig, UrbanLLM
91
+ import asyncio
92
+ import time
93
+
94
+ async def main():
95
+ # load your config
96
+ with open('config_template.yaml', 'r') as file:
97
+ config = yaml.safe_load(file)
98
+
99
+ # get the simulator object
100
+ smi = Simulator(config['citysim_request'])
101
+
102
+ # get the person by person_id, return agent
103
+ agent = await smi.GetAgent("name_of_agent", 8)
104
+
105
+ # Help you build unique agent by scratch/profile
106
+ agent.Image.load_scratch('scratch_template.json')
107
+
108
+ # Load Memory and assist the agent to understand "Opencity"
109
+ agent.Brain.Memory.Spatial.MemoryLoad('spatial_knowledge_template.json')
110
+ agent.Brain.Memory.Social.MemoryLoad('social_background_template.json')
111
+
112
+ # Connect to apphub so you can interact with your agent in front end
113
+ agent.ConnectToHub(config['apphub_request'])
114
+
115
+ # Creat the soul (a LLM processor actually)
116
+ llmConfig = LLMConfig(config['llm_request'])
117
+ soul = UrbanLLM(llmConfig)
118
+
119
+ # Add the soul to your agent
120
+ agent.add_soul(soul)
121
+
122
+ # Start and have fun with it!!!
123
+ while True:
124
+ await agent.Run()
125
+ time.sleep(1)
126
+
127
+ if __name__ == '__main__':
128
+ asyncio.run(main())
129
+ ```
130
+
131
+ ### Congratulations
132
+ - Following this "Hands On" guide, you have easily created an agent by your hand!
133
+ - You can observe your AGENT in your console or in the [Opencity website](https://opencity.fiblab.net/).
134
+ - HAVE FUN WITH IT!
@@ -0,0 +1,4 @@
1
+ from .simulator import Simulator
2
+ from .agent import Agent
3
+
4
+ __all__ = [Simulator, Agent]
@@ -0,0 +1,6 @@
1
+ '''Action Control - 最终进行simulator以及AppHub对接'''
2
+
3
+ from .ac import *
4
+ from .action import *
5
+
6
+ __all__ = [ActionController, Action]
@@ -0,0 +1,50 @@
1
+ from typing import Any
2
+ from .trip import TripAction
3
+ from .shop import ShopAction
4
+ from .converse import ConverseAction
5
+ from .controled import ControledAction
6
+ from .idle import IdleAction
7
+
8
+ class ActionController:
9
+ """
10
+ Agent行为控制器: 与AppHub(simulator)对接
11
+ Agent Controller: Connect with AppHub and Simulator
12
+ Note: Actions are predefined. By now, user defined actions are not supported
13
+ """
14
+ def __init__(self, agent, config=None) -> None:
15
+ self._agent = agent
16
+ self._trip = TripAction(agent)
17
+ self._shop = ShopAction(agent)
18
+ self._converse = ConverseAction(agent)
19
+ self._control = ControledAction(agent)
20
+ self._idle = IdleAction(agent)
21
+ self._config = config
22
+
23
+ async def Run(self):
24
+ # TODO: 后期补充相关扩展接口,应该根据state-action关联模块进行(为了方便用户定义更加丰富的状态)
25
+ if self._agent.state == 'idle':
26
+ await self._idle()
27
+ elif self._agent.state == 'trip':
28
+ await self._trip()
29
+ elif self._agent.state == 'conve':
30
+ await self._converse()
31
+ elif self._agent.state == 'shop':
32
+ await self._shop()
33
+ elif self._agent.state == 'controled':
34
+ await self._control()
35
+
36
+ @property
37
+ def TripAction(self):
38
+ return self._trip
39
+
40
+ @property
41
+ def ShopAction(self):
42
+ return self._shop
43
+
44
+ @property
45
+ def ConveAction(self):
46
+ return self._converse
47
+
48
+ @property
49
+ def ControlAction(self):
50
+ return self._controls
@@ -0,0 +1,14 @@
1
+ from abc import ABC, abstractclassmethod
2
+ from typing import Any
3
+
4
+ class Action:
5
+ def __init__(self, agent) -> None:
6
+ '''默认初始化'''
7
+ self._agent = agent
8
+
9
+ @abstractclassmethod
10
+ async def Forward(self):
11
+ '''接口函数'''
12
+
13
+ async def __call__(self) -> Any:
14
+ await self.Forward()
@@ -0,0 +1,13 @@
1
+ import time
2
+ from .action import Action
3
+ from pycitysim.apphub import AgentMessage
4
+
5
+ class ControledAction(Action):
6
+ '''Converse行为控制器'''
7
+ def __init__(self, agent) -> None:
8
+ super().__init__(agent)
9
+
10
+ async def Forward(self):
11
+ req = {'person_id': self._agent._id, 'schedules': []}
12
+ await self._agent._client.person_service.SetSchedule(req)
13
+ self._agent.Hub.Update([AgentMessage(self._agent.Hub._agent_id, int(time.time()*1000), '我已理解您的意思,正在修改我的行程', None, None)])
@@ -0,0 +1,31 @@
1
+ import time
2
+ from .action import Action
3
+ from pycitysim.apphub import AgentMessage
4
+
5
+ class ConverseAction(Action):
6
+ '''Converse行为控制器'''
7
+ def __init__(self, agent) -> None:
8
+ super().__init__(agent)
9
+
10
+ async def Forward(self):
11
+ target_agent_ids = self._agent.Brain.Memory.Working.Reason['agent_message_handle_resp'][0]
12
+ if len(target_agent_ids) == 0:
13
+ return
14
+ messages = self._agent.Brain.Memory.Working.Reason['agent_message_handle_resp'][1]
15
+ req = {'messages': []}
16
+ if len(target_agent_ids) != len(messages):
17
+ print("Warning: the number of target agent and message are not aligned, only sends matched messages")
18
+ rng = min(len(target_agent_ids), len(messages))
19
+ for i in range(rng):
20
+ dic = {}
21
+ dic['from'] = self._agent._id
22
+ dic['to'] = target_agent_ids[i]
23
+ dic['message'] = messages[i]
24
+ req['messages'].append(dic)
25
+ # * 发送至模拟器
26
+ await self._agent._client.social_service.Send(req=req)
27
+
28
+ # * 发送至AppHub
29
+ if self._agent.Hub != None and messages[0] != 'End':
30
+ # * 将信息中的第一条不同至pop
31
+ self._agent.Hub.Update(pop=messages[0])
@@ -0,0 +1,17 @@
1
+ import time
2
+ from .action import Action
3
+ from pycitysim.apphub import AgentMessage
4
+
5
+ class IdleAction(Action):
6
+ '''idle行为控制器'''
7
+ def __init__(self, agent) -> None:
8
+ super().__init__(agent)
9
+
10
+ async def Forward(self):
11
+ if len(self._agent.base['schedules']) > 0:
12
+ req = {'person_id': self._agent._id, 'schedules': []}
13
+ await self._agent._client.person_service.SetSchedule(req)
14
+ if self._agent.Hub != None:
15
+ self._agent.Hub.Update()
16
+
17
+
@@ -0,0 +1,80 @@
1
+ from .action import Action
2
+ from pycitysim.apphub import AgentMessage
3
+ import time
4
+
5
+ def encap_msg(msg, role='user', **kwargs):
6
+ dialog = {'role': role, 'content': msg}
7
+ dialog.update(kwargs)
8
+ return dialog
9
+
10
+ class ShopAction(Action):
11
+ '''Shop行为控制器'''
12
+ def __init__(self, agent) -> None:
13
+ super().__init__(agent)
14
+
15
+ async def Forward(self):
16
+ # * 与模拟器对接 - 暂时没有
17
+ # * 与AppHub对接
18
+ profile = self._agent.Image.get_profile()
19
+ self.consumption(profile)
20
+
21
+ def consumption(self, profile, mall_info):
22
+ dialogs = []
23
+ system_prompt = f'''
24
+ 你是一个在北京工作和生活的人。
25
+ {profile}
26
+ 现在是2024年1月。
27
+ 你需要为下一周的基本生活购买必需品。
28
+ '''
29
+ dialogs.append(encap_msg(system_prompt, 'system'))
30
+ actions_format = ['''{{'商品': 购买的商品的列表,'购买量': 每个商品的购买量,一个列表, '解释': '这种购买方式的原因'}}''']
31
+ actions_candidates = ['''【食品】
32
+ 米:10元/公斤
33
+ 面粉:7.5元/公斤
34
+ 新鲜蔬菜(如菠菜):7元/500克
35
+ 水果(如苹果):15元/公斤
36
+ 猪肉:30元/公斤
37
+ 鸡肉:20元/公斤
38
+ 鸡蛋:1.5元/个
39
+ 牛奶:10元/升''',
40
+ '''【清洁用品】
41
+ 洗衣液:30元/瓶
42
+ 洗洁精:20元/瓶
43
+ 垃圾袋:0.3元/个''',
44
+ '''【个人护理用品】
45
+ 牙膏:10元/支
46
+ 洗发水:30元/瓶
47
+ 沐浴露:35元/瓶
48
+ 面巾纸:5元/包''',
49
+ '''【其他】
50
+ 矿泉水:1.7元/瓶
51
+ 面包:8元/个
52
+ 辣条:3元/包''']
53
+
54
+ user_prompt = f'''
55
+ 首先确定你的消费预算。以如下格式回答,不要有冗余的文本!
56
+ {{'消费预算': 一个代表购买必需品需要消耗的钱的数量的数字}}
57
+ '''
58
+ dialogs.append(encap_msg(user_prompt))
59
+ # * 对接一:确定消费预算
60
+ self._agent.Hub.Update([AgentMessage(self._agent.Hub._agent_id, int(time.time()*1000), '我正在确定消费预算......', None, None)])
61
+ msg = self._agent._soul.text_request(dialogs)
62
+ self._agent.Hub.Update([AgentMessage(self._agent.Hub._agent_id, int(time.time()*1000), f'我的消费预算是: {msg}'), None, None])
63
+
64
+ dialogs.append(encap_msg(msg, 'assistant'))
65
+
66
+ # * 对接二:购物选择
67
+ for cand in actions_candidates:
68
+ user_prompt = f'''
69
+ 购物中心里有
70
+ {cand}
71
+ 你要买哪些商品,以如下格式回答,不要有冗余的文本!
72
+ {actions_format[0]}
73
+ '''
74
+ self._agent.Hub.Update([AgentMessage(self._agent.Hub._agent_id, int(time.time()*1000), f'我看到了\n {cand}', None, None)])
75
+ dialogs.append(encap_msg(user_prompt))
76
+ msg = self._agent._soul.text_request(dialogs)
77
+ self._agent.Hub.Update([AgentMessage(self._agent.Hub._agent_id, int(time.time()*1000), f'我的购买选择是: {msg}', None, None)])
78
+ dialogs.append(encap_msg(msg, 'assistant'))
79
+
80
+ self._agent.Hub.Update([AgentMessage(self._agent.Hub._agent_id, int(time.time()*1000), '购物完成', None, None)])
@@ -0,0 +1,37 @@
1
+ import time
2
+ from .action import Action
3
+ from pycitysim.apphub import AgentMessage
4
+
5
+ class TripAction(Action):
6
+ '''Trip行为控制器'''
7
+ def __init__(self, agent) -> None:
8
+ super().__init__(agent)
9
+
10
+ async def Forward(self):
11
+ now = self._agent.Scheduler.now
12
+ if now.is_set:
13
+ '''之前已经将schedule同步至模拟器了'''
14
+ if self._agent.Hub != None:
15
+ self._agent.Hub.Update(streetview=self._agent.Brain.Sence.sence_buffer['streetview'])
16
+ else:
17
+ '''同步schedule至模拟器'''
18
+ self._agent.Scheduler.now.is_set = True
19
+ departure_time = now.time
20
+ mode = now.mode
21
+ aoi_id = now.target_id_aoi
22
+ poi_id = now.target_id_poi
23
+ end = {'aoi_position': {'aoi_id': aoi_id, 'poi_id': poi_id}}
24
+ activity = now.description
25
+ trips = [{'mode': mode, 'end': end, 'departure_time': departure_time, 'activity': activity}]
26
+ set_schedule = [{'trips': trips, 'loop_count': 1, 'departure_time': departure_time}]
27
+
28
+ # * 与模拟器对接
29
+ req = {'person_id': self._agent._id, 'schedules': set_schedule}
30
+ await self._agent._client.person_service.SetSchedule(req)
31
+
32
+ # * 与AppHub对接
33
+ if self._agent.Hub != None:
34
+ messages = [AgentMessage(self._agent.Hub._agent_id, int(time.time()*1000), f'已到达出发时间, {activity}', None, None)]
35
+ self._agent.Hub.Update(messages)
36
+
37
+