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,426 @@
|
|
|
1
|
+
import importlib
|
|
2
|
+
import json
|
|
3
|
+
import logging
|
|
4
|
+
import mimetypes
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
from typing import Dict, List, Optional
|
|
7
|
+
from urllib.parse import quote
|
|
8
|
+
|
|
9
|
+
import griffe
|
|
10
|
+
from fastapi import APIRouter, Depends, File, Form, HTTPException, Response, UploadFile
|
|
11
|
+
from fastapi.responses import JSONResponse, StreamingResponse
|
|
12
|
+
from griffe import Alias, Class, Module, Object
|
|
13
|
+
from pydantic import BaseModel, ValidationError
|
|
14
|
+
from sqlalchemy import Engine
|
|
15
|
+
from starlette import status
|
|
16
|
+
|
|
17
|
+
from rustic_ai.api_server.api_dependency_manager import ApiDependencyManager
|
|
18
|
+
from rustic_ai.api_server.guilds.comms_manager import GuildCommunicationManager
|
|
19
|
+
from rustic_ai.api_server.guilds.schema import IdInfo
|
|
20
|
+
from rustic_ai.api_server.guilds.service import GuildService
|
|
21
|
+
from rustic_ai.core import Agent
|
|
22
|
+
from rustic_ai.core.agents.commons.media import MediaLink
|
|
23
|
+
from rustic_ai.core.guild.agent_ext.depends.filesystem import FileSystem
|
|
24
|
+
from rustic_ai.core.guild.dsl import GuildSpec
|
|
25
|
+
from rustic_ai.core.guild.metaprog.agent_registry import AgentRegistry
|
|
26
|
+
from rustic_ai.core.guild.metastore import Metastore
|
|
27
|
+
from rustic_ai.core.messaging.core.message import Message
|
|
28
|
+
from rustic_ai.core.utils.basic_class_utils import get_class_from_name
|
|
29
|
+
|
|
30
|
+
router = APIRouter()
|
|
31
|
+
guild_service = GuildService()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@router.post("/guilds", response_model=IdInfo, status_code=status.HTTP_201_CREATED, operation_id="createGuild")
|
|
35
|
+
def create_guild(guild_spec: GuildSpec):
|
|
36
|
+
"""
|
|
37
|
+
Creates a new guild and adds it to the database.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
guild_spec (GuildSpec): The spec for the new guild
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
IdInfo: The id of the newly created guild
|
|
44
|
+
"""
|
|
45
|
+
if not guild_spec:
|
|
46
|
+
raise HTTPException(status_code=400, detail="Invalid input") # pragma: no cover
|
|
47
|
+
|
|
48
|
+
try:
|
|
49
|
+
guild_id = guild_service.create_guild(Metastore.get_db_url(), guild_spec)
|
|
50
|
+
logging.debug(f"New guild created: {guild_id}")
|
|
51
|
+
return IdInfo(id=guild_id)
|
|
52
|
+
except ValidationError as e:
|
|
53
|
+
raise HTTPException(status_code=400, detail=e.errors()) # pragma: no cover
|
|
54
|
+
except Exception as e:
|
|
55
|
+
raise HTTPException(status_code=500, detail=str(e)) # pragma: no cover
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@router.get("/guilds/{guild_id}", response_model=GuildSpec, operation_id="getGuildDetailsById")
|
|
59
|
+
def get_guild(guild_id: str, engine=Depends(Metastore.get_engine)) -> GuildSpec:
|
|
60
|
+
"""
|
|
61
|
+
Retrieves details for a guild based on the provided guild_id.
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
guild_id (str): The ID of the guild to retrieve details for.
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
GuildSpec: The retrieved guild details, or None if the guild was not found.
|
|
68
|
+
|
|
69
|
+
Raises:
|
|
70
|
+
HTTPException: If the guild is not found, raises an HTTPException with a status code of 404.
|
|
71
|
+
"""
|
|
72
|
+
logging.debug(f"Retrieving details for guild: {guild_id}")
|
|
73
|
+
maybeGuild = guild_service.get_guild(engine, guild_id)
|
|
74
|
+
|
|
75
|
+
if maybeGuild is None:
|
|
76
|
+
raise HTTPException(status_code=404, detail="Guild not found")
|
|
77
|
+
|
|
78
|
+
return maybeGuild
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@router.get("/guilds/{guild_id}/{user_id}/messages", operation_id="getHistoricalUserMessages")
|
|
82
|
+
async def get_historical_user_notifications(
|
|
83
|
+
guild_id: str,
|
|
84
|
+
user_id: str,
|
|
85
|
+
guild_comm_manager: GuildCommunicationManager = Depends(GuildCommunicationManager.get_instance),
|
|
86
|
+
engine: Engine = Depends(Metastore.get_engine),
|
|
87
|
+
) -> List[Message]:
|
|
88
|
+
return await guild_comm_manager.get_historical_user_notifications(guild_id, user_id, engine)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _get_meta_file_name(filename: str) -> str:
|
|
92
|
+
return f".{filename}.meta"
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
async def upload_file(
|
|
96
|
+
guild_id: str,
|
|
97
|
+
file: UploadFile,
|
|
98
|
+
engine: Engine,
|
|
99
|
+
api_deps_manager: ApiDependencyManager,
|
|
100
|
+
agent_id: Optional[str] = None,
|
|
101
|
+
metadata: Optional[str] = None,
|
|
102
|
+
):
|
|
103
|
+
"""
|
|
104
|
+
Uploads a file to a guild.
|
|
105
|
+
"""
|
|
106
|
+
if not file or not file.filename:
|
|
107
|
+
raise HTTPException(status_code=400, detail="Invalid input: file and filename are required")
|
|
108
|
+
|
|
109
|
+
filesystem: FileSystem = api_deps_manager.get_dependency("filesystem", engine, guild_id, agent_id)
|
|
110
|
+
contents = await file.read()
|
|
111
|
+
|
|
112
|
+
if filesystem.exists(file.filename):
|
|
113
|
+
raise HTTPException(status_code=409, detail="File already exists")
|
|
114
|
+
|
|
115
|
+
file_meta = json.loads(metadata) if metadata else {}
|
|
116
|
+
file_meta["content_length"] = len(contents)
|
|
117
|
+
file_meta["content_type"] = file.content_type
|
|
118
|
+
file_meta["uploaded_at"] = datetime.now(timezone.utc).isoformat()
|
|
119
|
+
|
|
120
|
+
try:
|
|
121
|
+
with filesystem.open(file.filename, "wb") as f:
|
|
122
|
+
f.write(contents)
|
|
123
|
+
with filesystem.open(_get_meta_file_name(file.filename), "wb") as mf: # type: ignore[arg-type]
|
|
124
|
+
mf.write(json.dumps(file_meta).encode("utf-8"))
|
|
125
|
+
except Exception as e:
|
|
126
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
127
|
+
|
|
128
|
+
encoded_filename = quote(file.filename)
|
|
129
|
+
|
|
130
|
+
return JSONResponse(
|
|
131
|
+
content={
|
|
132
|
+
"guild_id": guild_id,
|
|
133
|
+
"filename": file.filename,
|
|
134
|
+
"url": f"/rustic/api/guilds/{guild_id}/files/{encoded_filename}",
|
|
135
|
+
"content_type": file.content_type,
|
|
136
|
+
"content_length": len(contents),
|
|
137
|
+
}
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@router.post("/guilds/{guild_id}/files/", operation_id="uploadFileForGuild")
|
|
142
|
+
async def upload_file_for_guild(
|
|
143
|
+
guild_id: str,
|
|
144
|
+
file: UploadFile = File(...),
|
|
145
|
+
file_meta: Optional[str] = Form(None),
|
|
146
|
+
engine: Engine = Depends(Metastore.get_engine),
|
|
147
|
+
api_deps_manager: ApiDependencyManager = Depends(ApiDependencyManager.get_instance),
|
|
148
|
+
):
|
|
149
|
+
return await upload_file(guild_id, file, engine, api_deps_manager, metadata=file_meta)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
@router.post(
|
|
153
|
+
"/guilds/{guild_id}/agents/{agent_id}/files/", operation_id="uploadFileForAgent", response_model=List[MediaLink]
|
|
154
|
+
)
|
|
155
|
+
async def upload_file_for_agent(
|
|
156
|
+
guild_id: str,
|
|
157
|
+
agent_id: str,
|
|
158
|
+
file: UploadFile = File(...),
|
|
159
|
+
file_meta: Optional[str] = Form(None),
|
|
160
|
+
engine: Engine = Depends(Metastore.get_engine),
|
|
161
|
+
api_deps_manager: ApiDependencyManager = Depends(ApiDependencyManager.get_instance),
|
|
162
|
+
):
|
|
163
|
+
return await upload_file(guild_id, file, engine, api_deps_manager, agent_id, metadata=file_meta)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
async def list_files(
|
|
167
|
+
guild_id: str, engine: Engine, api_deps_manager: ApiDependencyManager, agent_id: Optional[str] = None
|
|
168
|
+
):
|
|
169
|
+
"""Lists available files for a guild/agent."""
|
|
170
|
+
filesystem: FileSystem = api_deps_manager.get_dependency("filesystem", engine, guild_id, agent_id)
|
|
171
|
+
try:
|
|
172
|
+
files_with_details = filesystem.ls("/")
|
|
173
|
+
result = []
|
|
174
|
+
for file_details in files_with_details:
|
|
175
|
+
file_name = file_details["name"]
|
|
176
|
+
if not file_name.startswith("."):
|
|
177
|
+
file_meta = json.load(filesystem.open(_get_meta_file_name(file_name), "r"))
|
|
178
|
+
mimetype = file_meta["content_type"]
|
|
179
|
+
result.append(
|
|
180
|
+
MediaLink(
|
|
181
|
+
url=file_name,
|
|
182
|
+
name=file_name,
|
|
183
|
+
metadata={x: file_meta[x] for x in file_meta if x != "content_type"},
|
|
184
|
+
on_filesystem=True,
|
|
185
|
+
mimetype=mimetype,
|
|
186
|
+
).model_dump()
|
|
187
|
+
)
|
|
188
|
+
return JSONResponse(content=result)
|
|
189
|
+
except Exception as e:
|
|
190
|
+
logging.error(e)
|
|
191
|
+
# An exception is thrown when no such directory exists.
|
|
192
|
+
# This can happen when no files have been uploaded for the guild/agent yet.
|
|
193
|
+
# In such cases, we must return an empty list
|
|
194
|
+
return JSONResponse(content=[])
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
@router.get("/guilds/{guild_id}/files/", operation_id="listFilesForGuild")
|
|
198
|
+
async def list_files_for_guild(
|
|
199
|
+
guild_id: str,
|
|
200
|
+
engine: Engine = Depends(Metastore.get_engine),
|
|
201
|
+
api_deps_manager: ApiDependencyManager = Depends(ApiDependencyManager.get_instance),
|
|
202
|
+
):
|
|
203
|
+
return await list_files(guild_id, engine, api_deps_manager)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
@router.get("/guilds/{guild_id}/agents/{agent_id}/files/", operation_id="listFilesForAgent")
|
|
207
|
+
async def list_files_for_agent(
|
|
208
|
+
guild_id: str,
|
|
209
|
+
agent_id: str,
|
|
210
|
+
engine: Engine = Depends(Metastore.get_engine),
|
|
211
|
+
api_deps_manager: ApiDependencyManager = Depends(ApiDependencyManager.get_instance),
|
|
212
|
+
):
|
|
213
|
+
return await list_files(guild_id, engine, api_deps_manager, agent_id)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
async def download_file(
|
|
217
|
+
guild_id: str,
|
|
218
|
+
filename: str,
|
|
219
|
+
engine: Engine,
|
|
220
|
+
api_deps_manager: ApiDependencyManager,
|
|
221
|
+
agent_id: Optional[str] = None,
|
|
222
|
+
):
|
|
223
|
+
"""
|
|
224
|
+
Downloads a file from a guild.
|
|
225
|
+
"""
|
|
226
|
+
|
|
227
|
+
filesystem: FileSystem = api_deps_manager.get_dependency("filesystem", engine, guild_id, agent_id)
|
|
228
|
+
|
|
229
|
+
if not filesystem.exists(filename):
|
|
230
|
+
raise HTTPException(status_code=404, detail="File not found")
|
|
231
|
+
|
|
232
|
+
try:
|
|
233
|
+
|
|
234
|
+
def serve_file():
|
|
235
|
+
with filesystem.open(filename, "rb") as file_like:
|
|
236
|
+
yield from file_like
|
|
237
|
+
|
|
238
|
+
response = StreamingResponse(serve_file(), media_type="application/octet-stream")
|
|
239
|
+
response.headers["Content-Disposition"] = f"attachment; filename={filename}"
|
|
240
|
+
return response
|
|
241
|
+
|
|
242
|
+
except Exception as e:
|
|
243
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
async def get_file_content(
|
|
247
|
+
guild_id: str,
|
|
248
|
+
filename: str,
|
|
249
|
+
engine: Engine,
|
|
250
|
+
api_deps_manager: ApiDependencyManager,
|
|
251
|
+
agent_id: Optional[str] = None,
|
|
252
|
+
):
|
|
253
|
+
"""
|
|
254
|
+
Gets the file from a guild.
|
|
255
|
+
"""
|
|
256
|
+
|
|
257
|
+
filesystem: FileSystem = api_deps_manager.get_dependency("filesystem", engine, guild_id, agent_id)
|
|
258
|
+
|
|
259
|
+
if not filesystem.exists(filename):
|
|
260
|
+
raise HTTPException(status_code=404, detail="File not found")
|
|
261
|
+
|
|
262
|
+
try:
|
|
263
|
+
with filesystem.open(filename, "rb") as file_like:
|
|
264
|
+
return file_like.read()
|
|
265
|
+
except Exception as e:
|
|
266
|
+
logging.error(f"Error getting file content: {e}")
|
|
267
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
@router.get("/guilds/{guild_id}/files/{filename}", operation_id="getFileForGuild")
|
|
271
|
+
async def get_file_for_guild(
|
|
272
|
+
guild_id: str,
|
|
273
|
+
filename: str,
|
|
274
|
+
download: Optional[bool] = False,
|
|
275
|
+
engine: Engine = Depends(Metastore.get_engine),
|
|
276
|
+
api_deps_manager: ApiDependencyManager = Depends(ApiDependencyManager.get_instance),
|
|
277
|
+
):
|
|
278
|
+
if download:
|
|
279
|
+
return await download_file(guild_id, filename, engine, api_deps_manager)
|
|
280
|
+
else:
|
|
281
|
+
content = await get_file_content(guild_id, filename, engine, api_deps_manager)
|
|
282
|
+
return Response(content=content, media_type=mimetypes.guess_type(filename)[0])
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
@router.get("/guilds/{guild_id}/agents/{agent_id}/files/{filename}", operation_id="getFileForAgent")
|
|
286
|
+
async def get_file_for_agent(
|
|
287
|
+
guild_id: str,
|
|
288
|
+
agent_id: str,
|
|
289
|
+
filename: str,
|
|
290
|
+
download: Optional[bool] = False,
|
|
291
|
+
engine: Engine = Depends(Metastore.get_engine),
|
|
292
|
+
api_deps_manager: ApiDependencyManager = Depends(ApiDependencyManager.get_instance),
|
|
293
|
+
):
|
|
294
|
+
if download:
|
|
295
|
+
return await download_file(guild_id, filename, engine, api_deps_manager, agent_id)
|
|
296
|
+
else:
|
|
297
|
+
content = await get_file_content(guild_id, filename, engine, api_deps_manager, agent_id)
|
|
298
|
+
return Response(content=content, media_type=mimetypes.guess_type(filename)[0])
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
async def delete_file(
|
|
302
|
+
guild_id: str,
|
|
303
|
+
filename: str,
|
|
304
|
+
engine: Engine,
|
|
305
|
+
api_deps_manager: ApiDependencyManager,
|
|
306
|
+
agent_id: Optional[str] = None,
|
|
307
|
+
):
|
|
308
|
+
"""
|
|
309
|
+
Deletes the file from the guild/agent.
|
|
310
|
+
"""
|
|
311
|
+
|
|
312
|
+
filesystem: FileSystem = api_deps_manager.get_dependency("filesystem", engine, guild_id, agent_id)
|
|
313
|
+
|
|
314
|
+
if not filesystem.exists(filename):
|
|
315
|
+
raise HTTPException(status_code=404, detail="File not found")
|
|
316
|
+
|
|
317
|
+
try:
|
|
318
|
+
filesystem.rm_file(filename)
|
|
319
|
+
filesystem.rm_file(_get_meta_file_name(filename))
|
|
320
|
+
return Response(status_code=204)
|
|
321
|
+
except Exception as e:
|
|
322
|
+
logging.error(f"Error getting file content: {e}")
|
|
323
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
@router.delete(
|
|
327
|
+
"/guilds/{guild_id}/files/{filename}", status_code=status.HTTP_204_NO_CONTENT, operation_id="deleteGuildFile"
|
|
328
|
+
)
|
|
329
|
+
async def delete_file_for_guild(
|
|
330
|
+
guild_id: str,
|
|
331
|
+
filename: str,
|
|
332
|
+
engine: Engine = Depends(Metastore.get_engine),
|
|
333
|
+
api_deps_manager: ApiDependencyManager = Depends(ApiDependencyManager.get_instance),
|
|
334
|
+
):
|
|
335
|
+
return await delete_file(guild_id, filename, engine, api_deps_manager)
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
@router.delete(
|
|
339
|
+
"/guilds/{guild_id}/agents/{agent_id}/files/{filename}",
|
|
340
|
+
status_code=status.HTTP_204_NO_CONTENT,
|
|
341
|
+
operation_id="deleteAgentFile",
|
|
342
|
+
)
|
|
343
|
+
async def delete_files_for_agent(
|
|
344
|
+
guild_id: str,
|
|
345
|
+
agent_id: str,
|
|
346
|
+
filename: str,
|
|
347
|
+
engine: Engine = Depends(Metastore.get_engine),
|
|
348
|
+
api_deps_manager: ApiDependencyManager = Depends(ApiDependencyManager.get_instance),
|
|
349
|
+
):
|
|
350
|
+
return await delete_file(guild_id, filename, engine, api_deps_manager, agent_id)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
_base_agent_class = Agent.get_qualified_class_name()
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _load_agents():
|
|
357
|
+
"""
|
|
358
|
+
Scans the agents module for agents and imports them.
|
|
359
|
+
"""
|
|
360
|
+
packages = ["rustic_ai"]
|
|
361
|
+
|
|
362
|
+
for package in packages:
|
|
363
|
+
all_agents = _scan_module_for_agents(griffe.load(package))
|
|
364
|
+
|
|
365
|
+
for agent in all_agents:
|
|
366
|
+
importlib.import_module(agent.module.path)
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _inherits_agent(member: Class) -> bool:
|
|
370
|
+
if member.is_class and hasattr(member, "bases"):
|
|
371
|
+
for base in member.resolved_bases:
|
|
372
|
+
if _base_agent_class == base.path:
|
|
373
|
+
return True
|
|
374
|
+
elif isinstance(base, Class):
|
|
375
|
+
return _inherits_agent(base)
|
|
376
|
+
return False
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _scan_module_for_agents(module: Module | Object | Alias) -> List[Class]:
|
|
380
|
+
"""
|
|
381
|
+
Scans a module for agents and imports them.
|
|
382
|
+
"""
|
|
383
|
+
all_agents = []
|
|
384
|
+
if module.is_module:
|
|
385
|
+
for name in module.all_members:
|
|
386
|
+
member = module.get_member(name)
|
|
387
|
+
if member.is_alias:
|
|
388
|
+
continue
|
|
389
|
+
elif member.is_module:
|
|
390
|
+
new_agents = _scan_module_for_agents(member)
|
|
391
|
+
all_agents.extend(new_agents)
|
|
392
|
+
elif member.is_class and isinstance(member, Class):
|
|
393
|
+
if _inherits_agent(member):
|
|
394
|
+
all_agents.append(member)
|
|
395
|
+
|
|
396
|
+
return all_agents
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
_load_agents()
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
@router.get("/registry/agents/", response_model=Dict[str, dict], operation_id="getAgentsByClass")
|
|
403
|
+
def get_agents(agent_class: Optional[str] = None):
|
|
404
|
+
if agent_class:
|
|
405
|
+
agent = AgentRegistry.get_agent(agent_class)
|
|
406
|
+
if agent is None:
|
|
407
|
+
raise HTTPException(status_code=404, detail="Agent not found")
|
|
408
|
+
return {agent.qualified_class_name: agent.model_dump()}
|
|
409
|
+
else:
|
|
410
|
+
hidden_agents = ["GuildManagerAgent", "ProbeAgent", "EssentialProbeAgent"]
|
|
411
|
+
agents = AgentRegistry.list_agents()
|
|
412
|
+
all_agents = {name: agent.model_dump() for name, agent in agents.items() if name not in hidden_agents}
|
|
413
|
+
return JSONResponse(content=all_agents, media_type="application/json")
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
@router.get("/registry/message_schema/", response_model=dict, operation_id="getMessageSchemaByClass")
|
|
417
|
+
def get_message_types(message_class: str):
|
|
418
|
+
try:
|
|
419
|
+
class_instance = get_class_from_name(message_class)
|
|
420
|
+
except Exception as e:
|
|
421
|
+
raise HTTPException(status_code=404, detail=str(f"Class {message_class} not found: " + str(e)))
|
|
422
|
+
|
|
423
|
+
if issubclass(class_instance, BaseModel):
|
|
424
|
+
return class_instance.model_json_schema()
|
|
425
|
+
else:
|
|
426
|
+
raise HTTPException(status_code=400, detail="Class is not a subclass of pydantic.BaseModel")
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
|
|
3
|
+
from sqlalchemy import Engine
|
|
4
|
+
|
|
5
|
+
from rustic_ai.core.guild import GuildSpec
|
|
6
|
+
from rustic_ai.core.guild.builders import GuildBuilder
|
|
7
|
+
from rustic_ai.core.guild.metastore import GuildStore
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class GuildService:
|
|
11
|
+
|
|
12
|
+
def create_guild(self, metastore_url: str, guild_spec: GuildSpec) -> str:
|
|
13
|
+
"""
|
|
14
|
+
Creates a new guild and adds it to the database.
|
|
15
|
+
"""
|
|
16
|
+
guild = GuildBuilder.from_spec(guild_spec).bootstrap(metastore_url)
|
|
17
|
+
|
|
18
|
+
return guild.id
|
|
19
|
+
|
|
20
|
+
def get_guild(self, engine: Engine, guild_id: str) -> Optional[GuildSpec]:
|
|
21
|
+
"""
|
|
22
|
+
Retrieves a guild and its agents from the database.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
guild_store = GuildStore(engine)
|
|
26
|
+
guild_model = guild_store.get_guild(guild_id)
|
|
27
|
+
|
|
28
|
+
guild_spec = guild_model.to_guild_spec() if guild_model else None
|
|
29
|
+
|
|
30
|
+
return guild_spec
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import logging
|
|
3
|
+
from contextlib import asynccontextmanager
|
|
4
|
+
|
|
5
|
+
from fastapi import APIRouter, Depends, FastAPI, WebSocket
|
|
6
|
+
from sqlalchemy import Engine
|
|
7
|
+
|
|
8
|
+
from rustic_ai.api_server.guilds.comms_manager import GuildCommunicationManager
|
|
9
|
+
from rustic_ai.api_server.guilds.system_comms_manager import SystemCommunicationManager
|
|
10
|
+
from rustic_ai.core.guild.metastore.database import Metastore
|
|
11
|
+
|
|
12
|
+
socket = APIRouter()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@socket.websocket("/guilds/{guild_id}/usercomms/{user_id}/{user_name}")
|
|
16
|
+
async def websocket_endpoint(
|
|
17
|
+
websocket: WebSocket,
|
|
18
|
+
guild_id: str,
|
|
19
|
+
user_id: str,
|
|
20
|
+
user_name: str,
|
|
21
|
+
guild_comm_manager: GuildCommunicationManager = Depends(GuildCommunicationManager.get_instance),
|
|
22
|
+
engine: Engine = Depends(Metastore.get_engine),
|
|
23
|
+
):
|
|
24
|
+
logging.info(f"Connecting websocket for guild {guild_id} and user {user_id}")
|
|
25
|
+
logging.info(f"Engine: {engine}")
|
|
26
|
+
await guild_comm_manager.handle_websocket_connection(websocket, guild_id, user_id, user_name, engine)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@socket.websocket("/guilds/{guild_id}/syscomms/{user_id}")
|
|
30
|
+
async def system_websocket_endpoint(
|
|
31
|
+
websocket: WebSocket,
|
|
32
|
+
guild_id: str,
|
|
33
|
+
user_id: str,
|
|
34
|
+
system_comm_manager: SystemCommunicationManager = Depends(SystemCommunicationManager.get_instance),
|
|
35
|
+
engine: Engine = Depends(Metastore.get_engine),
|
|
36
|
+
):
|
|
37
|
+
logging.info(f"Connecting system updates websocket for guild {guild_id} and user {user_id}")
|
|
38
|
+
logging.info(f"Engine: {engine}")
|
|
39
|
+
await system_comm_manager.handle_websocket_connection(websocket, guild_id, user_id, engine)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@asynccontextmanager
|
|
43
|
+
async def lifespan(app: FastAPI):
|
|
44
|
+
try:
|
|
45
|
+
logging.info("Starting communication managers")
|
|
46
|
+
yield
|
|
47
|
+
finally:
|
|
48
|
+
logging.info("Shutting down communication managers")
|
|
49
|
+
await asyncio.gather(
|
|
50
|
+
GuildCommunicationManager.get_instance().shutdown(),
|
|
51
|
+
SystemCommunicationManager.get_instance().shutdown(),
|
|
52
|
+
)
|