pycityagent 1.0.0__py3-none-any.whl → 2.0.0a1__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.
Files changed (106) hide show
  1. pycityagent/__init__.py +7 -3
  2. pycityagent/agent.py +180 -284
  3. pycityagent/economy/__init__.py +5 -0
  4. pycityagent/economy/econ_client.py +307 -0
  5. pycityagent/environment/__init__.py +7 -0
  6. pycityagent/environment/interact/interact.py +141 -0
  7. pycityagent/environment/sence/__init__.py +0 -0
  8. pycityagent/{brain → environment/sence}/static.py +1 -1
  9. pycityagent/environment/sidecar/__init__.py +8 -0
  10. pycityagent/environment/sidecar/sidecarv2.py +109 -0
  11. pycityagent/environment/sim/__init__.py +27 -0
  12. pycityagent/environment/sim/aoi_service.py +38 -0
  13. pycityagent/environment/sim/client.py +126 -0
  14. pycityagent/environment/sim/clock_service.py +43 -0
  15. pycityagent/environment/sim/economy_services.py +191 -0
  16. pycityagent/environment/sim/lane_service.py +110 -0
  17. pycityagent/environment/sim/light_service.py +120 -0
  18. pycityagent/environment/sim/person_service.py +294 -0
  19. pycityagent/environment/sim/road_service.py +38 -0
  20. pycityagent/environment/sim/social_service.py +58 -0
  21. pycityagent/environment/simulator.py +369 -0
  22. pycityagent/environment/utils/__init__.py +8 -0
  23. pycityagent/environment/utils/geojson.py +26 -0
  24. pycityagent/environment/utils/grpc.py +57 -0
  25. pycityagent/environment/utils/map_utils.py +157 -0
  26. pycityagent/environment/utils/protobuf.py +39 -0
  27. pycityagent/llm/__init__.py +6 -0
  28. pycityagent/llm/embedding.py +136 -0
  29. pycityagent/llm/llm.py +430 -0
  30. pycityagent/llm/llmconfig.py +15 -0
  31. pycityagent/llm/utils.py +6 -0
  32. pycityagent/memory/__init__.py +11 -0
  33. pycityagent/memory/const.py +41 -0
  34. pycityagent/memory/memory.py +453 -0
  35. pycityagent/memory/memory_base.py +168 -0
  36. pycityagent/memory/profile.py +165 -0
  37. pycityagent/memory/self_define.py +165 -0
  38. pycityagent/memory/state.py +173 -0
  39. pycityagent/memory/utils.py +27 -0
  40. pycityagent/message/__init__.py +0 -0
  41. pycityagent/simulation/__init__.py +7 -0
  42. pycityagent/simulation/interview.py +36 -0
  43. pycityagent/simulation/simulation.py +286 -0
  44. pycityagent/simulation/survey/__init__.py +9 -0
  45. pycityagent/simulation/survey/manager.py +67 -0
  46. pycityagent/simulation/survey/models.py +49 -0
  47. pycityagent/simulation/ui/__init__.py +3 -0
  48. pycityagent/simulation/ui/interface.py +602 -0
  49. pycityagent/utils/__init__.py +0 -0
  50. pycityagent/utils/decorators.py +89 -0
  51. pycityagent/utils/parsers/__init__.py +12 -0
  52. pycityagent/utils/parsers/code_block_parser.py +37 -0
  53. pycityagent/utils/parsers/json_parser.py +86 -0
  54. pycityagent/utils/parsers/parser_base.py +60 -0
  55. pycityagent/workflow/__init__.py +22 -0
  56. pycityagent/workflow/block.py +137 -0
  57. pycityagent/workflow/prompt.py +72 -0
  58. pycityagent/workflow/tool.py +246 -0
  59. pycityagent/workflow/trigger.py +66 -0
  60. pycityagent-2.0.0a1.dist-info/METADATA +208 -0
  61. pycityagent-2.0.0a1.dist-info/RECORD +65 -0
  62. {pycityagent-1.0.0.dist-info → pycityagent-2.0.0a1.dist-info}/WHEEL +1 -2
  63. pycityagent/ac/__init__.py +0 -6
  64. pycityagent/ac/ac.py +0 -50
  65. pycityagent/ac/action.py +0 -14
  66. pycityagent/ac/controled.py +0 -13
  67. pycityagent/ac/converse.py +0 -31
  68. pycityagent/ac/idle.py +0 -17
  69. pycityagent/ac/shop.py +0 -80
  70. pycityagent/ac/trip.py +0 -37
  71. pycityagent/brain/__init__.py +0 -10
  72. pycityagent/brain/brain.py +0 -52
  73. pycityagent/brain/brainfc.py +0 -10
  74. pycityagent/brain/memory.py +0 -541
  75. pycityagent/brain/persistence/social.py +0 -1
  76. pycityagent/brain/persistence/spatial.py +0 -14
  77. pycityagent/brain/reason/shop.py +0 -37
  78. pycityagent/brain/reason/social.py +0 -148
  79. pycityagent/brain/reason/trip.py +0 -67
  80. pycityagent/brain/reason/user.py +0 -122
  81. pycityagent/brain/retrive/social.py +0 -6
  82. pycityagent/brain/scheduler.py +0 -408
  83. pycityagent/brain/sence.py +0 -375
  84. pycityagent/cc/__init__.py +0 -5
  85. pycityagent/cc/cc.py +0 -102
  86. pycityagent/cc/conve.py +0 -6
  87. pycityagent/cc/idle.py +0 -20
  88. pycityagent/cc/shop.py +0 -6
  89. pycityagent/cc/trip.py +0 -13
  90. pycityagent/cc/user.py +0 -13
  91. pycityagent/hubconnector/__init__.py +0 -3
  92. pycityagent/hubconnector/hubconnector.py +0 -137
  93. pycityagent/image/__init__.py +0 -3
  94. pycityagent/image/image.py +0 -158
  95. pycityagent/simulator.py +0 -161
  96. pycityagent/st/__init__.py +0 -4
  97. pycityagent/st/st.py +0 -96
  98. pycityagent/urbanllm/__init__.py +0 -3
  99. pycityagent/urbanllm/urbanllm.py +0 -132
  100. pycityagent-1.0.0.dist-info/LICENSE +0 -21
  101. pycityagent-1.0.0.dist-info/METADATA +0 -181
  102. pycityagent-1.0.0.dist-info/RECORD +0 -48
  103. pycityagent-1.0.0.dist-info/top_level.txt +0 -1
  104. /pycityagent/{brain/persistence/__init__.py → config.py} +0 -0
  105. /pycityagent/{brain/reason → environment/interact}/__init__.py +0 -0
  106. /pycityagent/{brain/retrive → environment/message}/__init__.py +0 -0
@@ -0,0 +1,286 @@
1
+ import asyncio
2
+ import json
3
+ import logging
4
+ from datetime import datetime, timedelta
5
+ from typing import Dict, List, Optional
6
+
7
+ from ..agent import Agent
8
+ from ..environment import Simulator
9
+ from .interview import InterviewManager
10
+ from .survey import QuestionType, Survey, SurveyManager
11
+ from .ui import InterviewUI
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class AgentSimulation:
17
+ """城市智能体模拟器"""
18
+
19
+ def __init__(self, simulator: Optional[Simulator] = None):
20
+ self.simulator = simulator
21
+ self._agents: Dict[str, Agent] = {}
22
+ self._interview_manager = InterviewManager()
23
+ self._interview_lock = asyncio.Lock()
24
+ self._start_time = datetime.now()
25
+ self._agent_run_times: Dict[str, datetime] = {} # 记录每个智能体的运行开始时间
26
+ self._ui: Optional[InterviewUI] = None
27
+ self._loop = asyncio.get_event_loop()
28
+ self._blocked_agents: List[str] = [] # 新增:持续阻塞的智能体列表
29
+ self._survey_manager = SurveyManager()
30
+
31
+ def add_agent(self, agent: Agent) -> None:
32
+ """添加智能体到模拟器"""
33
+ if agent._name in self._agents:
34
+ raise ValueError(f"智能体 {agent._name} 已存在")
35
+ self._agents[agent._name] = agent
36
+ self._agent_run_times[agent._name] = datetime.now()
37
+ logger.info(f"添加智能体: {agent._name}")
38
+
39
+ def remove_agent(self, agent_name: str) -> None:
40
+ """从模拟器中移除智能体"""
41
+ if agent_name in self._agents:
42
+ del self._agents[agent_name]
43
+ del self._agent_run_times[agent_name]
44
+ logger.info(f"移除智能体: {agent_name}")
45
+
46
+ def get_agent_runtime(self, agent_name: str) -> str:
47
+ """获取智能体运行时间"""
48
+ if agent_name not in self._agent_run_times:
49
+ return "-"
50
+ delta = datetime.now() - self._agent_run_times[agent_name]
51
+ hours = delta.seconds // 3600
52
+ minutes = (delta.seconds % 3600) // 60
53
+ seconds = delta.seconds % 60
54
+ return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
55
+
56
+ def get_total_runtime(self) -> str:
57
+ """获取总运行时间"""
58
+ delta = datetime.now() - self._start_time
59
+ hours = delta.seconds // 3600
60
+ minutes = (delta.seconds % 3600) // 60
61
+ seconds = delta.seconds % 60
62
+ return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
63
+
64
+ def export_chat_history(self, agent_name: str | None) -> str:
65
+ """导出对话历史
66
+
67
+ Args:
68
+ agent_name: 可选的智能体名称,如果提供则只导出该智能体的对话
69
+
70
+ Returns:
71
+ str: JSON格式的对话历史
72
+ """
73
+ history = (
74
+ self._interview_manager.get_agent_history(agent_name)
75
+ if agent_name
76
+ else self._interview_manager.get_recent_history(limit=1000)
77
+ )
78
+
79
+ # 转换为易读格式
80
+ formatted_history = []
81
+ for record in history:
82
+ formatted_history.append(
83
+ {
84
+ "timestamp": record.timestamp.strftime("%Y-%m-%d %H:%M:%S"),
85
+ "agent": record.agent_name,
86
+ "question": record.question,
87
+ "response": record.response,
88
+ "blocking": record.blocking,
89
+ }
90
+ )
91
+
92
+ return json.dumps(formatted_history, ensure_ascii=False, indent=2)
93
+
94
+ def toggle_agent_block(self, agent_name: str, blocking: bool) -> str:
95
+ """切换智能体的阻塞状态
96
+
97
+ Args:
98
+ agent_name: 能体名称
99
+ blocking: True表示阻塞,False表示取消阻塞
100
+
101
+ Returns:
102
+ str: 状态变更消息
103
+ """
104
+ if agent_name not in self._agents:
105
+ return f"找不到智能体 {agent_name}"
106
+
107
+ if blocking and agent_name not in self._blocked_agents:
108
+ self._blocked_agents.append(agent_name)
109
+ return f"已阻塞智能体 {agent_name}"
110
+ elif not blocking and agent_name in self._blocked_agents:
111
+ self._blocked_agents.remove(agent_name)
112
+ return f"已取消阻塞智能体 {agent_name}"
113
+
114
+ return f"智能体 {agent_name} 状态未变"
115
+
116
+ async def interview_agent(self, agent_name: str, question: str) -> str:
117
+ """采访指定智能体"""
118
+ agent = self._agents.get(agent_name)
119
+ if not agent:
120
+ return "找不到指定的智能体"
121
+
122
+ try:
123
+ response = await agent.generate_response(question)
124
+ # 记录采访历史
125
+ self._interview_manager.add_record(
126
+ agent_name,
127
+ question,
128
+ response,
129
+ blocking=(agent_name in self._blocked_agents),
130
+ )
131
+ return response
132
+
133
+ except Exception as e:
134
+ logger.error(f"采访过程出错: {str(e)}")
135
+ return f"采访过程出现错误: {str(e)}"
136
+
137
+ async def run(
138
+ self,
139
+ steps: int = -1,
140
+ interval: float = 1.0,
141
+ start_ui: bool = True,
142
+ server_name: str = "127.0.0.1",
143
+ server_port: int = 7860,
144
+ ):
145
+ """运行模拟器
146
+
147
+ Args:
148
+ steps: 运行步数,默认为-1表示无限运行
149
+ interval: 智能体forward间隔时间,单位为秒,默认1秒
150
+ start_ui: 是否启动UI,默认为True
151
+ server_name: UI服务器地址,默认为"127.0.0.1"
152
+ server_port: UI服务器端口,默认为7860
153
+ """
154
+ try:
155
+ self._interview_lock = asyncio.Lock()
156
+ # 初始化UI
157
+ if start_ui:
158
+ self._ui = InterviewUI(self)
159
+ interface = self._ui.create_interface()
160
+ interface.queue().launch(
161
+ server_name=server_name,
162
+ server_port=server_port,
163
+ prevent_thread_lock=True,
164
+ quiet=True,
165
+ )
166
+ print(
167
+ f"Gradio Frontend is running on http://{server_name}:{server_port}"
168
+ )
169
+
170
+ # 运行所有agents
171
+ tasks = []
172
+ for agent in self._agents.values():
173
+ tasks.append(self._run_agent(agent, steps, interval))
174
+
175
+ await asyncio.gather(*tasks)
176
+
177
+ except Exception as e:
178
+ logger.error(f"模拟器运行错误: {str(e)}")
179
+ raise
180
+
181
+ async def _run_agent(self, agent: Agent, steps: int = -1, interval: float = 1.0):
182
+ """运行单个agent的包装器
183
+
184
+ Args:
185
+ agent: 要运行的能体
186
+ steps: 运行步数,默认为-1表示无限运行
187
+ interval: 智能体forward间隔时间,单位为秒
188
+ """
189
+ step_count = 0
190
+ while steps == -1 or step_count < steps:
191
+ try:
192
+ if agent._name in self._blocked_agents:
193
+ await asyncio.sleep(interval)
194
+ continue
195
+
196
+ await agent.forward()
197
+ await asyncio.sleep(interval) # 控制运行频率
198
+ step_count += 1
199
+
200
+ except Exception as e:
201
+ logger.error(f"智能体 {agent._name} 运行错误: {str(e)}")
202
+ await asyncio.sleep(interval) # 发生错误时暂停一下
203
+
204
+ async def submit_survey(self, agent_name: str, survey_id: str) -> str:
205
+ """向智能体提交问卷
206
+
207
+ Args:
208
+ agent_name: 智能体名称
209
+ survey_id: 问卷ID
210
+
211
+ Returns:
212
+ str: 处理结果
213
+ """
214
+ agent = self._agents.get(agent_name)
215
+ if not agent:
216
+ return "找不到指定的智能体"
217
+
218
+ survey = self._survey_manager.get_survey(survey_id)
219
+ if not survey:
220
+ return "找不到指定的问卷"
221
+
222
+ try:
223
+ # 建问卷提示
224
+ prompt = f"""请以第一人称回答以下调查问卷:
225
+
226
+ 问卷标题: {survey.title}
227
+ 问卷说明: {survey.description}
228
+
229
+ """
230
+ for i, question in enumerate(survey.questions):
231
+ prompt += f"\n问题{i+1}. {question.content}"
232
+ if question.type in (
233
+ QuestionType.SINGLE_CHOICE,
234
+ QuestionType.MULTIPLE_CHOICE,
235
+ ):
236
+ prompt += "\n选项: " + ", ".join(question.options)
237
+ elif question.type == QuestionType.RATING:
238
+ prompt += (
239
+ f"\n(请给出{question.min_rating}-{question.max_rating}的评分)"
240
+ )
241
+ elif question.type == QuestionType.LIKERT:
242
+ prompt += "\n(1-强烈不同意, 2-不同意, 3-中立, 4-同意, 5-强烈同意)"
243
+
244
+ # 生成回答
245
+ response = await agent.generate_response(prompt)
246
+
247
+ # 存储原始回答
248
+ self._survey_manager.add_response(
249
+ survey_id, agent_name, {"raw_response": response, "parsed": False}
250
+ )
251
+
252
+ return response
253
+
254
+ except Exception as e:
255
+ logger.error(f"问卷处理出错: {str(e)}")
256
+ return f"问卷处理出现错误: {str(e)}"
257
+
258
+ def create_survey(self, **survey_data: dict) -> None:
259
+ """创建新问卷
260
+
261
+ Args:
262
+ survey_data: 问卷数据,包含 title, description, questions
263
+
264
+ Returns:
265
+ 更新后的问卷列表
266
+ """
267
+ self._survey_manager.create_survey(**survey_data) # type:ignore
268
+
269
+ def get_surveys(self) -> list:
270
+ """获取所有问卷"""
271
+ return self._survey_manager.get_all_surveys()
272
+
273
+ def get_survey_questions(self, survey_id: str) -> dict | None:
274
+ """获取指定问卷的问题列表
275
+
276
+ Args:
277
+ survey_id: 问卷ID
278
+
279
+ Returns:
280
+ 问卷数据,包含 title, description, questions
281
+ """
282
+ for _, survey in self._survey_manager._surveys.items():
283
+ survey_dict = survey.to_dict()
284
+ if survey_dict["id"] == survey_id:
285
+ return survey_dict
286
+ return None
@@ -0,0 +1,9 @@
1
+ from .models import QuestionType, Question, Survey
2
+ from .manager import SurveyManager
3
+
4
+ __all__ = [
5
+ 'QuestionType',
6
+ 'Question',
7
+ 'Survey',
8
+ 'SurveyManager'
9
+ ]
@@ -0,0 +1,67 @@
1
+ from typing import List, Dict, Optional
2
+ from datetime import datetime
3
+ import uuid
4
+ import json
5
+ from .models import Survey, Question, QuestionType
6
+
7
+ class SurveyManager:
8
+ def __init__(self):
9
+ self._surveys: Dict[str, Survey] = {}
10
+
11
+ def create_survey(self, title: str, description: str, questions: List[dict]) -> Survey:
12
+ """创建新问卷"""
13
+ survey_id = str(uuid.uuid4())
14
+
15
+ # 转换问题数据
16
+ survey_questions = []
17
+ for q in questions:
18
+ question = Question(
19
+ content=q["content"],
20
+ type=QuestionType(q["type"]),
21
+ required=q.get("required", True),
22
+ options=q.get("options", []),
23
+ min_rating=q.get("min_rating", 1),
24
+ max_rating=q.get("max_rating", 5)
25
+ )
26
+ survey_questions.append(question)
27
+
28
+ survey = Survey(
29
+ id=survey_id,
30
+ title=title,
31
+ description=description,
32
+ questions=survey_questions
33
+ )
34
+
35
+ self._surveys[survey_id] = survey
36
+ return survey
37
+
38
+ def get_survey(self, survey_id: str) -> Optional[Survey]:
39
+ """获取指定问卷"""
40
+ return self._surveys.get(survey_id)
41
+
42
+ def get_all_surveys(self) -> List[Survey]:
43
+ """获取所有问卷"""
44
+ return list(self._surveys.values())
45
+
46
+ def add_response(self, survey_id: str, agent_name: str, response: dict) -> bool:
47
+ """添加问卷回答"""
48
+ survey = self.get_survey(survey_id)
49
+ if not survey:
50
+ return False
51
+
52
+ survey.responses[agent_name] = {
53
+ "timestamp": datetime.now(),
54
+ **response
55
+ }
56
+ return True
57
+
58
+ def export_results(self, survey_id: str) -> str:
59
+ """导出问卷结果"""
60
+ survey = self.get_survey(survey_id)
61
+ if not survey:
62
+ return json.dumps({"error": "问卷不存在"})
63
+
64
+ return json.dumps({
65
+ "survey": survey.to_dict(),
66
+ "responses": survey.responses
67
+ }, ensure_ascii=False, indent=2)
@@ -0,0 +1,49 @@
1
+ from dataclasses import dataclass, field
2
+ from typing import List, Dict, Optional
3
+ from datetime import datetime
4
+ from enum import Enum
5
+ import uuid
6
+
7
+ class QuestionType(Enum):
8
+ TEXT = "文本"
9
+ SINGLE_CHOICE = "单选"
10
+ MULTIPLE_CHOICE = "多选"
11
+ RATING = "评分"
12
+ LIKERT = "李克特量表"
13
+
14
+ @dataclass
15
+ class Question:
16
+ content: str
17
+ type: QuestionType
18
+ required: bool = True
19
+ options: List[str] = field(default_factory=list)
20
+ min_rating: int = 1
21
+ max_rating: int = 5
22
+
23
+ def to_dict(self) -> dict:
24
+ return {
25
+ "content": self.content,
26
+ "type": self.type.value,
27
+ "required": self.required,
28
+ "options": self.options,
29
+ "min_rating": self.min_rating,
30
+ "max_rating": self.max_rating
31
+ }
32
+
33
+ @dataclass
34
+ class Survey:
35
+ id: str
36
+ title: str
37
+ description: str
38
+ questions: List[Question]
39
+ responses: Dict[str, dict] = field(default_factory=dict)
40
+ created_at: datetime = field(default_factory=datetime.now)
41
+
42
+ def to_dict(self) -> dict:
43
+ return {
44
+ "id": self.id,
45
+ "title": self.title,
46
+ "description": self.description,
47
+ "questions": [q.to_dict() for q in self.questions],
48
+ "response_count": len(self.responses)
49
+ }
@@ -0,0 +1,3 @@
1
+ from .interface import InterviewUI
2
+
3
+ __all__ = ["InterviewUI"]