|
4 | 4 | import autogpt_libs.auth.depends
|
5 | 5 | import autogpt_libs.auth.middleware
|
6 | 6 | import fastapi
|
| 7 | +import prisma |
7 | 8 |
|
8 | 9 | import backend.data.graph
|
| 10 | +import backend.integrations.creds_manager |
| 11 | +import backend.integrations.webhooks.graph_lifecycle_hooks |
9 | 12 | import backend.server.v2.library.db
|
10 | 13 | import backend.server.v2.library.model
|
11 | 14 |
|
12 | 15 | logger = logging.getLogger(__name__)
|
13 | 16 |
|
14 | 17 | router = fastapi.APIRouter()
|
| 18 | +integration_creds_manager = ( |
| 19 | + backend.integrations.creds_manager.IntegrationCredentialsManager() |
| 20 | +) |
15 | 21 |
|
16 | 22 |
|
17 | 23 | @router.get(
|
@@ -63,10 +69,53 @@ async def add_agent_to_library(
|
63 | 69 | HTTPException: If there is an error adding the agent to the library
|
64 | 70 | """
|
65 | 71 | try:
|
66 |
| - await backend.server.v2.library.db.add_agent_to_library( |
67 |
| - store_listing_version_id=store_listing_version_id, user_id=user_id |
| 72 | + # Get the graph from the store listing |
| 73 | + store_listing_version = ( |
| 74 | + await prisma.models.StoreListingVersion.prisma().find_unique( |
| 75 | + where={"id": store_listing_version_id}, include={"Agent": True} |
| 76 | + ) |
| 77 | + ) |
| 78 | + |
| 79 | + if not store_listing_version or not store_listing_version.Agent: |
| 80 | + raise fastapi.HTTPException( |
| 81 | + status_code=404, |
| 82 | + detail=f"Store listing version {store_listing_version_id} not found", |
| 83 | + ) |
| 84 | + |
| 85 | + agent = store_listing_version.Agent |
| 86 | + |
| 87 | + if agent.userId == user_id: |
| 88 | + raise fastapi.HTTPException( |
| 89 | + status_code=400, detail="Cannot add own agent to library" |
| 90 | + ) |
| 91 | + |
| 92 | + # Create a new graph from the template |
| 93 | + graph = await backend.data.graph.get_graph( |
| 94 | + agent.id, agent.version, template=True, user_id=user_id |
68 | 95 | )
|
| 96 | + |
| 97 | + if not graph: |
| 98 | + raise fastapi.HTTPException( |
| 99 | + status_code=404, detail=f"Agent {agent.id} not found" |
| 100 | + ) |
| 101 | + |
| 102 | + # Create a deep copy with new IDs |
| 103 | + graph.version = 1 |
| 104 | + graph.is_template = False |
| 105 | + graph.is_active = True |
| 106 | + graph.reassign_ids(user_id=user_id, reassign_graph_id=True) |
| 107 | + |
| 108 | + # Save the new graph |
| 109 | + graph = await backend.data.graph.create_graph(graph, user_id=user_id) |
| 110 | + graph = ( |
| 111 | + await backend.integrations.webhooks.graph_lifecycle_hooks.on_graph_activate( |
| 112 | + graph, |
| 113 | + get_credentials=lambda id: integration_creds_manager.get(user_id, id), |
| 114 | + ) |
| 115 | + ) |
| 116 | + |
69 | 117 | return fastapi.Response(status_code=201)
|
| 118 | + |
70 | 119 | except Exception:
|
71 | 120 | logger.exception("Exception occurred whilst adding agent to library")
|
72 | 121 | raise fastapi.HTTPException(
|
|
0 commit comments