Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(builder): promotion/demotion of featured agents (#7932)

Nicholas Tindle79ebc4c13b5d
diff --git a/rnd/autogpt_builder/package.json b/rnd/autogpt_builder/package.json
index f1086be167..77b24c0963 100644
--- a/rnd/autogpt_builder/package.json
+++ b/rnd/autogpt_builder/package.json
@@ -29,6 +29,7 @@
"@radix-ui/react-tooltip": "^1.1.2",
"@supabase/ssr": "^0.4.0",
"@supabase/supabase-js": "^2.45.0",
+ "@tanstack/react-table": "^8.20.5",
"@xyflow/react": "^12.1.0",
"ajv": "^8.17.1",
"class-variance-authority": "^0.7.0",
@@ -47,8 +48,8 @@
"react-icons": "^5.2.1",
"react-markdown": "^9.0.1",
"react-modal": "^3.16.1",
- "recharts": "^2.12.7",
"react-shepherd": "^6.1.1",
+ "recharts": "^2.12.7",
"tailwind-merge": "^2.3.0",
"tailwindcss-animate": "^1.0.7",
"uuid": "^10.0.0",
diff --git a/rnd/autogpt_builder/src/app/admin/marketplace/page.tsx b/rnd/autogpt_builder/src/app/admin/marketplace/page.tsx
index e328dba505..7eb82d7d32 100644
--- a/rnd/autogpt_builder/src/app/admin/marketplace/page.tsx
+++ b/rnd/autogpt_builder/src/app/admin/marketplace/page.tsx
@@ -2,15 +2,18 @@ import { withRoleAccess } from "@/lib/withRoleAccess";
import React from "react";
import { getReviewableAgents } from "@/components/admin/marketplace/actions";
-import AdminMarketplaceCard from "@/components/admin/marketplace/AdminMarketplaceCard";
import AdminMarketplaceAgentList from "@/components/admin/marketplace/AdminMarketplaceAgentList";
+import AdminFeaturedAgentsControl from "@/components/admin/marketplace/AdminFeaturedAgentsControl";
+import { Separator } from "@/components/ui/separator";
async function AdminMarketplace() {
- const agents = await getReviewableAgents();
+ const reviewableAgents = await getReviewableAgents();
+
return (
- <div>
- <h3>Agents to review</h3>
- <AdminMarketplaceAgentList agents={agents.agents} />
- </div>
+ <>
+ <AdminMarketplaceAgentList agents={reviewableAgents.agents} />
+ <Separator className="my-4" />
+ <AdminFeaturedAgentsControl className="mt-4" />
+ </>
);
}
diff --git a/rnd/autogpt_builder/src/app/marketplace/[id]/page.tsx b/rnd/autogpt_builder/src/app/marketplace/[id]/page.tsx
index 84e17d85cb..b9abb47f54 100644
--- a/rnd/autogpt_builder/src/app/marketplace/[id]/page.tsx
+++ b/rnd/autogpt_builder/src/app/marketplace/[id]/page.tsx
@@ -2,7 +2,7 @@ import { Suspense } from "react";
import { notFound } from "next/navigation";
import MarketplaceAPI from "@/lib/marketplace-api";
import { AgentDetailResponse } from "@/lib/marketplace-api";
-import AgentDetailContent from "@/components/AgentDetailContent";
+import AgentDetailContent from "@/components/marketplace/AgentDetailContent";
async function getAgentDetails(id: string): Promise<AgentDetailResponse> {
const apiUrl =
diff --git a/rnd/autogpt_builder/src/components/admin/marketplace/AdminAddFeaturedAgentDialog.tsx b/rnd/autogpt_builder/src/components/admin/marketplace/AdminAddFeaturedAgentDialog.tsx
new file mode 100644
index 0000000000..3fe3ef9e34
--- /dev/null
+++ b/rnd/autogpt_builder/src/components/admin/marketplace/AdminAddFeaturedAgentDialog.tsx
@@ -0,0 +1,149 @@
+"use client";
+
+import {
+ Dialog,
+ DialogContent,
+ DialogClose,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { Button } from "@/components/ui/button";
+import {
+ MultiSelector,
+ MultiSelectorContent,
+ MultiSelectorInput,
+ MultiSelectorItem,
+ MultiSelectorList,
+ MultiSelectorTrigger,
+} from "@/components/ui/multiselect";
+import { Controller, useForm } from "react-hook-form";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { useState } from "react";
+import { addFeaturedAgent } from "./actions";
+import { Agent } from "@/lib/marketplace-api/types";
+
+type FormData = {
+ agent: string;
+ categories: string[];
+};
+
+export const AdminAddFeaturedAgentDialog = ({
+ categories,
+ agents,
+}: {
+ categories: string[];
+ agents: Agent[];
+}) => {
+ const [selectedAgent, setSelectedAgent] = useState<string>("");
+ const [selectedCategories, setSelectedCategories] = useState<string[]>([]);
+
+ const {
+ control,
+ handleSubmit,
+ watch,
+ setValue,
+ formState: { errors },
+ } = useForm<FormData>({
+ defaultValues: {
+ agent: "",
+ categories: [],
+ },
+ });
+
+ return (
+ <Dialog>
+ <DialogTrigger asChild>
+ <Button variant="outline" size="sm">
+ Add Featured Agent
+ </Button>
+ </DialogTrigger>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Add Featured Agent</DialogTitle>
+ </DialogHeader>
+ <div className="flex flex-col gap-4">
+ <Controller
+ name="agent"
+ control={control}
+ rules={{ required: true }}
+ render={({ field }) => (
+ <div>
+ <label htmlFor={field.name}>Agent</label>
+ <Select
+ onValueChange={(value) => {
+ field.onChange(value);
+ setSelectedAgent(value);
+ }}
+ value={field.value || ""}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Select an agent" />
+ </SelectTrigger>
+ <SelectContent>
+ {/* Populate with agents */}
+ {agents.map((agent) => (
+ <SelectItem key={agent.id} value={agent.id}>
+ {agent.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ )}
+ />
+ <Controller
+ name="categories"
+ control={control}
+ render={({ field }) => (
+ <MultiSelector
+ values={field.value || []}
+ onValuesChange={(values) => {
+ field.onChange(values);
+ setSelectedCategories(values);
+ }}
+ >
+ <MultiSelectorTrigger>
+ <MultiSelectorInput placeholder="Select categories" />
+ </MultiSelectorTrigger>
+ <MultiSelectorContent>
+ <MultiSelectorList>
+ {categories.map((category) => (
+ <MultiSelectorItem key={category} value={category}>
+ {category}
+ </MultiSelectorItem>
+ ))}
+ </MultiSelectorList>
+ </MultiSelectorContent>
+ </MultiSelector>
+ )}
+ />
+ </div>
+ <DialogFooter>
+ <DialogClose asChild>
+ <Button variant="outline">Cancel</Button>
+ </DialogClose>
+ <DialogClose asChild>
+ <Button
+ type="submit"
+ onClick={async () => {
+ // Handle adding the featured agent
+ await addFeaturedAgent(selectedAgent, selectedCategories);
+ // close the dialog
+ }}
+ >
+ Add
+ </Button>
+ </DialogClose>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/rnd/autogpt_builder/src/components/admin/marketplace/AdminFeaturedAgentsControl.tsx b/rnd/autogpt_builder/src/components/admin/marketplace/AdminFeaturedAgentsControl.tsx
new file mode 100644
index 0000000000..06331cd9fa
--- /dev/null
+++ b/rnd/autogpt_builder/src/components/admin/marketplace/AdminFeaturedAgentsControl.tsx
@@ -0,0 +1,67 @@
+import { Button } from "@/components/ui/button";
+import {
+ getFeaturedAgents,
+ removeFeaturedAgent,
+ getCategories,
+ getNotFeaturedAgents,
+} from "./actions";
+
+import FeaturedAgentsTable from "./FeaturedAgentsTable";
+import { AdminAddFeaturedAgentDialog } from "./AdminAddFeaturedAgentDialog";
+import { revalidatePath } from "next/cache";
+
+export default async function AdminFeaturedAgentsControl({
+ className,
+}: {
+ className?: string;
+}) {
+ // add featured agent button
+ // modal to select agent?
+ // modal to select categories?
+ // table of featured agents
+ // in table
+ // remove featured agent button
+ // edit featured agent categories button
+ // table footer
+ // Next page button
+ // Previous page button
+ // Page number input
+ // Page size input
+ // Total pages input
+ // Go to page button
+
+ const page = 1;
+ const pageSize = 10;
+
+ const agents = await getFeaturedAgents(page, pageSize);
+
+ const categories = await getCategories();
+
+ const notFeaturedAgents = await getNotFeaturedAgents();
+
+ return (
+ <div className={`flex flex-col gap-4 ${className}`}>
+ <div className="mb-4 flex justify-between">
+ <h3 className="text-lg font-semibold">Featured Agent Controls</h3>
+ <AdminAddFeaturedAgentDialog
+ categories={categories.unique_categories}
+ agents={notFeaturedAgents.agents}
+ />
+ </div>
+ <FeaturedAgentsTable
+ agents={agents.agents}
+ globalActions={[
+ {
+ component: <Button>Remove</Button>,
+ action: async (rows) => {
+ "use server";
+ const all = rows.map((row) => removeFeaturedAgent(row.id));
+ await Promise.all(all);
+ revalidatePath("/marketplace");
+ },
+ },
+ ]}
+ />
+ </div>
+ );
+}
diff --git a/rnd/autogpt_builder/src/components/admin/marketplace/AdminMarketplaceAgentList.tsx b/rnd/autogpt_builder/src/components/admin/marketplace/AdminMarketplaceAgentList.tsx
index d3fe147a9e..cc6c751457 100644
--- a/rnd/autogpt_builder/src/components/admin/marketplace/AdminMarketplaceAgentList.tsx
+++ b/rnd/autogpt_builder/src/components/admin/marketplace/AdminMarketplaceAgentList.tsx
@@ -4,23 +4,33 @@ import { ClipboardX } from "lucide-react";
export default function AdminMarketplaceAgentList({
agents,
+ className,
}: {
agents: Agent[];
+ className?: string;
}) {
if (agents.length === 0) {
return (
- <div className="flex flex-col items-center justify-center py-12 text-gray-500">
- <ClipboardX size={48} />
- <p className="mt-4 text-lg font-semibold">No agents to review</p>
+ <div className={className}>
+ <h3 className="text-lg font-semibold">Agents to review</h3>
+ <div className="flex flex-col items-center justify-center py-12 text-gray-500">
+ <ClipboardX size={48} />
+ <p className="mt-4 text-lg font-semibold">No agents to review</p>
+ </div>
</div>
);
}
return (
- <div>
- {agents.map((agent) => (
- <AdminMarketplaceCard agent={agent} key={agent.id} />
- ))}
+ <div className={`flex flex-col gap-4 ${className}`}>
+ <div>
+ <h3 className="text-lg font-semibold">Agents to review</h3>
+ </div>
+ <div className="flex flex-col gap-4">
+ {agents.map((agent) => (
+ <AdminMarketplaceCard agent={agent} key={agent.id} />
+ ))}
+ </div>
</div>
);
}
diff --git a/rnd/autogpt_builder/src/components/admin/marketplace/FeaturedAgentsTable.tsx b/rnd/autogpt_builder/src/components/admin/marketplace/FeaturedAgentsTable.tsx
new file mode 100644
index 0000000000..6fd31301aa
--- /dev/null
+++ b/rnd/autogpt_builder/src/components/admin/marketplace/FeaturedAgentsTable.tsx
@@ -0,0 +1,114 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
+import { DataTable } from "@/components/ui/data-table";
+import { Agent } from "@/lib/marketplace-api";
+import { ColumnDef } from "@tanstack/react-table";
+import { ArrowUpDown } from "lucide-react";
+import { removeFeaturedAgent } from "./actions";
+import { GlobalActions } from "@/components/ui/data-table";
+
+export const columns: ColumnDef<Agent>[] = [
+ {
+ id: "select",
+ header: ({ table }) => (
+ <Checkbox
+ checked={
+ table.getIsAllPageRowsSelected() ||
+ (table.getIsSomePageRowsSelected() && "indeterminate")
+ }
+ onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
+ aria-label="Select all"
+ />
+ ),
+ cell: ({ row }) => (
+ <Checkbox
+ checked={row.getIsSelected()}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ aria-label="Select row"
+ />
+ ),
+ },
+ {
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
+ >
+ Name
+ <ArrowUpDown className="ml-2 h-4 w-4" />
+ </Button>
+ );
+ },
+ accessorKey: "name",
+ },
+ {
+ header: "Description",
+ accessorKey: "description",
+ },
+ {
+ header: "Categories",
+ accessorKey: "categories",
+ },
+ {
+ header: "Keywords",
+ accessorKey: "keywords",
+ },
+ {
+ header: "Downloads",
+ accessorKey: "downloads",
+ },
+ {
+ header: "Author",
+ accessorKey: "author",
+ },
+ {
+ header: "Version",
+ accessorKey: "version",
+ },
+ {
+ header: "actions",
+ cell: ({ row }) => {
+ const handleRemove = async () => {
+ await removeFeaturedAgentWithId();
+ };
+ // const handleEdit = async () => {
+ // console.log("edit");
+ // };
+ const removeFeaturedAgentWithId = removeFeaturedAgent.bind(
+ null,
+ row.original.id,
+ );
+ return (
+ <div className="flex justify-end gap-2">
+ <Button variant="outline" size="sm" onClick={handleRemove}>
+ Remove
+ </Button>
+ {/* <Button variant="outline" size="sm" onClick={handleEdit}>
+ Edit
+ </Button> */}
+ </div>
+ );
+ },
+ },
+];
+
+export default function FeaturedAgentsTable({
+ agents,
+ globalActions,
+}: {
+ agents: Agent[];
+ globalActions: GlobalActions<Agent>[];
+}) {
+ return (
+ <DataTable
+ columns={columns}
+ data={agents}
+ filterPlaceholder="Search agents..."
+ filterColumn="name"
+ globalActions={globalActions}
+ />
+ );
+}
diff --git a/rnd/autogpt_builder/src/components/admin/marketplace/actions.ts b/rnd/autogpt_builder/src/components/admin/marketplace/actions.ts
index c67313d36d..88c3c2a88a 100644
--- a/rnd/autogpt_builder/src/components/admin/marketplace/actions.ts
+++ b/rnd/autogpt_builder/src/components/admin/marketplace/actions.ts
@@ -1,5 +1,7 @@
"use server";
+import AutoGPTServerAPI from "@/lib/autogpt-server-api";
import MarketplaceAPI from "@/lib/marketplace-api";
+import { revalidatePath } from "next/cache";
export async function approveAgent(
agentId: string,
@@ -9,6 +11,7 @@ export async function approveAgent(
const api = new MarketplaceAPI();
await api.approveAgentSubmission(agentId, version, comment);
console.debug(`Approving agent ${agentId}`);
+ revalidatePath("/marketplace");
}
export async function rejectAgent(
@@ -19,9 +22,64 @@ export async function rejectAgent(
const api = new MarketplaceAPI();
await api.rejectAgentSubmission(agentId, version, comment);
console.debug(`Rejecting agent ${agentId}`);
+ revalidatePath("/marketplace");
}
export async function getReviewableAgents() {
const api = new MarketplaceAPI();
return api.getAgentSubmissions();
}
+
+export async function getFeaturedAgents(
+ page: number = 1,
+ pageSize: number = 10,
+) {
+ const api = new MarketplaceAPI();
+ const featured = await api.getFeaturedAgents(page, pageSize);
+ console.debug(`Getting featured agents ${featured.agents.length}`);
+ return featured;
+}
+
+export async function getFeaturedAgent(agentId: string) {
+ const api = new MarketplaceAPI();
+ const featured = await api.getFeaturedAgent(agentId);
+ console.debug(`Getting featured agent ${featured.agentId}`);
+ return featured;
+}
+
+export async function addFeaturedAgent(
+ agentId: string,
+ categories: string[] = ["featured"],
+) {
+ const api = new MarketplaceAPI();
+ await api.addFeaturedAgent(agentId, categories);
+ console.debug(`Adding featured agent ${agentId}`);
+ revalidatePath("/marketplace");
+}
+
+export async function removeFeaturedAgent(
+ agentId: string,
+ categories: string[] = ["featured"],
+) {
+ const api = new MarketplaceAPI();
+ await api.removeFeaturedAgent(agentId, categories);
+ console.debug(`Removing featured agent ${agentId}`);
+ revalidatePath("/marketplace");
+}
+
+export async function getCategories() {
+ const api = new MarketplaceAPI();
+ const categories = await api.getCategories();
+ console.debug(`Getting categories ${categories.unique_categories.length}`);
+ return categories;
+}
+
+export async function getNotFeaturedAgents(
+ page: number = 1,
+ pageSize: number = 100,
+) {
+ const api = new MarketplaceAPI();
+ const agents = await api.getNotFeaturedAgents(page, pageSize);
+ console.debug(`Getting not featured agents ${agents.agents.length}`);
+ return agents;
+}
diff --git a/rnd/autogpt_builder/src/components/AgentDetailContent.tsx b/rnd/autogpt_builder/src/components/marketplace/AgentDetailContent.tsx
similarity index 100%
rename from rnd/autogpt_builder/src/components/AgentDetailContent.tsx
rename to rnd/autogpt_builder/src/components/marketplace/AgentDetailContent.tsx
diff --git a/rnd/autogpt_builder/src/components/ui/data-table.tsx b/rnd/autogpt_builder/src/components/ui/data-table.tsx
new file mode 100644
index 0000000000..17f0a8f9f7
--- /dev/null
+++ b/rnd/autogpt_builder/src/components/ui/data-table.tsx
@@ -0,0 +1,209 @@
+"use client";
+
+import {
+ ColumnDef,
+ ColumnFiltersState,
+ SortingState,
+ VisibilityState,
+ flexRender,
+ getCoreRowModel,
+ useReactTable,
+ getPaginationRowModel,
+ getSortedRowModel,
+ getFilteredRowModel,
+} from "@tanstack/react-table";
+import {
+ TableHeader,
+ TableRow,
+ TableHead,
+ TableBody,
+ TableCell,
+ Table,
+} from "@/components/ui/table";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Input } from "@/components/ui/input";
+import { cloneElement, Fragment, useState } from "react";
+
+export interface GlobalActions<TData> {
+ component: React.ReactElement;
+ action: (rows: TData[]) => Promise<void>;
+}
+
+interface DataTableProps<TData, TValue> {
+ columns: ColumnDef<TData, TValue>[];
+ data: TData[];
+ filterPlaceholder: string;
+ filterColumn?: string;
+ globalActions?: GlobalActions<TData>[];
+}
+
+export function DataTable<TData, TValue>({
+ columns,
+ data,
+ filterPlaceholder = "Filter...",
+ filterColumn,
+ globalActions = [],
+}: DataTableProps<TData, TValue>) {
+ const [sorting, setSorting] = useState<SortingState>([]);
+ const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
+ const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
+ const [rowSelection, setRowSelection] = useState({});
+
+ const table = useReactTable({
+ data,
+ columns,
+ getCoreRowModel: getCoreRowModel(),
+ getPaginationRowModel: getPaginationRowModel(),
+ getSortedRowModel: getSortedRowModel(),
+ getFilteredRowModel: getFilteredRowModel(),
+ onSortingChange: setSorting,
+ onColumnFiltersChange: setColumnFilters,
+ onColumnVisibilityChange: setColumnVisibility,
+ onRowSelectionChange: setRowSelection,
+ state: {
+ sorting,
+ columnFilters,
+ columnVisibility,
+ rowSelection,
+ },
+ });
+
+ return (
+ <div>
+ <div className="flex items-center gap-2 py-4">
+ {filterColumn && (
+ <Input
+ placeholder={filterPlaceholder}
+ value={
+ (table.getColumn(filterColumn)?.getFilterValue() as string) ?? ""
+ }
+ onChange={(event) =>
+ table.getColumn(filterColumn)?.setFilterValue(event.target.value)
+ }
+ className="max-w-sm"
+ />
+ )}
+
+ {globalActions &&
+ globalActions.map((action, index) => {
+ return (
+ <Fragment key={index}>
+ <div className="flex items-center">
+ {cloneElement(action.component, {
+ onClick: () => {
+ const filteredSelectedRows = table
+ .getFilteredSelectedRowModel()
+ .rows.map((row) => row.original);
+ action.action(filteredSelectedRows);
+ },
+ })}
+ </div>
+ </Fragment>
+ );
+ })}
+
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline" className="ml-auto">
+ Columns
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {table
+ .getAllColumns()
+ .filter((column) => column.getCanHide())
+ .map((column) => {
+ return (
+ <DropdownMenuCheckboxItem
+ key={column.id}
+ className="capitalize"
+ checked={column.getIsVisible()}
+ onCheckedChange={(value) =>
+ column.toggleVisibility(!!value)
+ }
+ >
+ {column.id}
+ </DropdownMenuCheckboxItem>
+ );
+ })}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+
+ <div className="rounded-md border">
+ <Table>
+ <TableHeader>
+ {table.getHeaderGroups().map((headerGroup) => (
+ <TableRow key={headerGroup.id}>
+ {headerGroup.headers.map((header) => {
+ return (
+ <TableHead key={header.id}>
+ {header.isPlaceholder
+ ? null
+ : flexRender(
+ header.column.columnDef.header,
+ header.getContext(),
+ )}
+ </TableHead>
+ );
+ })}
+ </TableRow>
+ ))}
+ </TableHeader>
+ <TableBody>
+ {table.getRowModel().rows?.length ? (
+ table.getRowModel().rows.map((row) => (
+ <TableRow
+ key={row.id}
+ data-state={row.getIsSelected() && "selected"}
+ >
+ {row.getVisibleCells().map((cell) => (
+ <TableCell key={cell.id}>
+ {flexRender(
+ cell.column.columnDef.cell,
+ cell.getContext(),
+ )}
+ </TableCell>
+ ))}
+ </TableRow>
+ ))
+ ) : (
+ <TableRow>
+ <TableCell
+ colSpan={columns.length}
+ className="h-24 text-center"
+ >
+ No results.
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ </Table>
+ </div>
+ <div className="flex items-center justify-end space-x-2 py-4">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => table.previousPage()}
+ disabled={!table.getCanPreviousPage()}
+ >
+ Previous
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => table.nextPage()}
+ disabled={!table.getCanNextPage()}
+ >
+ Next
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/rnd/autogpt_builder/src/lib/marketplace-api/client.ts b/rnd/autogpt_builder/src/lib/marketplace-api/client.ts
index 263596b00e..9cc62c39b5 100644
--- a/rnd/autogpt_builder/src/lib/marketplace-api/client.ts
+++ b/rnd/autogpt_builder/src/lib/marketplace-api/client.ts
@@ -6,6 +6,8 @@ import {
AgentListResponse,
AgentDetailResponse,
AgentWithRank,
+ FeaturedAgentResponse,
+ UniqueCategoriesResponse,
} from "./types";
export default class MarketplaceAPI {
@@ -155,6 +157,42 @@ export default class MarketplaceAPI {
});
}
+ async addFeaturedAgent(
+ agentId: string,
+ categories: string[],
+ ): Promise<FeaturedAgentResponse> {
+ const response = await this._post(`/admin/agent/featured/${agentId}`, {
+ categories: categories,
+ });
+ return response;
+ }
+
+ async removeFeaturedAgent(
+ agentId: string,
+ categories: string[],
+ ): Promise<FeaturedAgentResponse> {
+ return this._delete(`/admin/agent/featured/${agentId}`, {
+ categories: categories,
+ });
+ }
+
+ async getFeaturedAgent(agentId: string): Promise<FeaturedAgentResponse> {
+ return this._get(`/admin/agent/featured/${agentId}`);
+ }
+
+ async getNotFeaturedAgents(
+ page: number = 1,
+ pageSize: number = 10,
+ ): Promise<AgentListResponse> {
+ return this._get(
+ `/admin/agent/not-featured?page=${page}&page_size=${pageSize}`,
+ );
+ }
+
+ async getCategories(): Promise<UniqueCategoriesResponse> {
+ return this._get("/admin/categories");
+ }
+
private async _get(path: string) {
return this._request("GET", path);
}
@@ -163,6 +201,10 @@ export default class MarketplaceAPI {
return this._request("POST", path, payload);
}
+ private async _delete(path: string, payload: { [key: string]: any }) {
+ return this._request("DELETE", path, payload);
+ }
+
private async _getBlob(path: string): Promise<Blob> {
const response = await fetch(this.baseUrl + path);
if (!response.ok) {
@@ -178,7 +220,7 @@ export default class MarketplaceAPI {
}
private async _request(
- method: "GET" | "POST" | "PUT" | "PATCH",
+ method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE",
path: string,
payload?: { [key: string]: any },
) {
diff --git a/rnd/autogpt_builder/src/lib/marketplace-api/types.ts b/rnd/autogpt_builder/src/lib/marketplace-api/types.ts
index 3ecc250e07..145c973e46 100644
--- a/rnd/autogpt_builder/src/lib/marketplace-api/types.ts
+++ b/rnd/autogpt_builder/src/lib/marketplace-api/types.ts
@@ -43,6 +43,22 @@ export type AgentList = {
total_pages: number;
};
+export type FeaturedAgentResponse = {
+ agentId: string;
+ featuredCategories: string[];
+ createdAt: string; // ISO8601 datetime string
+ updatedAt: string; // ISO8601 datetime string
+ isActive: boolean;
+};
+
+export type FeaturedAgentsList = {
+ agents: FeaturedAgentResponse[];
+ total_count: number;
+ page: number;
+ page_size: number;
+ total_pages: number;
+};
+
export type AgentDetail = Agent & {
graph: Record<string, any>;
};
@@ -56,3 +72,7 @@ export type AgentListResponse = AgentList;
export type AgentDetailResponse = AgentDetail;
export type AgentResponse = Agent;
+
+export type UniqueCategoriesResponse = {
+ unique_categories: string[];
+};
diff --git a/rnd/autogpt_builder/yarn.lock b/rnd/autogpt_builder/yarn.lock
index 8a01dbeb43..9d301db3a8 100644
--- a/rnd/autogpt_builder/yarn.lock
+++ b/rnd/autogpt_builder/yarn.lock
@@ -883,6 +883,18 @@
"@swc/counter" "^0.1.3"
tslib "^2.4.0"
+"@tanstack/react-table@^8.20.5":
+ version "8.20.5"
+ resolved "https://registry.yarnpkg.com/@tanstack/react-table/-/react-table-8.20.5.tgz#19987d101e1ea25ef5406dce4352cab3932449d8"
+ integrity sha512-WEHopKw3znbUZ61s9i0+i9g8drmDo6asTWbrQh8Us63DAk/M0FkmIqERew6P71HI75ksZ2Pxyuf4vvKh9rAkiA==
+ dependencies:
+ "@tanstack/table-core" "8.20.5"
+
+"@tanstack/[email protected]":
+ version "8.20.5"
+ resolved "https://registry.yarnpkg.com/@tanstack/table-core/-/table-core-8.20.5.tgz#3974f0b090bed11243d4107283824167a395cf1d"
+ integrity sha512-P9dF7XbibHph2PFRz8gfBKEXEY/HJPOhym8CHmjF8y3q5mWpKx9xtZapXQUWCgkqvsK0R46Azuz+VaxD4Xl+Tg==
+
"@types/d3-array@^3.0.3":
version "3.2.1"
resolved "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.1.tgz"
diff --git a/rnd/market/market/app.py b/rnd/market/market/app.py
index 54cdd0802e..0d8a7ba621 100644
--- a/rnd/market/market/app.py
+++ b/rnd/market/market/app.py
@@ -65,7 +65,7 @@ app.add_middleware(
"http://localhost:3000",
"http://127.0.0.1:3000",
"http://127.0.0.1:3000",
- "https://dev-builder.agpt.co"
+ "https://dev-builder.agpt.co",
],
allow_credentials=True,
allow_methods=["*"],
diff --git a/rnd/market/market/db.py b/rnd/market/market/db.py
index 6302a46653..6ca92722ff 100644
--- a/rnd/market/market/db.py
+++ b/rnd/market/market/db.py
@@ -403,7 +403,7 @@ async def get_top_agents_by_downloads(
async def set_agent_featured(
agent_id: str, is_active: bool = True, featured_categories: list[str] = ["featured"]
-):
+) -> prisma.models.FeaturedAgent:
"""Set an agent as featured in the database.
Args:
@@ -418,7 +418,7 @@ async def set_agent_featured(
if not agent:
raise AgentQueryError(f"Agent with ID {agent_id} not found.")
- await prisma.models.FeaturedAgent.prisma().upsert(
+ featured = await prisma.models.FeaturedAgent.prisma().upsert(
where={"agentId": agent_id},
data={
"update": {
@@ -432,6 +432,7 @@ async def set_agent_featured(
},
},
)
+ return featured
except prisma.errors.PrismaError as e:
raise AgentQueryError(f"Database query failed: {str(e)}")
@@ -553,3 +554,90 @@ async def add_featured_category(
raise AgentQueryError(f"Database query failed: {str(e)}")
except Exception as e:
raise AgentQueryError(f"Unexpected error occurred: {str(e)}")
+
+
+async def get_agent_featured(agent_id: str) -> prisma.models.FeaturedAgent | None:
+ """Retrieve an agent's featured categories from the database.
+
+ Args:
+ agent_id (str): The ID of the agent.
+
+ Returns:
+ FeaturedAgentResponse: The list of featured agents.
+ """
+ try:
+ featured_agent = await prisma.models.FeaturedAgent.prisma().find_unique(
+ where={"agentId": agent_id},
+ )
+ return featured_agent
+ except prisma.errors.PrismaError as e:
+ raise AgentQueryError(f"Database query failed: {str(e)}")
+ except Exception as e:
+ raise AgentQueryError(f"Unexpected error occurred: {str(e)}")
+
+
+async def get_not_featured_agents(
+ page: int = 1, page_size: int = 10
+) -> typing.List[prisma.models.Agents]:
+ """
+ Retrieve a list of not featured agents from the database.
+ """
+ try:
+ agents = await prisma.client.get_client().query_raw(
+ query=f"""
+ SELECT
+ "Agents".id,
+ "Agents"."createdAt",
+ "Agents"."updatedAt",
+ "Agents".version,
+ "Agents".name,
+ LEFT("Agents".description, 500) AS description,
+ "Agents".author,
+ "Agents".keywords,
+ "Agents".categories,
+ "Agents".graph,
+ "Agents"."submissionStatus",
+ "Agents"."submissionDate",
+ "Agents".search::text AS search
+ FROM "Agents"
+ LEFT JOIN "FeaturedAgent" ON "Agents"."id" = "FeaturedAgent"."agentId"
+ WHERE ("FeaturedAgent"."agentId" IS NULL OR "FeaturedAgent"."featuredCategories" = '{{}}')
+ AND "Agents"."submissionStatus" = 'APPROVED'
+ ORDER BY "Agents"."createdAt" DESC
+ LIMIT {page_size} OFFSET {page_size * (page - 1)}
+ """,
+ model=prisma.models.Agents,
+ )
+ return agents
+ except prisma.errors.PrismaError as e:
+ raise AgentQueryError(f"Database query failed: {str(e)}")
+ except Exception as e:
+ raise AgentQueryError(f"Unexpected error occurred: {str(e)}")
+
+
+async def get_all_categories() -> market.model.CategoriesResponse:
+ """
+ Retrieve all unique categories from the database.
+
+ Returns:
+ CategoriesResponse: A list of unique categories.
+ """
+ try:
+ categories = await prisma.client.get_client().query_first(
+ query="""
+SELECT ARRAY_AGG(DISTINCT category ORDER BY category) AS unique_categories
+FROM (
+ SELECT UNNEST(categories) AS category
+ FROM "Agents"
+) subquery;
+""",
+ model=market.model.CategoriesResponse,
+ )
+ if not categories:
+ raise AgentQueryError("No categories found")
+
+ return categories
+ except prisma.errors.PrismaError as e:
+ raise AgentQueryError(f"Database query failed: {str(e)}")
+ except Exception as e:
+ raise AgentQueryError(f"Unexpected error occurred: {str(e)}")
diff --git a/rnd/market/market/model.py b/rnd/market/market/model.py
index 0ee1126e7d..864b177878 100644
--- a/rnd/market/market/model.py
+++ b/rnd/market/market/model.py
@@ -95,3 +95,26 @@ class AgentDetailResponse(pydantic.BaseModel):
createdAt: datetime.datetime
updatedAt: datetime.datetime
graph: dict[str, typing.Any]
+
+
+class FeaturedAgentResponse(pydantic.BaseModel):
+ """
+ Represents the response data for an agent detail.
+ """
+
+ agentId: str
+ featuredCategories: list[str]
+ createdAt: datetime.datetime
+ updatedAt: datetime.datetime
+ isActive: bool
+
+
+class CategoriesResponse(pydantic.BaseModel):
+ """
+ Represents the response data for a list of categories.
+
+ Attributes:
+ unique_categories (list[str]): The list of unique categories.
+ """
+
+ unique_categories: list[str]
diff --git a/rnd/market/market/routes/admin.py b/rnd/market/market/routes/admin.py
index ae0c51dbd7..19ebe0f3b1 100644
--- a/rnd/market/market/routes/admin.py
+++ b/rnd/market/market/routes/admin.py
@@ -46,19 +46,44 @@ async def create_agent_entry(
@router.post("/agent/featured/{agent_id}")
async def set_agent_featured(
agent_id: str,
- category: list[str] = ["featured"],
+ categories: list[str] = fastapi.Query(
+ default=["featured"],
+ description="The categories to set the agent as featured in",
+ ),
user: autogpt_libs.auth.User = fastapi.Depends(
autogpt_libs.auth.requires_admin_user
),
-):
+) -> market.model.FeaturedAgentResponse:
"""
A basic endpoint to set an agent as featured in the database.
"""
try:
- await market.db.set_agent_featured(
- agent_id, is_active=True, featured_categories=category
+ agent = await market.db.set_agent_featured(
+ agent_id, is_active=True, featured_categories=categories
)
- return fastapi.responses.Response(status_code=200)
+ return market.model.FeaturedAgentResponse(**agent.model_dump())
+ except market.db.AgentQueryError as e:
+ raise fastapi.HTTPException(status_code=500, detail=str(e))
+ except Exception as e:
+ raise fastapi.HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/agent/featured/{agent_id}")
+async def get_agent_featured(
+ agent_id: str,
+ user: autogpt_libs.auth.User = fastapi.Depends(
+ autogpt_libs.auth.requires_admin_user
+ ),
+) -> market.model.FeaturedAgentResponse | None:
+ """
+ A basic endpoint to get an agent as featured in the database.
+ """
+ try:
+ agent = await market.db.get_agent_featured(agent_id)
+ if agent:
+ return market.model.FeaturedAgentResponse(**agent.model_dump())
+ else:
+ return None
except market.db.AgentQueryError as e:
raise fastapi.HTTPException(status_code=500, detail=str(e))
except Exception as e:
@@ -72,14 +97,46 @@ async def unset_agent_featured(
user: autogpt_libs.auth.User = fastapi.Depends(
autogpt_libs.auth.requires_admin_user
),
-):
+) -> market.model.FeaturedAgentResponse | None:
"""
A basic endpoint to unset an agent as featured in the database.
"""
try:
+ featured = await market.db.remove_featured_category(agent_id, category=category)
+ if featured:
+ return market.model.FeaturedAgentResponse(**featured.model_dump())
+ else:
+ return None
+ except market.db.AgentQueryError as e:
+ raise fastapi.HTTPException(status_code=500, detail=str(e))
+ except Exception as e:
+ raise fastapi.HTTPException(status_code=500, detail=str(e))
+
- await market.db.remove_featured_category(agent_id, category=category)
- return fastapi.responses.Response(status_code=200)
[email protected]("/agent/not-featured")
+async def get_not_featured_agents(
+ page: int = fastapi.Query(1, ge=1, description="Page number"),
+ page_size: int = fastapi.Query(
+ 10, ge=1, le=100, description="Number of items per page"
+ ),
+ user: autogpt_libs.auth.User = fastapi.Depends(
+ autogpt_libs.auth.requires_admin_user
+ ),
+) -> market.model.AgentListResponse:
+ """
+ A basic endpoint to get all not featured agents in the database.
+ """
+ try:
+ agents = await market.db.get_not_featured_agents(page=page, page_size=page_size)
+ return market.model.AgentListResponse(
+ agents=[
+ market.model.AgentResponse(**agent.model_dump()) for agent in agents
+ ],
+ total_count=len(agents),
+ page=page,
+ page_size=page_size,
+ total_pages=999,
+ )
except market.db.AgentQueryError as e:
raise fastapi.HTTPException(status_code=500, detail=str(e))
except Exception as e:
@@ -177,3 +234,15 @@ async def review_submission(
raise fastapi.HTTPException(status_code=500, detail=str(e))
except Exception as e:
raise fastapi.HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/categories")
+async def get_categories() -> market.model.CategoriesResponse:
+ """
+ A basic endpoint to get all available categories.
+ """
+ try:
+ categories = await market.db.get_all_categories()
+ return categories
+ except Exception as e:
+ raise fastapi.HTTPException(status_code=500, detail=str(e))