rusticai-api 0.0.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.
- rustic_ai/api_server/__init__.py +0 -0
- rustic_ai/api_server/api_dependency_manager.py +103 -0
- rustic_ai/api_server/catalog/__init__.py +4 -0
- rustic_ai/api_server/catalog/catalog_store.py +607 -0
- rustic_ai/api_server/catalog/models.py +338 -0
- rustic_ai/api_server/catalog/router.py +423 -0
- rustic_ai/api_server/guilds/__init__.py +4 -0
- rustic_ai/api_server/guilds/comms_manager.py +256 -0
- rustic_ai/api_server/guilds/router.py +426 -0
- rustic_ai/api_server/guilds/schema.py +5 -0
- rustic_ai/api_server/guilds/service.py +30 -0
- rustic_ai/api_server/guilds/socket.py +52 -0
- rustic_ai/api_server/guilds/system_comms_manager.py +238 -0
- rustic_ai/api_server/logging/__init__.py +4 -0
- rustic_ai/api_server/logging/config.py +35 -0
- rustic_ai/api_server/logging/format.py +24 -0
- rustic_ai/api_server/main.py +95 -0
- rustic_ai/api_server/main_debug.py +17 -0
- rusticai_api-0.0.1.dist-info/METADATA +87 -0
- rusticai_api-0.0.1.dist-info/RECORD +21 -0
- rusticai_api-0.0.1.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,423 @@
|
|
|
1
|
+
# Routes to work with the Catalog models
|
|
2
|
+
|
|
3
|
+
from typing import Annotated, Dict, List
|
|
4
|
+
|
|
5
|
+
from fastapi import APIRouter, Body, Depends, HTTPException, Response
|
|
6
|
+
from fastapi.params import Query
|
|
7
|
+
from pydantic import BaseModel, ValidationError
|
|
8
|
+
from sqlalchemy import Engine
|
|
9
|
+
from starlette import status
|
|
10
|
+
|
|
11
|
+
from rustic_ai.api_server.guilds.schema import IdInfo
|
|
12
|
+
from rustic_ai.core.guild.dsl import GuildSpec
|
|
13
|
+
from rustic_ai.core.guild.metaprog.agent_registry import AgentEntry
|
|
14
|
+
from rustic_ai.core.guild.metastore.database import Metastore
|
|
15
|
+
|
|
16
|
+
from .catalog_store import CatalogStore
|
|
17
|
+
from .models import (
|
|
18
|
+
AgentNameWithIcon,
|
|
19
|
+
BasicGuildInfo,
|
|
20
|
+
BlueprintAgentsIconReqRes,
|
|
21
|
+
BlueprintCategoryCreate,
|
|
22
|
+
BlueprintCategoryResponse,
|
|
23
|
+
BlueprintCreate,
|
|
24
|
+
BlueprintDetailsResponse,
|
|
25
|
+
BlueprintInfoResponse,
|
|
26
|
+
BlueprintResponseWithAccessReason,
|
|
27
|
+
BlueprintReviewCreate,
|
|
28
|
+
BlueprintReviewResponse,
|
|
29
|
+
BlueprintReviewsResponse,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
catalog_router = APIRouter()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@catalog_router.post(
|
|
36
|
+
"/blueprints/",
|
|
37
|
+
response_model=IdInfo,
|
|
38
|
+
status_code=status.HTTP_201_CREATED,
|
|
39
|
+
operation_id="createBlueprint",
|
|
40
|
+
tags=["blueprints"],
|
|
41
|
+
)
|
|
42
|
+
async def create_blueprint(blueprint: BlueprintCreate, engine: Engine = Depends(Metastore.get_engine)):
|
|
43
|
+
try:
|
|
44
|
+
GuildSpec.model_validate(blueprint.spec)
|
|
45
|
+
|
|
46
|
+
for agent in blueprint.spec.agents:
|
|
47
|
+
class_name = agent.class_name
|
|
48
|
+
try:
|
|
49
|
+
CatalogStore(engine).get_agent_by_class_name(class_name)
|
|
50
|
+
except Exception:
|
|
51
|
+
raise HTTPException(status_code=400, detail=f"Agent not found for class_name: {class_name}")
|
|
52
|
+
except ValidationError as e:
|
|
53
|
+
raise HTTPException(status_code=400, detail=e.errors())
|
|
54
|
+
blueprint_id = CatalogStore(engine).create_blueprint(blueprint)
|
|
55
|
+
return IdInfo(id=blueprint_id)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@catalog_router.get(
|
|
59
|
+
"/blueprints/{blueprint_id}",
|
|
60
|
+
response_model=BlueprintDetailsResponse,
|
|
61
|
+
operation_id="getBlueprintById",
|
|
62
|
+
tags=["blueprints"],
|
|
63
|
+
)
|
|
64
|
+
async def get_blueprint(blueprint_id: str, engine: Engine = Depends(Metastore.get_engine)):
|
|
65
|
+
blueprint = CatalogStore(engine).get_blueprint(blueprint_id)
|
|
66
|
+
if not blueprint:
|
|
67
|
+
raise HTTPException(status_code=404, detail="Blueprint not found")
|
|
68
|
+
return blueprint
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@catalog_router.get(
|
|
72
|
+
"/organizations/{organization_id}/blueprints/owned/",
|
|
73
|
+
response_model=List[BlueprintInfoResponse],
|
|
74
|
+
operation_id="getOrganizationBlueprints",
|
|
75
|
+
tags=["blueprints", "organizations"],
|
|
76
|
+
)
|
|
77
|
+
async def get_organization_blueprints(organization_id: str, engine: Engine = Depends(Metastore.get_engine)):
|
|
78
|
+
return CatalogStore(engine).get_blueprints_by_organization(organization_id)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@catalog_router.get(
|
|
82
|
+
"/users/{user_id}/blueprints/owned/",
|
|
83
|
+
response_model=List[BlueprintInfoResponse],
|
|
84
|
+
operation_id="getUserBlueprints",
|
|
85
|
+
tags=["blueprints", "users"],
|
|
86
|
+
)
|
|
87
|
+
async def get_user_blueprints(user_id: str, engine: Engine = Depends(Metastore.get_engine)):
|
|
88
|
+
return CatalogStore(engine).get_blueprints_by_author(user_id)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@catalog_router.get(
|
|
92
|
+
"/users/{user_id}/blueprints/accessible/",
|
|
93
|
+
response_model=List[BlueprintResponseWithAccessReason],
|
|
94
|
+
operation_id="getAccessibleBlueprintsByUserId",
|
|
95
|
+
tags=["blueprints", "users"],
|
|
96
|
+
)
|
|
97
|
+
async def get_user_accessible_blueprints(user_id: str, engine: Engine = Depends(Metastore.get_engine)):
|
|
98
|
+
return CatalogStore(engine).get_user_accessible_blueprints(user_id)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class ShareWithOrgRequest(BaseModel):
|
|
102
|
+
organization_id: str
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@catalog_router.post(
|
|
106
|
+
"/blueprints/{blueprint_id}/share/",
|
|
107
|
+
status_code=status.HTTP_204_NO_CONTENT,
|
|
108
|
+
operation_id="shareBlueprintWithOrganization",
|
|
109
|
+
tags=["blueprints", "organizations"],
|
|
110
|
+
)
|
|
111
|
+
async def share_blueprint_with_organization(
|
|
112
|
+
blueprint_id: str, sbr: ShareWithOrgRequest, engine: Engine = Depends(Metastore.get_engine)
|
|
113
|
+
):
|
|
114
|
+
share_status = CatalogStore(engine).share_blueprint(blueprint_id, sbr.organization_id)
|
|
115
|
+
if share_status:
|
|
116
|
+
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@catalog_router.delete(
|
|
120
|
+
"/blueprints/{blueprint_id}/share/{organization_id}",
|
|
121
|
+
status_code=status.HTTP_204_NO_CONTENT,
|
|
122
|
+
operation_id="unshareBlueprintWithOrganization",
|
|
123
|
+
tags=["blueprints", "organizations"],
|
|
124
|
+
)
|
|
125
|
+
async def unshare_blueprint_with_organization(
|
|
126
|
+
blueprint_id: str, organization_id: str, engine: Engine = Depends(Metastore.get_engine)
|
|
127
|
+
):
|
|
128
|
+
unshare_status = CatalogStore(engine).unshare_blueprint(blueprint_id, organization_id)
|
|
129
|
+
if unshare_status:
|
|
130
|
+
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@catalog_router.get(
|
|
134
|
+
"/organizations/{organization_id}/blueprints/shared/",
|
|
135
|
+
response_model=List[BlueprintInfoResponse],
|
|
136
|
+
operation_id="getSharedBlueprintsByOrganizationId",
|
|
137
|
+
tags=["blueprints", "organizations"],
|
|
138
|
+
)
|
|
139
|
+
async def get_organization_shared_blueprints(organization_id: str, engine: Engine = Depends(Metastore.get_engine)):
|
|
140
|
+
return CatalogStore(engine).get_blueprints_shared_with_organization(organization_id)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@catalog_router.get(
|
|
144
|
+
"/blueprints/{blueprint_id}/organizations/shared/",
|
|
145
|
+
response_model=List[str],
|
|
146
|
+
operation_id="getSharedOrganizationsByBlueprintId",
|
|
147
|
+
tags=["blueprints", "organizations"],
|
|
148
|
+
)
|
|
149
|
+
async def get_blueprint_shared_organizations(blueprint_id: str, engine: Engine = Depends(Metastore.get_engine)):
|
|
150
|
+
return CatalogStore(engine).get_organization_with_shared_blueprint(blueprint_id)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
@catalog_router.get(
|
|
154
|
+
"/categories/{category_id}", response_model=BlueprintCategoryResponse, operation_id="getCategoryById"
|
|
155
|
+
)
|
|
156
|
+
async def get_category(category_id: str, engine: Engine = Depends(Metastore.get_engine)):
|
|
157
|
+
category = CatalogStore(engine).get_category(category_id)
|
|
158
|
+
if not category:
|
|
159
|
+
raise HTTPException(status_code=404, detail="Category not found")
|
|
160
|
+
return category
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@catalog_router.post(
|
|
164
|
+
"/categories/",
|
|
165
|
+
response_model=IdInfo,
|
|
166
|
+
status_code=status.HTTP_201_CREATED,
|
|
167
|
+
operation_id="createCategory",
|
|
168
|
+
)
|
|
169
|
+
async def create_category(category: BlueprintCategoryCreate, engine: Engine = Depends(Metastore.get_engine)):
|
|
170
|
+
category_id = CatalogStore(engine).create_category(category)
|
|
171
|
+
return IdInfo(id=category_id)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
@catalog_router.get(
|
|
175
|
+
"/categories/",
|
|
176
|
+
response_model=List[BlueprintCategoryResponse],
|
|
177
|
+
status_code=status.HTTP_200_OK,
|
|
178
|
+
operation_id="listCategories",
|
|
179
|
+
)
|
|
180
|
+
async def list_categories(engine: Engine = Depends(Metastore.get_engine)):
|
|
181
|
+
return CatalogStore(engine).get_categories()
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
@catalog_router.get(
|
|
185
|
+
"/categories/{category_name}/blueprints/",
|
|
186
|
+
response_model=List[BlueprintCategoryResponse],
|
|
187
|
+
operation_id="getBlueprintsByCategoryName",
|
|
188
|
+
tags=["blueprints"],
|
|
189
|
+
)
|
|
190
|
+
async def get_category_blueprints(category_name: str, engine: Engine = Depends(Metastore.get_engine)):
|
|
191
|
+
return CatalogStore(engine).get_blueprints_by_category(category_name)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@catalog_router.post(
|
|
195
|
+
"/blueprints/{blueprint_id}/reviews/",
|
|
196
|
+
response_model=IdInfo,
|
|
197
|
+
status_code=status.HTTP_201_CREATED,
|
|
198
|
+
operation_id="createBlueprintReview",
|
|
199
|
+
tags=["blueprints"],
|
|
200
|
+
)
|
|
201
|
+
async def create_review(
|
|
202
|
+
blueprint_id: str, review: BlueprintReviewCreate, engine: Engine = Depends(Metastore.get_engine)
|
|
203
|
+
):
|
|
204
|
+
review_id = CatalogStore(engine).create_blueprint_review(blueprint_id, review)
|
|
205
|
+
return IdInfo(id=review_id)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
@catalog_router.get(
|
|
209
|
+
"/blueprints/{blueprint_id}/reviews/",
|
|
210
|
+
response_model=BlueprintReviewsResponse,
|
|
211
|
+
operation_id="getReviewsByBlueprintId",
|
|
212
|
+
tags=["blueprints"],
|
|
213
|
+
)
|
|
214
|
+
async def get_blueprint_reviews(blueprint_id: str, engine: Engine = Depends(Metastore.get_engine)):
|
|
215
|
+
return CatalogStore(engine).get_blueprint_reviews(blueprint_id)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
@catalog_router.get(
|
|
219
|
+
"/blueprints/{blueprint_id}/reviews/{review_id}",
|
|
220
|
+
response_model=BlueprintReviewResponse,
|
|
221
|
+
operation_id="getBlueprintReview",
|
|
222
|
+
)
|
|
223
|
+
async def get_blueprint_review(blueprint_id: str, review_id: str, engine: Engine = Depends(Metastore.get_engine)):
|
|
224
|
+
return CatalogStore(engine).get_blueprint_review(review_id)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
@catalog_router.get("/tags/", response_model=List[str], operation_id="listTags", tags=["blueprints"])
|
|
228
|
+
async def list_tags(engine: Engine = Depends(Metastore.get_engine)):
|
|
229
|
+
return CatalogStore(engine).get_tags()
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
@catalog_router.post(
|
|
233
|
+
"/blueprints/{blueprint_id}/guilds/{guild_id}",
|
|
234
|
+
status_code=status.HTTP_204_NO_CONTENT,
|
|
235
|
+
operation_id="addGuildToBlueprint",
|
|
236
|
+
tags=["blueprints"],
|
|
237
|
+
)
|
|
238
|
+
async def add_guild_to_blueprint(blueprint_id: str, guild_id: str, engine: Engine = Depends(Metastore.get_engine)):
|
|
239
|
+
CatalogStore(engine).add_guild_to_blueprint(blueprint_id, guild_id)
|
|
240
|
+
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
@catalog_router.get(
|
|
244
|
+
"/guilds/{guild_id}/blueprints/",
|
|
245
|
+
response_model=BlueprintDetailsResponse,
|
|
246
|
+
operation_id="getBlueprintForGuild",
|
|
247
|
+
tags=["blueprints"],
|
|
248
|
+
)
|
|
249
|
+
async def get_blueprint_for_guild(guild_id: str, engine: Engine = Depends(Metastore.get_engine)):
|
|
250
|
+
return CatalogStore(engine).get_blueprint_for_guild(guild_id)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
@catalog_router.post(
|
|
254
|
+
"/guilds/{guild_id}/users/{user_id}",
|
|
255
|
+
status_code=status.HTTP_204_NO_CONTENT,
|
|
256
|
+
operation_id="addUserToGuild",
|
|
257
|
+
tags=["users"],
|
|
258
|
+
)
|
|
259
|
+
async def add_user_to_guild(guild_id: str, user_id: str, engine: Engine = Depends(Metastore.get_engine)):
|
|
260
|
+
CatalogStore(engine).add_user_to_guild(guild_id, user_id)
|
|
261
|
+
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
@catalog_router.get(
|
|
265
|
+
"/users/{user_id}/guilds/",
|
|
266
|
+
response_model=List[BasicGuildInfo],
|
|
267
|
+
operation_id="getGuildsForUser",
|
|
268
|
+
tags=["users"],
|
|
269
|
+
)
|
|
270
|
+
async def get_guilds_for_user(user_id: str, engine: Engine = Depends(Metastore.get_engine)):
|
|
271
|
+
return CatalogStore(engine).get_guilds_for_user(user_id)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
@catalog_router.delete(
|
|
275
|
+
"/guilds/{guild_id}/users/{user_id}",
|
|
276
|
+
status_code=status.HTTP_204_NO_CONTENT,
|
|
277
|
+
operation_id="removeUserFromGuild",
|
|
278
|
+
tags=["users"],
|
|
279
|
+
)
|
|
280
|
+
async def remove_user_from_guild(guild_id: str, user_id: str, engine: Engine = Depends(Metastore.get_engine)):
|
|
281
|
+
CatalogStore(engine).remove_user_from_guild(guild_id, user_id)
|
|
282
|
+
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
@catalog_router.post(
|
|
286
|
+
"/guilds/{guild_id}/organizations/{organization_id}",
|
|
287
|
+
status_code=status.HTTP_204_NO_CONTENT,
|
|
288
|
+
operation_id="addOrgToGuild",
|
|
289
|
+
tags=["organizations"],
|
|
290
|
+
)
|
|
291
|
+
async def add_org_to_guild(guild_id: str, organization_id: str, engine: Engine = Depends(Metastore.get_engine)):
|
|
292
|
+
CatalogStore(engine).add_org_to_guild(guild_id, organization_id)
|
|
293
|
+
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
@catalog_router.get(
|
|
297
|
+
"/organizations/{organization_id}/guilds/",
|
|
298
|
+
response_model=List[BasicGuildInfo],
|
|
299
|
+
operation_id="getGuildsForOrganization",
|
|
300
|
+
tags=["organizations"],
|
|
301
|
+
)
|
|
302
|
+
async def get_guilds_for_organization(organization_id: str, engine: Engine = Depends(Metastore.get_engine)):
|
|
303
|
+
return CatalogStore(engine).get_guilds_for_org(organization_id)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
@catalog_router.delete(
|
|
307
|
+
"/guilds/{guild_id}/organizations/{organization_id}",
|
|
308
|
+
status_code=status.HTTP_204_NO_CONTENT,
|
|
309
|
+
operation_id="removeOrgFromGuild",
|
|
310
|
+
tags=["organizations"],
|
|
311
|
+
)
|
|
312
|
+
async def remove_org_from_guild(guild_id: str, organization_id: str, engine: Engine = Depends(Metastore.get_engine)):
|
|
313
|
+
CatalogStore(engine).remove_org_from_guild(guild_id, organization_id)
|
|
314
|
+
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
@catalog_router.post(
|
|
318
|
+
"/blueprints/{blueprint_id}/icons/",
|
|
319
|
+
status_code=status.HTTP_204_NO_CONTENT,
|
|
320
|
+
operation_id="addBlueprintAgentIcons",
|
|
321
|
+
tags=["blueprints"],
|
|
322
|
+
)
|
|
323
|
+
async def add_bp_agent_icons(
|
|
324
|
+
blueprint_id: str, req_data: BlueprintAgentsIconReqRes, engine: Engine = Depends(Metastore.get_engine)
|
|
325
|
+
):
|
|
326
|
+
if len(req_data.agent_icons) == 0:
|
|
327
|
+
raise HTTPException(status_code=400, detail="No agent icons provided")
|
|
328
|
+
CatalogStore(engine).add_agent_icons_to_blueprint(blueprint_id, req_data.agent_icons)
|
|
329
|
+
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
@catalog_router.get(
|
|
333
|
+
"/blueprints/{blueprint_id}/icons/",
|
|
334
|
+
response_model=BlueprintAgentsIconReqRes,
|
|
335
|
+
operation_id="getBlueprintAgentIcons",
|
|
336
|
+
tags=["blueprints"],
|
|
337
|
+
)
|
|
338
|
+
async def get_bp_agent_icons(blueprint_id: str, engine: Engine = Depends(Metastore.get_engine)):
|
|
339
|
+
result = CatalogStore(engine).get_blueprint_agent_icons(blueprint_id)
|
|
340
|
+
return BlueprintAgentsIconReqRes(agent_icons=result)
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
@catalog_router.post(
|
|
344
|
+
"/blueprints/{blueprint_id}/icons/{agent_name}",
|
|
345
|
+
status_code=status.HTTP_204_NO_CONTENT,
|
|
346
|
+
operation_id="addBlueprintAgentIconByName",
|
|
347
|
+
tags=["blueprints"],
|
|
348
|
+
)
|
|
349
|
+
async def add_bp_agent_icon_by_name(
|
|
350
|
+
blueprint_id: str,
|
|
351
|
+
agent_name: str,
|
|
352
|
+
agent_icon: Annotated[str, Body(embed=True)],
|
|
353
|
+
engine: Engine = Depends(Metastore.get_engine),
|
|
354
|
+
):
|
|
355
|
+
if not agent_icon:
|
|
356
|
+
raise HTTPException(status_code=400, detail="No agent icon provided")
|
|
357
|
+
data = [AgentNameWithIcon(agent_name=agent_name, icon=agent_icon)]
|
|
358
|
+
CatalogStore(engine).add_agent_icons_to_blueprint(blueprint_id, data)
|
|
359
|
+
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
@catalog_router.get(
|
|
363
|
+
"/blueprints/{blueprint_id}/icons/{agent_name}",
|
|
364
|
+
response_model=AgentNameWithIcon,
|
|
365
|
+
operation_id="getBlueprintAgentIconByName",
|
|
366
|
+
tags=["blueprints"],
|
|
367
|
+
)
|
|
368
|
+
async def get_bp_agent_icons_by_name(
|
|
369
|
+
blueprint_id: str, agent_name: str, engine: Engine = Depends(Metastore.get_engine)
|
|
370
|
+
):
|
|
371
|
+
return CatalogStore(engine).get_blueprint_agent_icon_by_name(blueprint_id, agent_name)
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
@catalog_router.post("/agents", status_code=status.HTTP_201_CREATED, operation_id="registerAgent", tags=["agents"])
|
|
375
|
+
def register_agent(
|
|
376
|
+
agent_spec: AgentEntry,
|
|
377
|
+
engine: Engine = Depends(Metastore.get_engine),
|
|
378
|
+
):
|
|
379
|
+
try:
|
|
380
|
+
agent = AgentEntry.model_validate(agent_spec)
|
|
381
|
+
CatalogStore(engine).register_agent(agent)
|
|
382
|
+
|
|
383
|
+
return Response(status_code=status.HTTP_201_CREATED)
|
|
384
|
+
|
|
385
|
+
except ValidationError as e:
|
|
386
|
+
raise HTTPException(status_code=400, detail=e.errors())
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
@catalog_router.get(
|
|
390
|
+
"/agents",
|
|
391
|
+
response_model=Dict[str, AgentEntry],
|
|
392
|
+
operation_id="getAgents",
|
|
393
|
+
tags=["agents"],
|
|
394
|
+
)
|
|
395
|
+
def get_agents(
|
|
396
|
+
class_names: Annotated[list[str] | None, Query()] = None, engine: Engine = Depends(Metastore.get_engine)
|
|
397
|
+
):
|
|
398
|
+
hidden_agents = [
|
|
399
|
+
"rustic_ai.agents.system.guild_manager_agent.GuildManagerAgent",
|
|
400
|
+
"rustic_ai.agents.utils.probe_agent.ProbeAgent",
|
|
401
|
+
"rustic_ai.agents.utils.probe_agent.EssentialProbeAgent",
|
|
402
|
+
]
|
|
403
|
+
return CatalogStore(engine).get_agents(class_names, hidden_agents)
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
@catalog_router.get(
|
|
407
|
+
"/agents/{class_name}",
|
|
408
|
+
response_model=AgentEntry,
|
|
409
|
+
operation_id="getAgentByClassName",
|
|
410
|
+
tags=["agents"],
|
|
411
|
+
)
|
|
412
|
+
def get_agent(class_name: str, engine: Engine = Depends(Metastore.get_engine)):
|
|
413
|
+
return CatalogStore(engine).get_agent_by_class_name(class_name)
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
@catalog_router.get(
|
|
417
|
+
"/agents/message_schema/",
|
|
418
|
+
response_model=dict,
|
|
419
|
+
operation_id="getMessageSchemaByFormat",
|
|
420
|
+
tags=["agents"],
|
|
421
|
+
)
|
|
422
|
+
def get_message_schema(message_format: str, engine: Engine = Depends(Metastore.get_engine)):
|
|
423
|
+
return CatalogStore(engine).get_agent_by_message_format(message_format)
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import logging
|
|
3
|
+
import random
|
|
4
|
+
import time
|
|
5
|
+
from typing import Callable, Dict, List, Optional, Tuple
|
|
6
|
+
|
|
7
|
+
import shortuuid
|
|
8
|
+
from fastapi import WebSocket, WebSocketDisconnect
|
|
9
|
+
from opentelemetry import trace
|
|
10
|
+
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
|
11
|
+
from sqlalchemy import Engine
|
|
12
|
+
|
|
13
|
+
from rustic_ai.core.agents.system.guild_manager_agent import UserAgentCreationRequest
|
|
14
|
+
from rustic_ai.core.agents.utils.user_proxy_agent import UserProxyAgent
|
|
15
|
+
from rustic_ai.core.guild.agent_ext.mixins.telemetry import TelemetryConstants
|
|
16
|
+
from rustic_ai.core.guild.builders import GuildHelper
|
|
17
|
+
from rustic_ai.core.guild.dsl import GuildSpec, GuildTopics
|
|
18
|
+
from rustic_ai.core.guild.metastore.guild_store import GuildStore
|
|
19
|
+
from rustic_ai.core.messaging.client.message_tracking_client import (
|
|
20
|
+
MessageTrackingClient,
|
|
21
|
+
)
|
|
22
|
+
from rustic_ai.core.messaging.core.client import Client
|
|
23
|
+
from rustic_ai.core.messaging.core.message import AgentTag, Message
|
|
24
|
+
from rustic_ai.core.messaging.core.messaging_interface import MessagingInterface
|
|
25
|
+
from rustic_ai.core.utils.basic_class_utils import get_qualified_class_name
|
|
26
|
+
from rustic_ai.core.utils.gemstone_id import GemstoneGenerator
|
|
27
|
+
from rustic_ai.core.utils.priority import Priority
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class GuildCommunicationManager:
|
|
31
|
+
_gemstone: GemstoneGenerator = GemstoneGenerator(random.randint(10, 100))
|
|
32
|
+
_instance: Optional["GuildCommunicationManager"] = None
|
|
33
|
+
|
|
34
|
+
def __new__(cls):
|
|
35
|
+
if cls._instance is None:
|
|
36
|
+
cls._instance = super().__new__(cls)
|
|
37
|
+
return cls._instance
|
|
38
|
+
|
|
39
|
+
def __init__(self):
|
|
40
|
+
if not hasattr(self, "initialized"):
|
|
41
|
+
self.websockets: Dict[Tuple[str, str], List[WebSocket]] = {}
|
|
42
|
+
self.initialized = True
|
|
43
|
+
self.tracer = trace.get_tracer(TelemetryConstants.TRACER_NAME)
|
|
44
|
+
self.guild_specs: Dict[str, GuildSpec] = {}
|
|
45
|
+
self.messaging_interfaces: Dict[str, MessagingInterface] = {}
|
|
46
|
+
|
|
47
|
+
async def shutdown(self):
|
|
48
|
+
for _, messaging in self.messaging_interfaces.items():
|
|
49
|
+
messaging.shutdown()
|
|
50
|
+
|
|
51
|
+
async def get_or_fetch_guild_spec(self, guild_id: str, engine: Engine) -> Optional[GuildSpec]:
|
|
52
|
+
if guild_id not in self.guild_specs:
|
|
53
|
+
guild_store = GuildStore(engine)
|
|
54
|
+
guild_model = guild_store.get_guild(guild_id)
|
|
55
|
+
|
|
56
|
+
if guild_model:
|
|
57
|
+
self.guild_specs[guild_id] = guild_model.to_guild_spec()
|
|
58
|
+
else: # pragma: no cover
|
|
59
|
+
logging.debug(f"Guild with ID {guild_id} not found")
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
return self.guild_specs[guild_id]
|
|
63
|
+
|
|
64
|
+
async def get_or_create_messaging_interface(self, guild_spec: GuildSpec) -> MessagingInterface:
|
|
65
|
+
guild_id = guild_spec.id
|
|
66
|
+
if guild_id not in self.messaging_interfaces:
|
|
67
|
+
guild_spec = guild_spec
|
|
68
|
+
messaging_config = GuildHelper.get_messaging_config(guild_spec)
|
|
69
|
+
self.messaging_interfaces[guild_id] = MessagingInterface(guild_id, messaging_config)
|
|
70
|
+
return self.messaging_interfaces[guild_id]
|
|
71
|
+
|
|
72
|
+
async def create_guild_client(
|
|
73
|
+
self,
|
|
74
|
+
guild_id: str,
|
|
75
|
+
user_id: str,
|
|
76
|
+
messaging: MessagingInterface,
|
|
77
|
+
websocket: WebSocket,
|
|
78
|
+
loop: asyncio.AbstractEventLoop,
|
|
79
|
+
) -> Client:
|
|
80
|
+
uuid = shortuuid.uuid()
|
|
81
|
+
client = MessageTrackingClient(
|
|
82
|
+
uuid, f"{guild_id}_{uuid}", self.build_message_handler(guild_id, user_id, websocket, loop)
|
|
83
|
+
)
|
|
84
|
+
messaging.register_client(client)
|
|
85
|
+
return client
|
|
86
|
+
|
|
87
|
+
def build_message_handler(
|
|
88
|
+
self,
|
|
89
|
+
guild_id: str,
|
|
90
|
+
user_id: str,
|
|
91
|
+
websocket: WebSocket,
|
|
92
|
+
loop: asyncio.AbstractEventLoop,
|
|
93
|
+
) -> Callable[[Message], None]:
|
|
94
|
+
def on_message(message: Message) -> None:
|
|
95
|
+
logging.debug(f"Received message: {message}")
|
|
96
|
+
|
|
97
|
+
try:
|
|
98
|
+
coroutine = self.send_message(guild_id, user_id, message, websocket)
|
|
99
|
+
asyncio.run_coroutine_threadsafe(coroutine, loop)
|
|
100
|
+
except ValueError as e: # pragma: no cover
|
|
101
|
+
logging.error(f"Invalid message received: {e}")
|
|
102
|
+
except RuntimeError as e: # pragma: no cover
|
|
103
|
+
logging.error(f"Error sending message: {e}")
|
|
104
|
+
except Exception as e: # pragma: no cover
|
|
105
|
+
logging.error(f"Error sending message: {e}")
|
|
106
|
+
|
|
107
|
+
return on_message
|
|
108
|
+
|
|
109
|
+
async def send_message(self, guild_id: str, user_id: str, message: Message, websocket: WebSocket):
|
|
110
|
+
logging.debug(f"Sending message to User[{user_id}] on WS[{websocket}]: \n{message.model_dump_json()}")
|
|
111
|
+
span_context = None
|
|
112
|
+
if message.traceparent:
|
|
113
|
+
carrier = {"traceparent": message.traceparent}
|
|
114
|
+
span_context = TraceContextTextMapPropagator().extract(carrier)
|
|
115
|
+
with self.tracer.start_as_current_span(
|
|
116
|
+
"websocket:send_message",
|
|
117
|
+
attributes={
|
|
118
|
+
"user_id": user_id,
|
|
119
|
+
"guild_id": guild_id,
|
|
120
|
+
"message_id": f"id:{message.id}",
|
|
121
|
+
"message_format": message.format,
|
|
122
|
+
"message_topic": message.topic_published_to or "UNKNOWN",
|
|
123
|
+
"agent_id": message.sender.id or "UNKNOWN",
|
|
124
|
+
"agent_name": message.sender.name or "UNKNOWN",
|
|
125
|
+
"root_thread_id": f"id:{message.root_thread_id}",
|
|
126
|
+
},
|
|
127
|
+
context=span_context,
|
|
128
|
+
):
|
|
129
|
+
try:
|
|
130
|
+
await websocket.send_json(message.model_dump())
|
|
131
|
+
except Exception as e: # pragma: no cover
|
|
132
|
+
logging.error(f"Error sending message: {e}")
|
|
133
|
+
|
|
134
|
+
async def handle_websocket_connection(
|
|
135
|
+
self,
|
|
136
|
+
websocket: WebSocket,
|
|
137
|
+
guild_id: str,
|
|
138
|
+
user_id: str,
|
|
139
|
+
user_name: str,
|
|
140
|
+
engine: Engine,
|
|
141
|
+
):
|
|
142
|
+
guild_spec = await self.get_or_fetch_guild_spec(guild_id, engine)
|
|
143
|
+
|
|
144
|
+
if not guild_spec: # pragma: no cover
|
|
145
|
+
logging.error(f"Guild with ID {guild_id} not found")
|
|
146
|
+
await websocket.close()
|
|
147
|
+
return
|
|
148
|
+
else:
|
|
149
|
+
await websocket.accept()
|
|
150
|
+
|
|
151
|
+
loop = asyncio.get_running_loop()
|
|
152
|
+
|
|
153
|
+
messaging: MessagingInterface = await self.get_or_create_messaging_interface(guild_spec)
|
|
154
|
+
guild_client: Client = await self.create_guild_client(guild_id, user_id, messaging, websocket, loop)
|
|
155
|
+
messaging.subscribe(UserProxyAgent.get_user_notifications_topic(user_id), guild_client)
|
|
156
|
+
|
|
157
|
+
user_agent_tag = AgentTag(id=f"user_socket:{user_id}", name=user_name)
|
|
158
|
+
|
|
159
|
+
guild_client.publish(
|
|
160
|
+
Message(
|
|
161
|
+
self._gemstone.get_id(Priority.NORMAL),
|
|
162
|
+
topics=GuildTopics.SYSTEM_TOPIC,
|
|
163
|
+
sender=user_agent_tag,
|
|
164
|
+
format=get_qualified_class_name(UserAgentCreationRequest),
|
|
165
|
+
payload=UserAgentCreationRequest(user_id=user_id, user_name=user_name).model_dump(),
|
|
166
|
+
)
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
try:
|
|
170
|
+
while True:
|
|
171
|
+
try:
|
|
172
|
+
data = await websocket.receive_json()
|
|
173
|
+
except ValueError as e: # pragma: no cover
|
|
174
|
+
logging.error(f"Invalid JSON received: {e}")
|
|
175
|
+
continue
|
|
176
|
+
|
|
177
|
+
id = data.get("id", None)
|
|
178
|
+
|
|
179
|
+
if id and isinstance(id, str):
|
|
180
|
+
idg = self._gemstone.get_id_from_string(id)
|
|
181
|
+
elif id and isinstance(id, int):
|
|
182
|
+
idg = self._gemstone.get_id_from_int(id)
|
|
183
|
+
|
|
184
|
+
priority = Priority(data.get("priority", Priority.NORMAL.value))
|
|
185
|
+
if not idg or idg.timestamp - (time.time_ns() // 1000000) > 1000: # pragma: no cover
|
|
186
|
+
data["id"] = self._gemstone.get_id(priority).to_int()
|
|
187
|
+
else:
|
|
188
|
+
data["id"] = idg.to_int()
|
|
189
|
+
|
|
190
|
+
with self.tracer.start_as_current_span(
|
|
191
|
+
"websocket:receive_message",
|
|
192
|
+
attributes={
|
|
193
|
+
"user_id": user_id,
|
|
194
|
+
"guild_id": guild_id,
|
|
195
|
+
"guild_name": guild_spec.name,
|
|
196
|
+
"message_id": f"id:{data['id']}",
|
|
197
|
+
"message_format": data.get("format", "UNKNOWN"),
|
|
198
|
+
},
|
|
199
|
+
) as span:
|
|
200
|
+
|
|
201
|
+
carrier: Dict[str, str] = {}
|
|
202
|
+
TraceContextTextMapPropagator().inject(carrier, context=trace.set_span_in_context(span))
|
|
203
|
+
|
|
204
|
+
logging.debug(f"Carrier: {carrier}")
|
|
205
|
+
|
|
206
|
+
data["sender"] = user_agent_tag.model_dump()
|
|
207
|
+
|
|
208
|
+
if "thread" not in data or not data["thread"]:
|
|
209
|
+
data["thread"] = []
|
|
210
|
+
|
|
211
|
+
traceparent = carrier.get("traceparent", TelemetryConstants.NO_TRACING)
|
|
212
|
+
|
|
213
|
+
data["thread"].append(data["id"])
|
|
214
|
+
data["traceparent"] = traceparent
|
|
215
|
+
|
|
216
|
+
try:
|
|
217
|
+
logging.debug(f"Received message: {data}")
|
|
218
|
+
message = Message(
|
|
219
|
+
idg,
|
|
220
|
+
topics=UserProxyAgent.get_user_inbox_topic(user_id),
|
|
221
|
+
sender=user_agent_tag,
|
|
222
|
+
format=get_qualified_class_name(Message),
|
|
223
|
+
payload=data,
|
|
224
|
+
thread=[data["id"]],
|
|
225
|
+
traceparent=traceparent,
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
logging.debug(f"Publishing message: {message.model_dump_json()}")
|
|
229
|
+
|
|
230
|
+
if message:
|
|
231
|
+
guild_client.publish(message)
|
|
232
|
+
|
|
233
|
+
except ValueError as e: # pragma: no cover
|
|
234
|
+
logging.error(f"Invalid message received: {e}")
|
|
235
|
+
continue
|
|
236
|
+
|
|
237
|
+
except WebSocketDisconnect:
|
|
238
|
+
messaging.unsubscribe(UserProxyAgent.get_user_notifications_topic(user_id), guild_client)
|
|
239
|
+
|
|
240
|
+
async def get_historical_user_notifications(self, guild_id: str, user_id: str, engine: Engine) -> List[Message]:
|
|
241
|
+
guild_spec = await self.get_or_fetch_guild_spec(guild_id, engine)
|
|
242
|
+
|
|
243
|
+
logging.debug(f"Retrieving historical messages for User[{user_id}] in Guild[{guild_id}]")
|
|
244
|
+
|
|
245
|
+
if guild_spec:
|
|
246
|
+
mi = await self.get_or_create_messaging_interface(guild_spec)
|
|
247
|
+
msgs = mi.get_messages(UserProxyAgent.get_user_notifications_topic(user_id))
|
|
248
|
+
logging.debug(f"Retrieved {len(msgs)} messages")
|
|
249
|
+
return msgs
|
|
250
|
+
else: # pragma: no cover
|
|
251
|
+
return []
|
|
252
|
+
|
|
253
|
+
@classmethod
|
|
254
|
+
def get_instance(cls) -> "GuildCommunicationManager":
|
|
255
|
+
gcm = GuildCommunicationManager()
|
|
256
|
+
return gcm
|