pycityagent 1.0.0__py3-none-any.whl → 2.0.0a2__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 (110) 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 +29 -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/sim_env.py +145 -0
  21. pycityagent/environment/sim/social_service.py +58 -0
  22. pycityagent/environment/simulator.py +320 -0
  23. pycityagent/environment/utils/__init__.py +10 -0
  24. pycityagent/environment/utils/base64.py +16 -0
  25. pycityagent/environment/utils/const.py +242 -0
  26. pycityagent/environment/utils/geojson.py +26 -0
  27. pycityagent/environment/utils/grpc.py +57 -0
  28. pycityagent/environment/utils/map_utils.py +157 -0
  29. pycityagent/environment/utils/port.py +11 -0
  30. pycityagent/environment/utils/protobuf.py +39 -0
  31. pycityagent/llm/__init__.py +6 -0
  32. pycityagent/llm/embedding.py +136 -0
  33. pycityagent/llm/llm.py +430 -0
  34. pycityagent/llm/llmconfig.py +15 -0
  35. pycityagent/llm/utils.py +6 -0
  36. pycityagent/memory/__init__.py +11 -0
  37. pycityagent/memory/const.py +41 -0
  38. pycityagent/memory/memory.py +453 -0
  39. pycityagent/memory/memory_base.py +168 -0
  40. pycityagent/memory/profile.py +165 -0
  41. pycityagent/memory/self_define.py +165 -0
  42. pycityagent/memory/state.py +173 -0
  43. pycityagent/memory/utils.py +27 -0
  44. pycityagent/message/__init__.py +0 -0
  45. pycityagent/simulation/__init__.py +7 -0
  46. pycityagent/simulation/interview.py +36 -0
  47. pycityagent/simulation/simulation.py +352 -0
  48. pycityagent/simulation/survey/__init__.py +9 -0
  49. pycityagent/simulation/survey/manager.py +67 -0
  50. pycityagent/simulation/survey/models.py +49 -0
  51. pycityagent/simulation/ui/__init__.py +3 -0
  52. pycityagent/simulation/ui/interface.py +602 -0
  53. pycityagent/utils/__init__.py +0 -0
  54. pycityagent/utils/decorators.py +89 -0
  55. pycityagent/utils/parsers/__init__.py +12 -0
  56. pycityagent/utils/parsers/code_block_parser.py +37 -0
  57. pycityagent/utils/parsers/json_parser.py +86 -0
  58. pycityagent/utils/parsers/parser_base.py +60 -0
  59. pycityagent/workflow/__init__.py +24 -0
  60. pycityagent/workflow/block.py +164 -0
  61. pycityagent/workflow/prompt.py +72 -0
  62. pycityagent/workflow/tool.py +246 -0
  63. pycityagent/workflow/trigger.py +150 -0
  64. pycityagent-2.0.0a2.dist-info/METADATA +208 -0
  65. pycityagent-2.0.0a2.dist-info/RECORD +69 -0
  66. {pycityagent-1.0.0.dist-info → pycityagent-2.0.0a2.dist-info}/WHEEL +1 -2
  67. pycityagent/ac/__init__.py +0 -6
  68. pycityagent/ac/ac.py +0 -50
  69. pycityagent/ac/action.py +0 -14
  70. pycityagent/ac/controled.py +0 -13
  71. pycityagent/ac/converse.py +0 -31
  72. pycityagent/ac/idle.py +0 -17
  73. pycityagent/ac/shop.py +0 -80
  74. pycityagent/ac/trip.py +0 -37
  75. pycityagent/brain/__init__.py +0 -10
  76. pycityagent/brain/brain.py +0 -52
  77. pycityagent/brain/brainfc.py +0 -10
  78. pycityagent/brain/memory.py +0 -541
  79. pycityagent/brain/persistence/social.py +0 -1
  80. pycityagent/brain/persistence/spatial.py +0 -14
  81. pycityagent/brain/reason/shop.py +0 -37
  82. pycityagent/brain/reason/social.py +0 -148
  83. pycityagent/brain/reason/trip.py +0 -67
  84. pycityagent/brain/reason/user.py +0 -122
  85. pycityagent/brain/retrive/social.py +0 -6
  86. pycityagent/brain/scheduler.py +0 -408
  87. pycityagent/brain/sence.py +0 -375
  88. pycityagent/cc/__init__.py +0 -5
  89. pycityagent/cc/cc.py +0 -102
  90. pycityagent/cc/conve.py +0 -6
  91. pycityagent/cc/idle.py +0 -20
  92. pycityagent/cc/shop.py +0 -6
  93. pycityagent/cc/trip.py +0 -13
  94. pycityagent/cc/user.py +0 -13
  95. pycityagent/hubconnector/__init__.py +0 -3
  96. pycityagent/hubconnector/hubconnector.py +0 -137
  97. pycityagent/image/__init__.py +0 -3
  98. pycityagent/image/image.py +0 -158
  99. pycityagent/simulator.py +0 -161
  100. pycityagent/st/__init__.py +0 -4
  101. pycityagent/st/st.py +0 -96
  102. pycityagent/urbanllm/__init__.py +0 -3
  103. pycityagent/urbanllm/urbanllm.py +0 -132
  104. pycityagent-1.0.0.dist-info/LICENSE +0 -21
  105. pycityagent-1.0.0.dist-info/METADATA +0 -181
  106. pycityagent-1.0.0.dist-info/RECORD +0 -48
  107. pycityagent-1.0.0.dist-info/top_level.txt +0 -1
  108. /pycityagent/{brain/persistence/__init__.py → config.py} +0 -0
  109. /pycityagent/{brain/reason → environment/interact}/__init__.py +0 -0
  110. /pycityagent/{brain/retrive → environment/message}/__init__.py +0 -0
@@ -0,0 +1,157 @@
1
+ import math
2
+ from typing import Dict, List, Literal, Optional, Tuple, Union
3
+
4
+ import numpy as np
5
+
6
+
7
+ def get_angle(x, y):
8
+ return math.atan2(y, x) * 180 / math.pi
9
+
10
+
11
+ def point_on_line_given_distance(start_node, end_node, distance):
12
+ """
13
+ Given two points (start_point and end_point) defining a line, and a distance s to travel along the line,
14
+ return the coordinates of the point reached after traveling s units along the line, starting from start_point.
15
+
16
+ Args:
17
+ start_point (tuple): Tuple of (x, y) representing the starting point on the line.
18
+ end_point (tuple): Tuple of (x, y) representing the ending point on the line.
19
+ distance (float): Distance to travel along the line, starting from start_point.
20
+
21
+ Returns:
22
+ tuple: Tuple of (x, y) representing the new point reached after traveling s units along the line.
23
+ """
24
+
25
+ x1, y1 = start_node["x"], start_node["y"]
26
+ x2, y2 = end_node["x"], end_node["y"]
27
+
28
+ # Calculate the slope m and the y-intercept b of the line
29
+ if x1 == x2:
30
+ # Vertical line, distance is only along the y-axis
31
+ return (x1, y1 + distance if distance >= 0 else y1 - abs(distance))
32
+ else:
33
+ m = (y2 - y1) / (x2 - x1)
34
+ b = y1 - m * x1
35
+
36
+ # Calculate the direction vector (dx, dy) along the line
37
+ dx = (x2 - x1) / math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
38
+ dy = (y2 - y1) / math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
39
+
40
+ # Scale the direction vector by the given distance
41
+ scaled_dx = dx * distance
42
+ scaled_dy = dy * distance
43
+
44
+ # Calculate the new point's coordinates
45
+ x = x1 + scaled_dx
46
+ y = y1 + scaled_dy
47
+
48
+ return [x, y]
49
+
50
+
51
+ def get_key_index_in_lane(
52
+ nodes: List[Dict[str, float]],
53
+ distance: float,
54
+ direction: Union[Literal["front"], Literal["back"]],
55
+ ) -> int:
56
+ if direction == "front":
57
+ _nodes = [n for n in nodes]
58
+ _index_offset, _index_factor = 0, 1
59
+ elif direction == "back":
60
+ _nodes = [n for n in nodes[::-1]]
61
+ _index_offset, _index_factor = len(_nodes) - 1, -1
62
+ else:
63
+ raise ValueError(f"Invalid direction type {direction}!")
64
+ _lane_points: List[Tuple[float, float, float]] = [
65
+ (n["x"], n["y"], n.get("z", 0)) for n in _nodes
66
+ ]
67
+ _line_lengths: List[float] = [0.0 for _ in range(len(_nodes))]
68
+ _s = 0.0
69
+ for i, (cur_p, next_p) in enumerate(zip(_lane_points[:-1], _lane_points[1:])):
70
+ _s += math.hypot(next_p[0] - cur_p[0], next_p[1] - cur_p[1])
71
+ _line_lengths[i + 1] = _s
72
+ s = np.clip(distance, _line_lengths[0], _line_lengths[-1])
73
+ _key_index = 0
74
+ for (
75
+ prev_s,
76
+ cur_s,
77
+ ) in zip(_line_lengths[:-1], _line_lengths[1:]):
78
+ if prev_s <= s < cur_s:
79
+ break
80
+ _key_index += 1
81
+ return _index_offset + _index_factor * _key_index
82
+
83
+
84
+ def get_xy_in_lane(
85
+ nodes: List[Dict[str, float]],
86
+ distance: float,
87
+ direction: Union[Literal["front"], Literal["back"]],
88
+ ) -> Tuple[float, float]:
89
+ if direction == "front":
90
+ _nodes = [n for n in nodes]
91
+ elif direction == "back":
92
+ _nodes = [n for n in nodes[::-1]]
93
+ else:
94
+ raise ValueError(f"Invalid direction type {direction}!")
95
+ _lane_points: List[Tuple[float, float, float]] = [
96
+ (n["x"], n["y"], n.get("z", 0)) for n in _nodes
97
+ ]
98
+ _line_lengths: List[float] = [0.0 for _ in range(len(_nodes))]
99
+ _s = 0.0
100
+ for i, (cur_p, next_p) in enumerate(zip(_lane_points[:-1], _lane_points[1:])):
101
+ _s += math.hypot(next_p[0] - cur_p[0], next_p[1] - cur_p[1])
102
+ _line_lengths[i + 1] = _s
103
+ s = np.clip(distance, _line_lengths[0], _line_lengths[-1])
104
+ for prev_s, prev_p, cur_s, cur_p in zip(
105
+ _line_lengths[:-1],
106
+ _lane_points[:-1],
107
+ _line_lengths[1:],
108
+ _lane_points[1:],
109
+ ):
110
+ if prev_s <= s < cur_s:
111
+ _delta_x, _delta_y, _delta_z = [
112
+ cur_p[_idx] - prev_p[_idx] for _idx in [0, 1, 2]
113
+ ]
114
+ _blend_x, _blend_y, _blend_z = [prev_p[_idx] for _idx in [0, 1, 2]]
115
+ _ratio = (s - prev_s) / (cur_s - prev_s)
116
+ return (
117
+ _blend_x + _ratio * _delta_x,
118
+ _blend_y + _ratio * _delta_y,
119
+ _blend_z + _ratio * _delta_z,
120
+ )[:2]
121
+ return _lane_points[-1][:2]
122
+
123
+
124
+ def get_direction_by_s(
125
+ nodes: List[Dict[str, float]],
126
+ distance: float,
127
+ direction: Union[Literal["front"], Literal["back"]],
128
+ ) -> float:
129
+ if direction == "front":
130
+ _nodes = [n for n in nodes]
131
+ elif direction == "back":
132
+ _nodes = [n for n in nodes[::-1]]
133
+ else:
134
+ raise ValueError(f"Invalid direction type {direction}!")
135
+ _lane_points: List[Tuple[float, float, float]] = [
136
+ (n["x"], n["y"], n.get("z", 0)) for n in _nodes
137
+ ]
138
+ _line_lengths: List[float] = [0.0 for _ in range(len(_nodes))]
139
+ _line_directions: List[Tuple[float, float]] = []
140
+ _s = 0.0
141
+ for i, (cur_p, next_p) in enumerate(zip(_lane_points[:-1], _lane_points[1:])):
142
+ _s += math.hypot(next_p[0] - cur_p[0], next_p[1] - cur_p[1])
143
+ _line_lengths[i + 1] = _s
144
+ for i, (cur_p, next_p) in enumerate(zip(_lane_points[:-1], _lane_points[1:])):
145
+ _direction = math.atan2(next_p[1] - cur_p[1], next_p[0] - cur_p[0])
146
+ _pitch = math.atan2(
147
+ next_p[2] - cur_p[2],
148
+ math.hypot(next_p[0] - cur_p[0], next_p[1] - cur_p[1]),
149
+ )
150
+ _line_directions.append((_direction / math.pi * 180, _pitch / math.pi * 180))
151
+ s = np.clip(distance, _line_lengths[0], _line_lengths[-1])
152
+ for prev_s, cur_s, direcs in zip(
153
+ _line_lengths[:-1], _line_lengths[1:], _line_directions
154
+ ):
155
+ if prev_s <= s < cur_s:
156
+ return direcs[0]
157
+ return _line_directions[-1][0]
@@ -0,0 +1,11 @@
1
+ import socket
2
+ from contextlib import closing
3
+
4
+ __all__ = ["find_free_port"]
5
+
6
+
7
+ def find_free_port():
8
+ with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
9
+ s.bind(("", 0))
10
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
11
+ return s.getsockname()[1]
@@ -0,0 +1,39 @@
1
+ from typing import Any, Awaitable, TypeVar, Union, Dict
2
+ from google.protobuf.message import Message
3
+ from google.protobuf.json_format import MessageToDict
4
+
5
+ __all__ = ["parse", "async_parse"]
6
+
7
+ T = TypeVar("T", bound=Message)
8
+
9
+
10
+ def parse(res: T, dict_return: bool) -> Union[Dict[str, Any], T]:
11
+ """
12
+ 将Protobuf返回值转换为dict或者原始值
13
+ Convert Protobuf return value to dict or original value
14
+ """
15
+ if dict_return:
16
+ return MessageToDict(
17
+ res,
18
+ including_default_value_fields=True,
19
+ preserving_proto_field_name=True,
20
+ use_integers_for_enums=True,
21
+ )
22
+ else:
23
+ return res
24
+
25
+
26
+ async def async_parse(res: Awaitable[T], dict_return: bool) -> Union[Dict[str, Any], T]:
27
+ """
28
+ 将Protobuf await返回值转换为dict或者原始值
29
+ Convert Protobuf await return value to dict or original value
30
+ """
31
+ if dict_return:
32
+ return MessageToDict(
33
+ await res,
34
+ including_default_value_fields=True,
35
+ preserving_proto_field_name=True,
36
+ use_integers_for_enums=True,
37
+ )
38
+ else:
39
+ return await res
@@ -0,0 +1,6 @@
1
+ """LLM相关模块"""
2
+
3
+ from .llm import LLM, LLMConfig
4
+ from .embedding import SimpleEmbedding
5
+
6
+ __all__ = ["LLM", "LLMConfig", "SimpleEmbedding"]
@@ -0,0 +1,136 @@
1
+ """简单的基于内存的embedding实现"""
2
+
3
+ import numpy as np
4
+ from typing import List, Dict, Optional
5
+ import hashlib
6
+ import json
7
+
8
+ class SimpleEmbedding:
9
+ """简单的基于内存的embedding实现
10
+
11
+ 使用简单的词袋模型(Bag of Words)和TF-IDF来生成文本的向量表示。
12
+ 所有向量都保存在内存中,适用于小规模应用。
13
+ """
14
+
15
+ def __init__(self, vector_dim: int = 128, cache_size: int = 1000):
16
+ """初始化
17
+
18
+ Args:
19
+ vector_dim: 向量维度
20
+ cache_size: 缓存大小,超过此大小将清除最早的缓存
21
+ """
22
+ self.vector_dim = vector_dim
23
+ self.cache_size = cache_size
24
+ self._cache: Dict[str, np.ndarray] = {}
25
+ self._vocab: Dict[str, int] = {} # 词汇表
26
+ self._idf: Dict[str, float] = {} # 逆文档频率
27
+ self._doc_count = 0 # 文档总数
28
+
29
+ def _text_to_hash(self, text: str) -> str:
30
+ """将文本转换为hash值"""
31
+ return hashlib.md5(text.encode()).hexdigest()
32
+
33
+ def _tokenize(self, text: str) -> List[str]:
34
+ """简单的分词"""
35
+ # 这里使用简单的空格分词,实际应用中可以使用更复杂的分词方法
36
+ return text.lower().split()
37
+
38
+ def _update_vocab(self, tokens: List[str]):
39
+ """更新词汇表"""
40
+ for token in set(tokens): # 使用set去重
41
+ if token not in self._vocab:
42
+ self._vocab[token] = len(self._vocab)
43
+
44
+ def _update_idf(self, tokens: List[str]):
45
+ """更新IDF值"""
46
+ self._doc_count += 1
47
+ unique_tokens = set(tokens)
48
+ for token in unique_tokens:
49
+ self._idf[token] = self._idf.get(token, 0) + 1
50
+
51
+ def _calculate_tf(self, tokens: List[str]) -> Dict[str, float]:
52
+ """计算词频(TF)"""
53
+ tf = {}
54
+ total_tokens = len(tokens)
55
+ for token in tokens:
56
+ tf[token] = tf.get(token, 0) + 1
57
+ # 归一化
58
+ for token in tf:
59
+ tf[token] /= total_tokens
60
+ return tf
61
+
62
+ def _calculate_tfidf(self, tokens: List[str]) -> np.ndarray:
63
+ """计算TF-IDF向量"""
64
+ vector = np.zeros(self.vector_dim)
65
+ tf = self._calculate_tf(tokens)
66
+
67
+ for token, tf_value in tf.items():
68
+ if token in self._idf:
69
+ idf = np.log(self._doc_count / self._idf[token])
70
+ idx = self._vocab[token] % self.vector_dim # 使用取模运算来控制向量维度
71
+ vector[idx] += tf_value * idf
72
+
73
+ # L2归一化
74
+ norm = np.linalg.norm(vector)
75
+ if norm > 0:
76
+ vector /= norm
77
+
78
+ return vector
79
+
80
+ async def embed(self, text: str) -> np.ndarray:
81
+ """生成文本的向量表示
82
+
83
+ Args:
84
+ text: 输入文本
85
+
86
+ Returns:
87
+ np.ndarray: 文本的向量表示
88
+ """
89
+ # 检查缓存
90
+ text_hash = self._text_to_hash(text)
91
+ if text_hash in self._cache:
92
+ return self._cache[text_hash]
93
+
94
+ # 分词
95
+ tokens = self._tokenize(text)
96
+ if not tokens:
97
+ return np.zeros(self.vector_dim)
98
+
99
+ # 更新词汇表和IDF
100
+ self._update_vocab(tokens)
101
+ self._update_idf(tokens)
102
+
103
+ # 计算向量
104
+ vector = self._calculate_tfidf(tokens)
105
+
106
+ # 更新缓存
107
+ if len(self._cache) >= self.cache_size:
108
+ # 删除最早的缓存
109
+ oldest_key = next(iter(self._cache))
110
+ del self._cache[oldest_key]
111
+ self._cache[text_hash] = vector
112
+
113
+ return vector
114
+
115
+ def save(self, file_path: str):
116
+ """保存模型"""
117
+ state = {
118
+ 'vector_dim': self.vector_dim,
119
+ 'cache_size': self.cache_size,
120
+ 'vocab': self._vocab,
121
+ 'idf': self._idf,
122
+ 'doc_count': self._doc_count
123
+ }
124
+ with open(file_path, 'w') as f:
125
+ json.dump(state, f)
126
+
127
+ def load(self, file_path: str):
128
+ """加载模型"""
129
+ with open(file_path, 'r') as f:
130
+ state = json.load(f)
131
+ self.vector_dim = state['vector_dim']
132
+ self.cache_size = state['cache_size']
133
+ self._vocab = state['vocab']
134
+ self._idf = state['idf']
135
+ self._doc_count = state['doc_count']
136
+ self._cache = {} # 清空缓存