pycityagent 2.0.0a43__cp311-cp311-macosx_11_0_arm64.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.
- pycityagent/__init__.py +23 -0
- pycityagent/agent.py +833 -0
- pycityagent/cli/wrapper.py +44 -0
- pycityagent/economy/__init__.py +5 -0
- pycityagent/economy/econ_client.py +355 -0
- pycityagent/environment/__init__.py +7 -0
- pycityagent/environment/interact/__init__.py +0 -0
- pycityagent/environment/interact/interact.py +198 -0
- pycityagent/environment/message/__init__.py +0 -0
- pycityagent/environment/sence/__init__.py +0 -0
- pycityagent/environment/sence/static.py +416 -0
- pycityagent/environment/sidecar/__init__.py +8 -0
- pycityagent/environment/sidecar/sidecarv2.py +109 -0
- pycityagent/environment/sim/__init__.py +29 -0
- pycityagent/environment/sim/aoi_service.py +39 -0
- pycityagent/environment/sim/client.py +126 -0
- pycityagent/environment/sim/clock_service.py +44 -0
- pycityagent/environment/sim/economy_services.py +192 -0
- pycityagent/environment/sim/lane_service.py +111 -0
- pycityagent/environment/sim/light_service.py +122 -0
- pycityagent/environment/sim/person_service.py +295 -0
- pycityagent/environment/sim/road_service.py +39 -0
- pycityagent/environment/sim/sim_env.py +145 -0
- pycityagent/environment/sim/social_service.py +59 -0
- pycityagent/environment/simulator.py +331 -0
- pycityagent/environment/utils/__init__.py +14 -0
- pycityagent/environment/utils/base64.py +16 -0
- pycityagent/environment/utils/const.py +244 -0
- pycityagent/environment/utils/geojson.py +24 -0
- pycityagent/environment/utils/grpc.py +57 -0
- pycityagent/environment/utils/map_utils.py +157 -0
- pycityagent/environment/utils/port.py +11 -0
- pycityagent/environment/utils/protobuf.py +41 -0
- pycityagent/llm/__init__.py +11 -0
- pycityagent/llm/embeddings.py +231 -0
- pycityagent/llm/llm.py +377 -0
- pycityagent/llm/llmconfig.py +13 -0
- pycityagent/llm/utils.py +6 -0
- pycityagent/memory/__init__.py +13 -0
- pycityagent/memory/const.py +43 -0
- pycityagent/memory/faiss_query.py +302 -0
- pycityagent/memory/memory.py +448 -0
- pycityagent/memory/memory_base.py +170 -0
- pycityagent/memory/profile.py +165 -0
- pycityagent/memory/self_define.py +165 -0
- pycityagent/memory/state.py +173 -0
- pycityagent/memory/utils.py +28 -0
- pycityagent/message/__init__.py +3 -0
- pycityagent/message/messager.py +88 -0
- pycityagent/metrics/__init__.py +6 -0
- pycityagent/metrics/mlflow_client.py +147 -0
- pycityagent/metrics/utils/const.py +0 -0
- pycityagent/pycityagent-sim +0 -0
- pycityagent/pycityagent-ui +0 -0
- pycityagent/simulation/__init__.py +8 -0
- pycityagent/simulation/agentgroup.py +580 -0
- pycityagent/simulation/simulation.py +634 -0
- pycityagent/simulation/storage/pg.py +184 -0
- pycityagent/survey/__init__.py +4 -0
- pycityagent/survey/manager.py +54 -0
- pycityagent/survey/models.py +120 -0
- pycityagent/utils/__init__.py +11 -0
- pycityagent/utils/avro_schema.py +109 -0
- pycityagent/utils/decorators.py +99 -0
- pycityagent/utils/parsers/__init__.py +13 -0
- pycityagent/utils/parsers/code_block_parser.py +37 -0
- pycityagent/utils/parsers/json_parser.py +86 -0
- pycityagent/utils/parsers/parser_base.py +60 -0
- pycityagent/utils/pg_query.py +92 -0
- pycityagent/utils/survey_util.py +53 -0
- pycityagent/workflow/__init__.py +26 -0
- pycityagent/workflow/block.py +211 -0
- pycityagent/workflow/prompt.py +79 -0
- pycityagent/workflow/tool.py +240 -0
- pycityagent/workflow/trigger.py +163 -0
- pycityagent-2.0.0a43.dist-info/LICENSE +21 -0
- pycityagent-2.0.0a43.dist-info/METADATA +235 -0
- pycityagent-2.0.0a43.dist-info/RECORD +81 -0
- pycityagent-2.0.0a43.dist-info/WHEEL +5 -0
- pycityagent-2.0.0a43.dist-info/entry_points.txt +3 -0
- pycityagent-2.0.0a43.dist-info/top_level.txt +3 -0
@@ -0,0 +1,302 @@
|
|
1
|
+
import asyncio
|
2
|
+
from collections.abc import Sequence
|
3
|
+
from typing import Any, Literal, Optional, Union
|
4
|
+
|
5
|
+
import faiss
|
6
|
+
import numpy as np
|
7
|
+
from langchain_community.docstore.in_memory import InMemoryDocstore
|
8
|
+
from langchain_community.vectorstores import FAISS
|
9
|
+
from langchain_core.documents import Document
|
10
|
+
from langchain_core.embeddings import Embeddings
|
11
|
+
|
12
|
+
from ..utils.decorators import lock_decorator
|
13
|
+
|
14
|
+
|
15
|
+
class FaissQuery:
|
16
|
+
def __init__(
|
17
|
+
self,
|
18
|
+
embeddings: Optional[Embeddings] = None,
|
19
|
+
index_type: Any = faiss.IndexFlatL2,
|
20
|
+
dimension: Optional[int] = None,
|
21
|
+
) -> None:
|
22
|
+
self._embeddings = embeddings
|
23
|
+
self._lock = asyncio.Lock()
|
24
|
+
if embeddings is None:
|
25
|
+
self._index = None
|
26
|
+
self._vectors_store = None
|
27
|
+
else:
|
28
|
+
if dimension is None:
|
29
|
+
dimension = len(embeddings.embed_query("hello world"))
|
30
|
+
self._index = index_type(dimension)
|
31
|
+
self._vectors_store = FAISS(
|
32
|
+
embedding_function=embeddings,
|
33
|
+
index=self._index,
|
34
|
+
docstore=InMemoryDocstore(),
|
35
|
+
index_to_docstore_id={},
|
36
|
+
)
|
37
|
+
|
38
|
+
@property
|
39
|
+
def embeddings(
|
40
|
+
self,
|
41
|
+
) -> Embeddings:
|
42
|
+
if self._embeddings is None:
|
43
|
+
raise RuntimeError(f"No embedding set, please `set_embeddings` first!")
|
44
|
+
return self._embeddings
|
45
|
+
|
46
|
+
@property
|
47
|
+
def vectors_store(
|
48
|
+
self,
|
49
|
+
) -> FAISS:
|
50
|
+
if self._vectors_store is None:
|
51
|
+
raise RuntimeError(f"No embedding set, thus no vector stores initialized!")
|
52
|
+
return self._vectors_store
|
53
|
+
|
54
|
+
@lock_decorator
|
55
|
+
async def add_documents(
|
56
|
+
self,
|
57
|
+
agent_id: int,
|
58
|
+
documents: Union[str, Sequence[str]],
|
59
|
+
extra_tags: Optional[dict] = None,
|
60
|
+
) -> list[str]:
|
61
|
+
if isinstance(documents, str):
|
62
|
+
documents = [documents]
|
63
|
+
_metadata = {"_id": agent_id}
|
64
|
+
if extra_tags is not None:
|
65
|
+
_metadata.update(extra_tags)
|
66
|
+
to_add_documents = [
|
67
|
+
Document(page_content=doc, metadata=_metadata) for doc in documents
|
68
|
+
]
|
69
|
+
return await self.vectors_store.aadd_documents(
|
70
|
+
documents=to_add_documents,
|
71
|
+
)
|
72
|
+
|
73
|
+
@lock_decorator
|
74
|
+
async def delete_documents(
|
75
|
+
self,
|
76
|
+
to_delete_ids: list[str],
|
77
|
+
):
|
78
|
+
await self.vectors_store.adelete(
|
79
|
+
ids=to_delete_ids,
|
80
|
+
)
|
81
|
+
|
82
|
+
@lock_decorator
|
83
|
+
async def similarity_search(
|
84
|
+
self,
|
85
|
+
query: str,
|
86
|
+
agent_id: int,
|
87
|
+
k: int = 4,
|
88
|
+
fetch_k: int = 20,
|
89
|
+
return_score_type: Union[
|
90
|
+
Literal["none"], Literal["similarity_score"], Literal["L2-distance"]
|
91
|
+
] = "none",
|
92
|
+
filter: Optional[dict] = None,
|
93
|
+
) -> Union[list[tuple[str, dict]], list[tuple[str, float, dict]]]:
|
94
|
+
"""
|
95
|
+
Return content most similar to the given query.
|
96
|
+
|
97
|
+
Args:
|
98
|
+
query (str): The text to look up documents similar to.
|
99
|
+
agent_id (int): The identifier of the agent to filter specific documents. Only documents associated with this agent will be considered.
|
100
|
+
k (int, optional): The number of top similar contents to return. Defaults to 4.
|
101
|
+
fetch_k (int, optional): The number of documents to fetch before applying any filters. Defaults to 20.
|
102
|
+
return_score_type (Union[Literal["none"], Literal["similarity_score"], Literal["L2-distance"]], optional):
|
103
|
+
Specifies whether and how to return similarity scores with the results:
|
104
|
+
- "none": Do not return scores; only return the contents (default).
|
105
|
+
- "similarity_score": Return a tuple of content and its similarity score.
|
106
|
+
- "L2-distance": Return a tuple of content and its L2 distance from the query.
|
107
|
+
filter (dict, optional): The filter dict for metadata.
|
108
|
+
|
109
|
+
Returns:
|
110
|
+
Union[list[tuple[str,dict]], list[tuple[str, float,dict]]]:
|
111
|
+
Depending on the `return_score_type` parameter, returns either a list of strings representing the top-k similar contents,
|
112
|
+
or a list of tuples where each tuple contains a string and a floating-point score.
|
113
|
+
"""
|
114
|
+
_filter = {
|
115
|
+
"_id": agent_id,
|
116
|
+
}
|
117
|
+
if filter is not None:
|
118
|
+
_filter.update(filter)
|
119
|
+
if return_score_type == "L2-distance":
|
120
|
+
_result = await self.vectors_store.asimilarity_search_with_score(
|
121
|
+
query=query,
|
122
|
+
k=k,
|
123
|
+
filter=_filter,
|
124
|
+
fetch_k=fetch_k,
|
125
|
+
)
|
126
|
+
return [(r.page_content, s, r.metadata) for r, s in _result]
|
127
|
+
elif return_score_type == "none":
|
128
|
+
_result = await self.vectors_store.asimilarity_search(
|
129
|
+
query=query,
|
130
|
+
k=k,
|
131
|
+
filter=_filter,
|
132
|
+
fetch_k=fetch_k,
|
133
|
+
)
|
134
|
+
return [(r.page_content, r.metadata) for r in _result]
|
135
|
+
elif return_score_type == "similarity_score":
|
136
|
+
_result = await self.vectors_store.asimilarity_search_with_relevance_scores(
|
137
|
+
query=query,
|
138
|
+
k=k,
|
139
|
+
filter=_filter,
|
140
|
+
fetch_k=fetch_k,
|
141
|
+
)
|
142
|
+
return [(r.page_content, s, r.metadata) for r, s in _result]
|
143
|
+
else:
|
144
|
+
raise ValueError(f"Invalid `return_score_type` {return_score_type}!")
|
145
|
+
|
146
|
+
@lock_decorator
|
147
|
+
async def similarity_search_by_embedding(
|
148
|
+
self,
|
149
|
+
embedding: list[float],
|
150
|
+
agent_id: int,
|
151
|
+
k: int = 4,
|
152
|
+
fetch_k: int = 20,
|
153
|
+
return_score_type: Union[Literal["none"], Literal["L2-distance"]] = "none",
|
154
|
+
filter: Optional[dict] = None,
|
155
|
+
) -> Union[list[tuple[str, dict]], list[tuple[str, float, dict]]]:
|
156
|
+
"""
|
157
|
+
Return content most similar to the given query.
|
158
|
+
|
159
|
+
Args:
|
160
|
+
embedding (list[float]): The vector to look up documents similar to.
|
161
|
+
agent_id (int): The identifier of the agent to filter specific documents. Only documents associated with this agent will be considered.
|
162
|
+
k (int, optional): The number of top similar contents to return. Defaults to 4.
|
163
|
+
fetch_k (int, optional): The number of documents to fetch before applying any filters. Defaults to 20.
|
164
|
+
return_score_type (Union[Literal["none"], Literal["similarity_score"], Literal["L2-distance"]], optional):
|
165
|
+
Specifies whether and how to return similarity scores with the results:
|
166
|
+
- "none": Do not return scores; only return the contents (default).
|
167
|
+
- "L2-distance": Return a tuple of content and its L2 distance from the query.
|
168
|
+
filter (dict, optional): The filter dict for metadata.
|
169
|
+
|
170
|
+
Returns:
|
171
|
+
Union[list[tuple[str,dict]], list[tuple[str, float,dict]]]:
|
172
|
+
Depending on the `return_score_type` parameter, returns either a list of strings representing the top-k similar contents,
|
173
|
+
or a list of tuples where each tuple contains a string and a floating-point score.
|
174
|
+
"""
|
175
|
+
_filter = {
|
176
|
+
"_id": agent_id,
|
177
|
+
}
|
178
|
+
if filter is not None:
|
179
|
+
_filter.update(filter)
|
180
|
+
if return_score_type == "L2-distance":
|
181
|
+
_result = await self.vectors_store.asimilarity_search_with_score_by_vector(
|
182
|
+
embedding=embedding,
|
183
|
+
k=k,
|
184
|
+
filter=_filter,
|
185
|
+
fetch_k=fetch_k,
|
186
|
+
)
|
187
|
+
return [(r.page_content, s, r.metadata) for r, s in _result]
|
188
|
+
elif return_score_type == "none":
|
189
|
+
_result = await self.vectors_store.asimilarity_search_by_vector(
|
190
|
+
embedding=embedding,
|
191
|
+
k=k,
|
192
|
+
filter=_filter,
|
193
|
+
fetch_k=fetch_k,
|
194
|
+
)
|
195
|
+
return [(r.page_content, r.metadata) for r in _result]
|
196
|
+
else:
|
197
|
+
raise ValueError(f"Invalid `return_score_type` {return_score_type}!")
|
198
|
+
|
199
|
+
@lock_decorator
|
200
|
+
async def marginal_relevance_search(
|
201
|
+
self,
|
202
|
+
query: str,
|
203
|
+
agent_id: int,
|
204
|
+
k: int = 4,
|
205
|
+
fetch_k: int = 20,
|
206
|
+
lambda_mult: float = 0.5,
|
207
|
+
return_score_type: Literal["none"] = "none",
|
208
|
+
filter: Optional[dict] = None,
|
209
|
+
) -> list[tuple[str, dict]]:
|
210
|
+
"""
|
211
|
+
Return contents selected using the maximal marginal relevance asynchronously.
|
212
|
+
|
213
|
+
Args:
|
214
|
+
query (str): The text to look up documents similar to.
|
215
|
+
agent_id (int): The identifier of the agent to filter specific documents. Only documents associated with this agent will be considered.
|
216
|
+
k (int, optional): The number of top similar contents to return. Defaults to 4.
|
217
|
+
fetch_k (int, optional): The number of documents to fetch before applying any filters. Defaults to 20.
|
218
|
+
lambda_mult (float): Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5.
|
219
|
+
return_score_type (Literal["none"].,optional):
|
220
|
+
Specifies whether and how to return similarity scores with the results:
|
221
|
+
- "none": Do not return scores; only return the contents (default).
|
222
|
+
filter (dict, optional): The filter dict for metadata.
|
223
|
+
|
224
|
+
Returns:
|
225
|
+
list[tuple[str,dict]]: the result contents.
|
226
|
+
"""
|
227
|
+
_filter = {
|
228
|
+
"_id": agent_id,
|
229
|
+
}
|
230
|
+
if filter is not None:
|
231
|
+
_filter.update(filter)
|
232
|
+
|
233
|
+
if return_score_type == "none":
|
234
|
+
_result = await self.vectors_store.amax_marginal_relevance_search(
|
235
|
+
query=query,
|
236
|
+
k=k,
|
237
|
+
filter=_filter,
|
238
|
+
fetch_k=fetch_k,
|
239
|
+
lambda_mult=lambda_mult,
|
240
|
+
)
|
241
|
+
return [(r.page_content, r.metadata) for r in _result]
|
242
|
+
else:
|
243
|
+
raise ValueError(f"Invalid `return_score_type` {return_score_type}!")
|
244
|
+
|
245
|
+
@lock_decorator
|
246
|
+
async def marginal_relevance_search_by_embedding(
|
247
|
+
self,
|
248
|
+
embedding: list[float],
|
249
|
+
agent_id: int,
|
250
|
+
k: int = 4,
|
251
|
+
fetch_k: int = 20,
|
252
|
+
lambda_mult: float = 0.5,
|
253
|
+
return_score_type: Union[Literal["none"], Literal["similarity_score"]] = "none",
|
254
|
+
filter: Optional[dict] = None,
|
255
|
+
) -> Union[list[tuple[str, dict]], list[tuple[str, float, dict]]]:
|
256
|
+
"""
|
257
|
+
Return contents selected using the maximal marginal relevance asynchronously.
|
258
|
+
|
259
|
+
Args:
|
260
|
+
embedding (list[float]): The vector to look up documents similar to.
|
261
|
+
agent_id (int): The identifier of the agent to filter specific documents. Only documents associated with this agent will be considered.
|
262
|
+
k (int, optional): The number of top similar contents to return. Defaults to 4.
|
263
|
+
fetch_k (int, optional): The number of documents to fetch before applying any filters. Defaults to 20.
|
264
|
+
lambda_mult (float): Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5.
|
265
|
+
return_score_type (Union[Literal["none"], Literal["similarity_score"]], optional):
|
266
|
+
Specifies whether and how to return similarity scores with the results:
|
267
|
+
- "none": Do not return scores; only return the contents (default).
|
268
|
+
- "similarity_score": Return a tuple of content and its similarity score.
|
269
|
+
filter (dict, optional): The filter dict for metadata.
|
270
|
+
|
271
|
+
Returns:
|
272
|
+
Union[list[tuple[str,dict]], list[tuple[str, float,dict]]]:
|
273
|
+
Depending on the `return_score_type` parameter, returns either a list of strings representing the top-k similar contents,
|
274
|
+
or a list of tuples where each tuple contains a string and a floating-point score.
|
275
|
+
"""
|
276
|
+
|
277
|
+
_filter = {
|
278
|
+
"_id": agent_id,
|
279
|
+
}
|
280
|
+
if filter is not None:
|
281
|
+
_filter.update(filter)
|
282
|
+
if return_score_type == "none":
|
283
|
+
_result = await self.vectors_store.amax_marginal_relevance_search_by_vector(
|
284
|
+
embedding=embedding,
|
285
|
+
k=k,
|
286
|
+
filter=_filter,
|
287
|
+
fetch_k=fetch_k,
|
288
|
+
lambda_mult=lambda_mult,
|
289
|
+
)
|
290
|
+
return [(r.page_content, r.metadata) for r in _result]
|
291
|
+
elif return_score_type == "similarity_score":
|
292
|
+
_result = await self.vectors_store.amax_marginal_relevance_search_with_score_by_vector(
|
293
|
+
embedding=embedding,
|
294
|
+
k=k,
|
295
|
+
filter=_filter,
|
296
|
+
fetch_k=fetch_k,
|
297
|
+
lambda_mult=lambda_mult,
|
298
|
+
)
|
299
|
+
return [(r.page_content, s, r.metadata) for r, s in _result]
|
300
|
+
|
301
|
+
else:
|
302
|
+
raise ValueError(f"Invalid `return_score_type` {return_score_type}!")
|