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.
@@ -0,0 +1,607 @@
1
+ from typing import Dict, List, Optional, Sequence
2
+
3
+ from fastapi import HTTPException
4
+ from sqlalchemy import Engine, join
5
+ from sqlmodel import Session, col, select
6
+
7
+ from rustic_ai.core.guild.dsl import GuildSpec
8
+ from rustic_ai.core.guild.metaprog.agent_registry import AgentEntry
9
+ from rustic_ai.core.guild.metastore import GuildModel
10
+
11
+ from .models import (
12
+ AgentIcon,
13
+ AgentNameWithIcon,
14
+ BasicGuildInfo,
15
+ Blueprint,
16
+ BlueprintAgentIcon,
17
+ BlueprintCategory,
18
+ BlueprintCategoryCreate,
19
+ BlueprintCategoryResponse,
20
+ BlueprintCommand,
21
+ BlueprintCreate,
22
+ BlueprintDetailsResponse,
23
+ BlueprintExposure,
24
+ BlueprintGuild,
25
+ BlueprintInfoResponse,
26
+ BlueprintResponseWithAccessReason,
27
+ BlueprintReview,
28
+ BlueprintReviewCreate,
29
+ BlueprintReviewResponse,
30
+ BlueprintReviewsResponse,
31
+ BlueprintSharedWithOrganization,
32
+ BlueprintStarterPrompt,
33
+ BlueprintTag,
34
+ CatalogAgentEntry,
35
+ OrganizationGuild,
36
+ Tag,
37
+ UserGuild,
38
+ )
39
+
40
+
41
+ class CatalogStore:
42
+ def __init__(self, engine: Engine):
43
+ self.engine = engine
44
+
45
+ def create_or_get_tags(self, tag_names: List[str]) -> List[Tag]:
46
+ query = select(Tag).where(Tag.tag.in_(tag_names)) # type:ignore
47
+ with Session(self.engine) as session:
48
+ existing_tags = session.exec(query).all()
49
+ existing_tag_names = {tag.tag for tag in existing_tags}
50
+ new_tag_names = set(tag_names) - existing_tag_names
51
+ new_tags = [Tag(tag=name) for name in new_tag_names]
52
+ session.add_all(new_tags)
53
+ session.commit()
54
+ tags = session.exec(query).all()
55
+ return list(tags)
56
+
57
+ def create_blueprint(self, blueprint_create: BlueprintCreate) -> str:
58
+ with Session(self.engine) as session:
59
+ try:
60
+ blueprint_details = blueprint_create.model_dump(
61
+ exclude={
62
+ "spec": {"id": True, "agents": {"__all__": {"id"}}},
63
+ "tags": True,
64
+ "commands": True,
65
+ "starter_prompts": True,
66
+ "agent_icons": True,
67
+ }
68
+ )
69
+ blueprint = Blueprint.model_validate(blueprint_details)
70
+ session.add(blueprint)
71
+ session.commit()
72
+ session.refresh(blueprint)
73
+
74
+ agent_specs = blueprint.spec.get("agents", [])
75
+ unique_class_names = set()
76
+ for agent in agent_specs:
77
+ class_name = agent["class_name"]
78
+ if class_name not in unique_class_names:
79
+ agent_entry = session.get(CatalogAgentEntry, class_name)
80
+ if agent_entry:
81
+ blueprint.agents.append(agent_entry)
82
+ unique_class_names.add(class_name)
83
+
84
+ if blueprint_create.tags and len(blueprint_create.tags) > 0:
85
+ tags = self.create_or_get_tags(blueprint_create.tags)
86
+ blueprint.tags.extend(tags)
87
+ if blueprint_create.commands and len(blueprint_create.commands) > 0:
88
+ commands = [
89
+ BlueprintCommand(command=command, blueprint_id=blueprint.id)
90
+ for command in blueprint_create.commands
91
+ ]
92
+ blueprint.commands.extend(commands)
93
+ if blueprint_create.starter_prompts and len(blueprint_create.starter_prompts) > 0:
94
+ starter_prompts = [
95
+ BlueprintStarterPrompt(prompt=prompt, blueprint_id=blueprint.id)
96
+ for prompt in blueprint_create.starter_prompts
97
+ ]
98
+ blueprint.starter_prompts.extend(starter_prompts)
99
+
100
+ session.commit()
101
+
102
+ return blueprint.id
103
+
104
+ except HTTPException:
105
+ raise
106
+
107
+ def get_blueprint(self, blueprint_id: str) -> Optional[BlueprintDetailsResponse]:
108
+ with Session(self.engine) as session:
109
+ blueprint = session.get(Blueprint, blueprint_id)
110
+ if not blueprint:
111
+ return None
112
+ return BlueprintDetailsResponse.from_table(blueprint)
113
+
114
+ def add_tag_to_blueprint(self, blueprint_id: str, tag: str):
115
+ with Session(self.engine) as session:
116
+ blueprint = session.get(Blueprint, blueprint_id)
117
+ if not blueprint:
118
+ raise HTTPException(status_code=404, detail="Blueprint not found")
119
+
120
+ stored_tag = self.create_or_get_tags([tag])[0]
121
+ etag = session.exec(
122
+ select(BlueprintTag)
123
+ .where(BlueprintTag.tag_id == stored_tag.id)
124
+ .where(BlueprintTag.blueprint_id == blueprint_id)
125
+ ).first()
126
+
127
+ if etag:
128
+ raise HTTPException(status_code=409, detail=f"Blueprint {blueprint_id} already tagged with {tag}")
129
+ btag = BlueprintTag(tag_id=stored_tag.id, blueprint_id=blueprint_id)
130
+ session.add(btag)
131
+ session.commit()
132
+
133
+ def remove_tag_from_blueprint(self, blueprint_id: str, tag: str):
134
+ with Session(self.engine) as session:
135
+ blueprint = session.get(Blueprint, blueprint_id)
136
+ if not blueprint:
137
+ raise HTTPException(status_code=404, detail="Blueprint not found")
138
+ stored_tag = session.exec(select(Tag).where(Tag.tag == tag)).first()
139
+ if not stored_tag:
140
+ raise HTTPException(status_code=404, detail=f"Tag {tag} not found")
141
+ etag = session.exec(
142
+ select(BlueprintTag)
143
+ .where(BlueprintTag.tag_id == stored_tag.id)
144
+ .where(BlueprintTag.blueprint_id == blueprint_id)
145
+ ).first()
146
+
147
+ if not etag:
148
+ raise HTTPException(status_code=404, detail=f"Tag {tag} not found on blueprint {blueprint_id}")
149
+
150
+ session.delete(etag)
151
+ session.commit()
152
+
153
+ def get_blueprints_by_tag(self, tag: str) -> List[BlueprintInfoResponse]:
154
+ with Session(self.engine) as session:
155
+ stmt = select(Blueprint).join(BlueprintTag).join(Tag).where(Tag.tag == tag)
156
+ blueprints = session.exec(stmt).all()
157
+ return [BlueprintInfoResponse.from_table(b) for b in blueprints]
158
+
159
+ def get_blueprints_by_category(self, category_name: str) -> List[BlueprintInfoResponse]:
160
+ with Session(self.engine) as session:
161
+ category = session.exec(select(BlueprintCategory).where(BlueprintCategory.name == category_name)).first()
162
+ if not category:
163
+ raise HTTPException(status_code=404, detail=f"Category {category_name} not found")
164
+
165
+ return [BlueprintInfoResponse.from_table(b) for b in category.blueprints]
166
+
167
+ def get_blueprints_by_author(self, author_id: str) -> List[BlueprintInfoResponse]:
168
+ with Session(self.engine) as session:
169
+ statement = select(Blueprint).where(Blueprint.author_id == author_id)
170
+ blueprints = session.exec(statement).all()
171
+ return [BlueprintInfoResponse.from_table(b) for b in blueprints]
172
+
173
+ def get_blueprints_by_organization(self, organization_id: str) -> List[BlueprintInfoResponse]:
174
+ with Session(self.engine) as session:
175
+ statement = select(Blueprint).where(Blueprint.organization_id == organization_id)
176
+ blueprints = session.exec(statement).all()
177
+ return [BlueprintInfoResponse.from_table(b) for b in blueprints]
178
+
179
+ def share_blueprint(self, blueprint_id: str, organization_id: str):
180
+ with Session(self.engine) as session:
181
+ blueprint = session.get(Blueprint, blueprint_id)
182
+ if not blueprint:
183
+ raise HTTPException(status_code=404, detail=f"Blueprint {blueprint_id} not found")
184
+
185
+ blueprint.sqlmodel_update({"exposure": BlueprintExposure.SHARED})
186
+ shared_with_organizations = BlueprintSharedWithOrganization(
187
+ organization_id=organization_id, blueprint_id=blueprint_id
188
+ )
189
+ session.add(blueprint)
190
+ session.add(shared_with_organizations)
191
+ session.commit()
192
+
193
+ def unshare_blueprint(self, blueprint_id: str, organization_id: str):
194
+ with Session(self.engine) as session:
195
+ blueprint = session.get(Blueprint, blueprint_id)
196
+ if not blueprint:
197
+ raise HTTPException(status_code=404, detail=f"Blueprint {blueprint_id} not found")
198
+
199
+ statement = (
200
+ select(BlueprintSharedWithOrganization)
201
+ .where(BlueprintSharedWithOrganization.organization_id == organization_id)
202
+ .where(BlueprintSharedWithOrganization.blueprint_id == blueprint_id)
203
+ )
204
+ entry = session.exec(statement).first()
205
+ session.delete(entry)
206
+ session.commit()
207
+
208
+ def get_blueprints_shared_with_organization(self, organization_id: str) -> List[BlueprintInfoResponse]:
209
+ with Session(self.engine) as session:
210
+ statement = (
211
+ select(Blueprint)
212
+ .join(BlueprintSharedWithOrganization)
213
+ .where(BlueprintSharedWithOrganization.organization_id == organization_id)
214
+ )
215
+ shared_blueprints = session.exec(statement).all()
216
+ return [BlueprintInfoResponse.from_table(b) for b in shared_blueprints]
217
+
218
+ def get_organization_with_shared_blueprint(self, blueprint_id: str) -> List[str]:
219
+ with Session(self.engine) as session:
220
+ blueprint = session.get(Blueprint, blueprint_id)
221
+ if not blueprint:
222
+ raise HTTPException(status_code=404, detail=f"Blueprint {blueprint_id} not found")
223
+
224
+ statement = select(BlueprintSharedWithOrganization).where(
225
+ BlueprintSharedWithOrganization.blueprint_id == blueprint_id
226
+ )
227
+ shared_organizations = session.exec(statement).all()
228
+ return [bp_org.organization_id for bp_org in shared_organizations]
229
+
230
+ def create_blueprint_review(self, blueprint_id: str, review_model: BlueprintReviewCreate) -> str:
231
+ with Session(self.engine) as session:
232
+ review = BlueprintReview.model_validate({"blueprint_id": blueprint_id, **review_model.model_dump()})
233
+
234
+ blueprint = session.get(Blueprint, blueprint_id)
235
+ if not blueprint:
236
+ raise HTTPException(status_code=404, detail=f"Blueprint {blueprint_id} not found")
237
+
238
+ session.add(review)
239
+ session.commit()
240
+ session.refresh(review)
241
+ return review.id
242
+
243
+ def get_blueprint_reviews(self, blueprint_id: str) -> BlueprintReviewsResponse:
244
+ with Session(self.engine) as session:
245
+ blueprint = session.get(Blueprint, blueprint_id)
246
+ if not blueprint:
247
+ raise HTTPException(status_code=404, detail=f"Blueprint {blueprint_id} not found")
248
+
249
+ reviews = [BlueprintReviewResponse.model_validate(r) for r in blueprint.reviews]
250
+ return BlueprintReviewsResponse(reviews=reviews)
251
+
252
+ def get_blueprint_review(self, review_id: str) -> BlueprintReviewResponse:
253
+ with Session(self.engine) as session:
254
+ review = session.get(BlueprintReview, review_id)
255
+ return BlueprintReviewResponse.model_validate(review)
256
+
257
+ @staticmethod
258
+ def _blueprint_with_org_access(
259
+ blueprint: Blueprint, org_id: Optional[str] = None
260
+ ) -> BlueprintResponseWithAccessReason:
261
+ blueprint_info = BlueprintInfoResponse.from_table(blueprint).model_dump()
262
+ return BlueprintResponseWithAccessReason(**blueprint_info, access_organization_id=org_id)
263
+
264
+ def get_user_accessible_blueprints(self, user_id: str) -> List[BlueprintResponseWithAccessReason]:
265
+ with Session(self.engine) as session:
266
+
267
+ public_blueprints_list = session.exec(
268
+ select(Blueprint).where(Blueprint.exposure == BlueprintExposure.PUBLIC)
269
+ ).all()
270
+
271
+ public_blueprints: Dict[str, BlueprintResponseWithAccessReason] = {
272
+ b.id: self._blueprint_with_org_access(b) for b in public_blueprints_list
273
+ }
274
+
275
+ owned_blueprints_list = session.exec(select(Blueprint).where(Blueprint.author_id == user_id)).all()
276
+
277
+ owned_blueprints: Dict[str, BlueprintResponseWithAccessReason] = {
278
+ b.id: self._blueprint_with_org_access(b) for b in owned_blueprints_list
279
+ }
280
+
281
+ # TODO - revisit this when there is a separate central app repository
282
+ # user_orgs = user.organizations
283
+ #
284
+ # org_owned_blueprints: Dict[str, BlueprintResponseWithAccessReason] = {}
285
+ # shared_blueprints: Dict[str, BlueprintResponseWithAccessReason] = {}
286
+ # for org in user_orgs:
287
+ # org_owned_blueprints.update(
288
+ # {
289
+ # b.id: self._blueprint_with_org_access(b, org_id=org.id)
290
+ # for b in org.blueprints
291
+ # if b.exposure == BlueprintExposure.ORGANIZATION
292
+ # }
293
+ # )
294
+ #
295
+ # shared_blueprints.update(
296
+ # {
297
+ # b.id: self._blueprint_with_org_access(b, org_id=org.id)
298
+ # for b in org.shared_blueprints
299
+ # if b.exposure == BlueprintExposure.SHARED
300
+ # }
301
+ # )
302
+ # accessible_bps = {**public_blueprints, **owned_blueprints, **org_owned_blueprints, **shared_blueprints}
303
+ accessible_bps = {**public_blueprints, **owned_blueprints}
304
+
305
+ return list(accessible_bps.values())
306
+
307
+ def create_category(self, category_create: BlueprintCategoryCreate) -> str:
308
+ with Session(self.engine) as session:
309
+ category = BlueprintCategory.model_validate(category_create)
310
+ session.add(category)
311
+ session.commit()
312
+ session.refresh(category)
313
+ return category.id
314
+
315
+ def get_category(self, category_id: str) -> BlueprintCategoryResponse:
316
+ with Session(self.engine) as session:
317
+ category = session.get(BlueprintCategory, category_id)
318
+ return BlueprintCategoryResponse.model_validate(category)
319
+
320
+ def get_categories(self) -> List[BlueprintCategory]:
321
+ with Session(self.engine) as session:
322
+ categories = session.exec(select(BlueprintCategory)).all()
323
+ return list(categories)
324
+
325
+ def get_tags(self) -> List[str]:
326
+ with Session(self.engine) as session:
327
+ tags = session.exec(select(Tag.tag).distinct()).all()
328
+ return [t for t in tags]
329
+
330
+ def add_guild_to_blueprint(self, blueprint_id: str, guild_id: str):
331
+ with Session(self.engine) as session:
332
+ blueprint = session.get(Blueprint, blueprint_id)
333
+ if not blueprint:
334
+ raise HTTPException(status_code=404, detail=f"Blueprint {blueprint_id} not found")
335
+
336
+ guild_model = session.get(GuildModel, guild_id)
337
+ if not guild_model:
338
+ raise HTTPException(status_code=404, detail=f"Guild {guild_id} not found")
339
+
340
+ existing_mapping = session.get(BlueprintGuild, guild_id)
341
+
342
+ if existing_mapping:
343
+ raise HTTPException(status_code=409, detail=f"Guild {guild_id} is already associated with a blueprint")
344
+ b_guild = BlueprintGuild(guild_id=guild_id, blueprint_id=blueprint_id)
345
+ session.add(b_guild)
346
+ session.commit()
347
+
348
+ def get_blueprint_for_guild(self, guild_id: str) -> Optional[BlueprintDetailsResponse]:
349
+ with Session(self.engine) as session:
350
+ guild_model = session.get(GuildModel, guild_id)
351
+ if not guild_model:
352
+ raise HTTPException(status_code=404, detail=f"Guild {guild_id} not found")
353
+
354
+ statement = select(Blueprint).join(BlueprintGuild).where(BlueprintGuild.guild_id == guild_id)
355
+ blueprint = session.exec(statement).first()
356
+ if not blueprint:
357
+ raise HTTPException(status_code=404, detail=f"No Blueprint associated with guild {guild_id}")
358
+ return BlueprintDetailsResponse.from_table(blueprint)
359
+
360
+ @staticmethod
361
+ def get_user_guild(session, user_id: str, guild_id: str):
362
+ guild = session.get(GuildModel, guild_id)
363
+ if not guild:
364
+ raise HTTPException(status_code=404, detail=f"Guild {guild_id} not found")
365
+
366
+ return session.get(UserGuild, {"guild_id": guild_id, "user_id": user_id})
367
+
368
+ @staticmethod
369
+ def get_org_guild(session, org_id: str, guild_id: str):
370
+ guild = session.get(GuildModel, guild_id)
371
+ if not guild:
372
+ raise HTTPException(status_code=404, detail=f"Guild {guild_id} not found")
373
+
374
+ return session.get(OrganizationGuild, {"guild_id": guild_id, "organization_id": org_id})
375
+
376
+ def add_org_to_guild(self, guild_id: str, org_id: str):
377
+ with Session(self.engine) as session:
378
+ existing_mapping = self.get_org_guild(session, org_id, guild_id)
379
+ if existing_mapping:
380
+ raise HTTPException(
381
+ status_code=409, detail=f"Organization {org_id} already associated with guild {guild_id}"
382
+ )
383
+
384
+ session.add(OrganizationGuild(guild_id=guild_id, organization_id=org_id))
385
+ session.commit()
386
+
387
+ def remove_org_from_guild(self, guild_id: str, org_id: str):
388
+ with Session(self.engine) as session:
389
+ existing_mapping = self.get_org_guild(session, org_id, guild_id)
390
+ if not existing_mapping:
391
+ raise HTTPException(
392
+ status_code=404, detail=f"Organization {org_id} is not associated with guild {guild_id}"
393
+ )
394
+
395
+ session.delete(existing_mapping)
396
+ session.commit()
397
+
398
+ def get_guilds_for_org(self, org_id: str) -> List[BasicGuildInfo]:
399
+ with Session(self.engine) as session:
400
+ statement = (
401
+ select(
402
+ GuildModel.id,
403
+ GuildModel.name,
404
+ Blueprint.id.label("blueprint_id"), # type:ignore
405
+ Blueprint.icon,
406
+ )
407
+ .select_from(
408
+ join(GuildModel, OrganizationGuild, GuildModel.id == OrganizationGuild.guild_id) # type:ignore
409
+ .outerjoin(BlueprintGuild, GuildModel.id == BlueprintGuild.guild_id) # type:ignore
410
+ .outerjoin(Blueprint, Blueprint.id == BlueprintGuild.blueprint_id) # type:ignore
411
+ )
412
+ .where(OrganizationGuild.organization_id == org_id)
413
+ )
414
+
415
+ guilds: Sequence[BasicGuildInfo] = session.exec(statement).all() # type:ignore
416
+ return list(guilds)
417
+
418
+ def add_user_to_guild(self, guild_id: str, user_id: str):
419
+ with Session(self.engine) as session:
420
+ existing_mapping = self.get_user_guild(session, user_id, guild_id)
421
+ if existing_mapping:
422
+ raise HTTPException(status_code=409, detail=f"User {user_id} already associated with guild {guild_id}")
423
+
424
+ session.add(UserGuild(guild_id=guild_id, user_id=user_id))
425
+ session.commit()
426
+
427
+ def remove_user_from_guild(self, guild_id: str, user_id: str):
428
+ with Session(self.engine) as session:
429
+ existing_mapping = self.get_user_guild(session, user_id, guild_id)
430
+ if not existing_mapping:
431
+ raise HTTPException(status_code=404, detail=f"User {user_id} is not associated with guild {guild_id}")
432
+
433
+ session.delete(existing_mapping)
434
+ session.commit()
435
+
436
+ def get_guilds_for_user(self, user_id) -> List[BasicGuildInfo]:
437
+ with Session(self.engine) as session:
438
+ statement = (
439
+ select(
440
+ GuildModel.id,
441
+ GuildModel.name,
442
+ Blueprint.id.label("blueprint_id"), # type:ignore
443
+ Blueprint.icon,
444
+ )
445
+ .select_from(
446
+ join(GuildModel, UserGuild, GuildModel.id == UserGuild.guild_id) # type:ignore
447
+ .outerjoin(BlueprintGuild, GuildModel.id == BlueprintGuild.guild_id) # type:ignore
448
+ .outerjoin(Blueprint, Blueprint.id == BlueprintGuild.blueprint_id) # type:ignore
449
+ )
450
+ .where(UserGuild.user_id == user_id)
451
+ )
452
+ guilds: Sequence[BasicGuildInfo] = session.exec(statement).all() # type:ignore
453
+ return list(guilds)
454
+
455
+ def add_agent_icon(self, agent_class: str, icon: str):
456
+ with Session(self.engine) as session:
457
+ existing_icon = session.get(AgentIcon, agent_class)
458
+ if existing_icon:
459
+ existing_icon.icon = icon
460
+ else:
461
+ session.add(AgentIcon(agent_class=agent_class, icon=icon))
462
+ session.commit()
463
+
464
+ def _get_default_agent_icons(self, guildspec: GuildSpec):
465
+ with Session(self.engine) as session:
466
+ agent_classes: set[str] = set([agent.class_name for agent in guildspec.agents])
467
+ default_agent_icons: Sequence[AgentIcon] = session.exec(
468
+ select(AgentIcon).where(col(AgentIcon.agent_class).in_(agent_classes))
469
+ ).all()
470
+ agent_icons_by_class = {agent_icon.agent_class: agent_icon.icon for agent_icon in default_agent_icons}
471
+ return agent_icons_by_class
472
+
473
+ def add_agent_icons_to_blueprint(self, blueprint_id: str, provided_icons: list[AgentNameWithIcon]):
474
+ with Session(self.engine) as session:
475
+ blueprint = session.get(Blueprint, blueprint_id)
476
+ if not blueprint:
477
+ raise HTTPException(status_code=404, detail=f"Blueprint {blueprint_id} not found")
478
+ guild_specs = GuildSpec.model_validate(blueprint.spec)
479
+ agent_names = [x.name for x in guild_specs.agents]
480
+ provided_agent_names = [a.agent_name for a in provided_icons] if provided_icons else []
481
+ if provided_agent_names and not set(provided_agent_names).issubset(set(agent_names)):
482
+ raise HTTPException(
483
+ status_code=400,
484
+ detail="Provided agent names are not a subset of the agent names in the blueprint",
485
+ )
486
+ existing_icons = session.exec(
487
+ select(BlueprintAgentIcon).where(BlueprintAgentIcon.blueprint_id == blueprint_id)
488
+ ).all()
489
+ existing_icon_names = []
490
+ for icon in existing_icons:
491
+ if icon.agent_name in provided_agent_names:
492
+ agent_details: AgentNameWithIcon = provided_icons[provided_agent_names.index(icon.agent_name)]
493
+ icon.icon = agent_details.icon
494
+ existing_icon_names.append(icon.agent_name)
495
+ new_icons = [
496
+ BlueprintAgentIcon(blueprint_id=blueprint_id, agent_name=x.agent_name, icon=x.icon)
497
+ for x in provided_icons
498
+ if x.agent_name not in existing_icon_names
499
+ ]
500
+ if len(new_icons) > 0:
501
+ session.add_all(new_icons)
502
+ session.commit()
503
+
504
+ def get_blueprint_agent_icons(self, blueprint_id: str) -> list[AgentNameWithIcon]:
505
+ with Session(self.engine) as session:
506
+ blueprint = session.get(Blueprint, blueprint_id)
507
+ if not blueprint:
508
+ raise HTTPException(status_code=404, detail=f"Blueprint {blueprint_id} not found")
509
+ bp_agent_icons: Sequence[AgentNameWithIcon] = session.exec(
510
+ select(BlueprintAgentIcon).where(BlueprintAgentIcon.blueprint_id == blueprint_id)
511
+ ).all()
512
+ guild_specs = GuildSpec.model_validate(blueprint.spec)
513
+ result: list[AgentNameWithIcon] = list(bp_agent_icons)
514
+ existing_icons = [agent_icon.agent_name for agent_icon in bp_agent_icons]
515
+ default_icons = self._get_default_agent_icons(guild_specs)
516
+ missing_icons = filter(
517
+ lambda x: x.name not in existing_icons and x.class_name in default_icons, guild_specs.agents
518
+ )
519
+ for agent in missing_icons:
520
+ icon_info = AgentNameWithIcon(agent_name=agent.name, icon=default_icons[agent.class_name])
521
+ result.append(icon_info)
522
+ return result
523
+
524
+ def get_blueprint_agent_icon_by_name(self, blueprint_id: str, agent_name: str) -> AgentNameWithIcon:
525
+ with Session(self.engine) as session:
526
+ blueprint = session.get(Blueprint, blueprint_id)
527
+ if not blueprint:
528
+ raise HTTPException(status_code=404, detail=f"Blueprint {blueprint_id} not found")
529
+ guild_specs = GuildSpec.model_validate(blueprint.spec)
530
+ valid_agent_names = [x.name for x in guild_specs.agents]
531
+ if agent_name and agent_name not in valid_agent_names:
532
+ raise HTTPException(status_code=404, detail=f"Agent {agent_name} does not exist")
533
+ agent_icon: Optional[AgentNameWithIcon] = session.exec(
534
+ select(BlueprintAgentIcon)
535
+ .where(BlueprintAgentIcon.blueprint_id == blueprint_id)
536
+ .where(BlueprintAgentIcon.agent_name == agent_name)
537
+ ).first()
538
+ if agent_icon:
539
+ return AgentNameWithIcon.model_validate(agent_icon)
540
+ default_icons = self._get_default_agent_icons(guild_specs)
541
+ if agent_name in default_icons.keys():
542
+ return AgentNameWithIcon(agent_name=agent_name, icon=default_icons[agent_name])
543
+ else:
544
+ raise HTTPException(status_code=404, detail=f"Agent {agent_name} does not have an icon")
545
+
546
+ def register_agent(self, agent_spec: AgentEntry):
547
+ with Session(self.engine) as session:
548
+ query = select(CatalogAgentEntry).where(
549
+ CatalogAgentEntry.qualified_class_name == agent_spec.qualified_class_name
550
+ )
551
+ existing_agent = session.exec(query).first()
552
+ if existing_agent:
553
+ raise HTTPException(status_code=409, detail=f"'{agent_spec.qualified_class_name}' already exists")
554
+
555
+ else:
556
+ agent_entry = CatalogAgentEntry.from_base(agent_spec)
557
+ session.add(agent_entry)
558
+ session.commit()
559
+
560
+ def get_agent_by_class_name(self, qualified_class_name: str) -> AgentEntry:
561
+ with Session(self.engine) as session:
562
+ agent_entry = session.exec(
563
+ select(CatalogAgentEntry).where(CatalogAgentEntry.qualified_class_name == qualified_class_name)
564
+ ).first()
565
+
566
+ if not agent_entry:
567
+ raise HTTPException(
568
+ status_code=404, detail=f"Agent with qualified class name {qualified_class_name} not found"
569
+ )
570
+ return AgentEntry.model_validate(
571
+ {**agent_entry.model_dump(), "agent_dependencies": list(agent_entry.agent_dependencies.values())}
572
+ )
573
+
574
+ def get_agents(self, class_names: Optional[List[str]] = None, hidden_agents: Optional[List[str]] = None) -> dict:
575
+ with Session(self.engine) as session:
576
+ query = select(CatalogAgentEntry)
577
+
578
+ if class_names:
579
+ query = query.where(col(CatalogAgentEntry.qualified_class_name).in_(class_names))
580
+
581
+ if hidden_agents:
582
+ query = query.where(~col(CatalogAgentEntry.qualified_class_name).in_(hidden_agents))
583
+
584
+ agents = session.exec(query).all()
585
+
586
+ if not agents:
587
+ return {}
588
+
589
+ return {
590
+ agent.qualified_class_name: AgentEntry.model_validate(
591
+ {**agent.model_dump(), "agent_dependencies": list(agent.agent_dependencies.values())}
592
+ )
593
+ for agent in agents
594
+ }
595
+
596
+ def get_agent_by_message_format(self, message_format: str):
597
+ with Session(self.engine) as session:
598
+ # Get all agent entries
599
+ agent_entries = session.exec(select(CatalogAgentEntry)).all()
600
+ # TODO: See if we need another table to store message format or message schema
601
+ for agent_entry in agent_entries:
602
+ handlers = agent_entry.message_handlers or {}
603
+ for handler_data in handlers.values():
604
+ if isinstance(handler_data, dict) and handler_data.get("message_format") == message_format:
605
+ return handler_data.get("message_format_schema")
606
+
607
+ raise HTTPException(status_code=404, detail=f"Agent with message format '{message_format}' not found")