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(autogpt_server, autogpt_builder): Add Agent Versioning & Templates functionality (#7376)
Swifty110e093e7b05
diff --git a/rnd/autogpt_builder/src/app/monitor/page.tsx b/rnd/autogpt_builder/src/app/monitor/page.tsxindex 57b899e94e..ff14973f03 100644--- a/rnd/autogpt_builder/src/app/monitor/page.tsx+++ b/rnd/autogpt_builder/src/app/monitor/page.tsx@@ -13,7 +13,16 @@ import {XAxis,YAxis,} from 'recharts';-import { Pencil2Icon } from '@radix-ui/react-icons';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuLabel,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu"+import { ClockIcon, Pencil2Icon } from '@radix-ui/react-icons';import AutoGPTServerAPI, { Flow, NodeExecutionResult } from '@/lib/autogpt_server_api';import { cn, hashString } from '@/lib/utils';import { Badge } from "@/components/ui/badge";@@ -66,8 +75,10 @@ const Monitor = () => {// Fetch flow runapi.getFlowExecutionInfo(flowID, runID).then(execInfo => setFlowRuns(flowRuns => {+ if (execInfo.length == 0) return flowRuns;+const flowRunIndex = flowRuns.findIndex(fr => fr.id == runID);- const flowRun = flowRunFromNodeExecutionResults(flowID, runID, execInfo)+ const flowRun = flowRunFromNodeExecutionResults(execInfo);if (flowRunIndex > -1) {flowRuns.splice(flowRunIndex, 1, flowRun)}@@ -129,6 +140,7 @@ const Monitor = () => {type FlowRun = {id: stringflowID: string+ flowVersion: numberstatus: 'running' | 'waiting' | 'success' | 'failed'startTime: number // unix timestamp (ms)endTime: number // unix timestamp (ms)@@ -139,7 +151,7 @@ type FlowRun = {};function flowRunFromNodeExecutionResults(- flowID: string, runID: string, nodeExecutionResults: NodeExecutionResult[]+ nodeExecutionResults: NodeExecutionResult[]): FlowRun {// Determine overall statuslet status: 'running' | 'waiting' | 'success' | 'failed' = 'success';@@ -173,14 +185,15 @@ function flowRunFromNodeExecutionResults(), 0) / 1000;return {- id: runID,- flowID: flowID,+ id: nodeExecutionResults[0].graph_exec_id,+ flowID: nodeExecutionResults[0].graph_id,+ flowVersion: nodeExecutionResults[0].graph_version,status,startTime,endTime,duration,totalRunTime,- nodeExecutionResults: nodeExecutionResults+ nodeExecutionResults: nodeExecutionResults,};}@@ -328,21 +341,68 @@ const FlowRunStatusBadge: React.FC<{const FlowInfo: React.FC<{flow: Flow;flowRuns: FlowRun[];-}> = ({ flow, flowRuns }) => {+ flowVersion?: number | "all";+}> = ({ flow, flowRuns, flowVersion }) => {+ const api = new AutoGPTServerAPI();++ const [flowVersions, setFlowVersions] = useState<Flow[] | null>(null);+ const [selectedVersion, setSelectedFlowVersion] = useState(flowVersion ?? "all");++ useEffect(() => {+ api.getFlowAllVersions(flow.id).then(result => setFlowVersions(result));+ }, [flow.id]);+return <Card>- <CardHeader className="flex-row items-center justify-between space-y-0 space-x-3">+ <CardHeader className="flex-row justify-between space-y-0 space-x-3"><div>- <CardTitle>{flow.name}</CardTitle>+ <CardTitle>+ {flow.name} <span className="font-light">v{flow.version}</span>+ </CardTitle><p className="mt-2">Agent ID: <code>{flow.id}</code></p></div>- <Link className={buttonVariants({ variant: "outline" })} href={`/build?flowID=${flow.id}`}>- <Pencil2Icon className="mr-2" /> Edit Agent- </Link>+ <div className="flex items-start space-x-2">+ {(flowVersions?.length ?? 0) > 1 &&+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="outline">+ <ClockIcon className="mr-2" />+ {selectedVersion == "all" ? "All versions" : `Version ${selectedVersion}`}+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent className="w-56">+ <DropdownMenuLabel>Choose a version</DropdownMenuLabel>+ <DropdownMenuSeparator />+ <DropdownMenuRadioGroup+ value={String(selectedVersion)}+ onValueChange={choice => setSelectedFlowVersion(+ choice == "all" ? choice : Number(choice)+ )}+ >+ <DropdownMenuRadioItem value="all">All versions</DropdownMenuRadioItem>+ {flowVersions?.map(v =>+ <DropdownMenuRadioItem key={v.version} value={v.version.toString()}>+ Version {v.version}{v.is_active ? " (active)" : ""}+ </DropdownMenuRadioItem>+ )}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>}+ <Link className={buttonVariants({ variant: "outline" })} href={`/build?flowID=${flow.id}`}>+ <Pencil2Icon className="mr-2" /> Edit+ </Link>+ </div></CardHeader><CardContent><FlowRunsStats- flows={[flow]}- flowRuns={flowRuns.filter(r => r.flowID == flow.id)}+ flows={[+ selectedVersion != "all"+ ? flowVersions?.find(v => v.version == selectedVersion)!+ : flow+ ]}+ flowRuns={flowRuns.filter(r =>+ r.flowID == flow.id+ && (selectedVersion == "all" || r.flowVersion == selectedVersion)+ )}/></CardContent></Card>;@@ -359,7 +419,9 @@ const FlowRunInfo: React.FC<{return <Card><CardHeader className="flex-row items-center justify-between space-y-0 space-x-3"><div>- <CardTitle>{flow.name}</CardTitle>+ <CardTitle>+ {flow.name} <span className="font-light">v{flow.version}</span>+ </CardTitle><p className="mt-2">Agent ID: <code>{flow.id}</code></p><p className="mt-1">Run ID: <code>{flowRun.id}</code></p></div>diff --git a/rnd/autogpt_builder/src/components/Flow.tsx b/rnd/autogpt_builder/src/components/Flow.tsxindex 42aac3b7a5..b17ee89b55 100644--- a/rnd/autogpt_builder/src/components/Flow.tsx+++ b/rnd/autogpt_builder/src/components/Flow.tsx@@ -20,6 +20,7 @@ import { ObjectSchema } from '@/lib/types';import { Button } from './ui/button';import { Input } from './ui/input';import { ChevronRight, ChevronLeft } from "lucide-react";+import { deepEquals } from '@/lib/utils';type CustomNodeData = {@@ -74,8 +75,8 @@ const FlowEditor: React.FC<{ flowID?: string; className?: string }> = ({const [edges, setEdges] = useState<Edge[]>([]);const [nodeId, setNodeId] = useState<number>(1);const [availableNodes, setAvailableNodes] = useState<Block[]>([]);- const [agentId, setAgentId] = useState<string | null>(null);const [isSidebarOpen, setIsSidebarOpen] = useState(true);+ const [savedAgent, setSavedAgent] = useState<Flow | null>(null);const [agentDescription, setAgentDescription] = useState<string>('');const [agentName, setAgentName] = useState<string>('');@@ -196,7 +197,9 @@ const FlowEditor: React.FC<{ flowID?: string; className?: string }> = ({};function loadFlow(flow: Flow) {- setAgentId(flow.id);+ setSavedAgent(flow);+ setAgentName(flow.name);+ setAgentDescription(flow.description);setNodes(flow.nodes.map(node => {const block = availableNodes.find(block => block.id === node.block_id)!;@@ -272,102 +275,105 @@ const FlowEditor: React.FC<{ flowID?: string; className?: string }> = ({};const saveAgent = async () => {- try {-- setNodes((nds) =>- nds.map((node) => ({- ...node,- data: {- ...node.data,- status: null,- },- }))- );- await new Promise((resolve) => setTimeout(resolve, 100));- console.log("All nodes before formatting:", nodes);- const blockIdToNodeIdMap = {};-- const formattedNodes = nodes.map(node => {- nodes.forEach(node => {- const key = `${node.data.block_id}_${node.position.x}_${node.position.y}`;- blockIdToNodeIdMap[key] = node.id;- });- const inputDefault = prepareNodeInputData(node, nodes, edges);- const inputNodes = edges- .filter(edge => edge.target === node.id)- .map(edge => ({- name: edge.targetHandle || '',- node_id: edge.source,- }));-- const outputNodes = edges- .filter(edge => edge.source === node.id)- .map(edge => ({- name: edge.sourceHandle || '',- node_id: edge.target,- }));-- return {- id: node.id,- block_id: node.data.block_id,- input_default: inputDefault,- input_nodes: inputNodes,- output_nodes: outputNodes,- metadata: { position: node.position }- };+ setNodes((nds) =>+ nds.map((node) => ({+ ...node,+ data: {+ ...node.data,+ status: undefined,+ },+ }))+ );+ await new Promise((resolve) => setTimeout(resolve, 100));+ console.log("All nodes before formatting:", nodes);+ const blockIdToNodeIdMap = {};++ const formattedNodes = nodes.map(node => {+ nodes.forEach(node => {+ const key = `${node.data.block_id}_${node.position.x}_${node.position.y}`;+ blockIdToNodeIdMap[key] = node.id;});-- const links = edges.map(edge => ({- source_id: edge.source,- sink_id: edge.target,- source_name: edge.sourceHandle || '',- sink_name: edge.targetHandle || ''- }));-- const payload = {- id: agentId || '',- name: agentName || 'Agent Name',- description: agentDescription || 'Agent Description',- nodes: formattedNodes,- links: links // Ensure this field is included+ const inputDefault = prepareNodeInputData(node, nodes, edges);+ const inputNodes = edges+ .filter(edge => edge.target === node.id)+ .map(edge => ({+ name: edge.targetHandle || '',+ node_id: edge.source,+ }));++ const outputNodes = edges+ .filter(edge => edge.source === node.id)+ .map(edge => ({+ name: edge.sourceHandle || '',+ node_id: edge.target,+ }));++ return {+ id: node.id,+ block_id: node.data.block_id,+ input_default: inputDefault,+ input_nodes: inputNodes,+ output_nodes: outputNodes,+ metadata: { position: node.position }};+ });- const createData = await api.createFlow(payload);- const newAgentId = createData.id;- setAgentId(newAgentId);- console.log('Response from the API:', JSON.stringify(createData, null, 2));-- // Update the node IDs in the frontend- const updatedNodes = createData.nodes.map(backendNode => {- const key = `${backendNode.block_id}_${backendNode.metadata.position.x}_${backendNode.metadata.position.y}`;- const frontendNodeId = blockIdToNodeIdMap[key];- const frontendNode = nodes.find(node => node.id === frontendNodeId);-- return frontendNode- ? {- ...frontendNode,- position: backendNode.metadata.position,- data: {- ...frontendNode.data,- backend_id: backendNode.id,- },- }- : null;- }).filter(node => node !== null);+ const links = edges.map(edge => ({+ source_id: edge.source,+ sink_id: edge.target,+ source_name: edge.sourceHandle || '',+ sink_name: edge.targetHandle || ''+ }));- setNodes(updatedNodes);+ const payload = {+ id: savedAgent?.id!,+ name: agentName || 'Agent Name',+ description: agentDescription || 'Agent Description',+ nodes: formattedNodes,+ links: links // Ensure this field is included+ };- return newAgentId;- } catch (error) {- console.error('Error running agent:', error);+ if (savedAgent && deepEquals(payload, savedAgent)) {+ console.debug("No need to save: Graph is the same as version on server");+ return;+ } else {+ console.debug("Saving new Graph version; old vs new:", savedAgent, payload);}++ const newSavedAgent = savedAgent+ ? await api.updateFlow(savedAgent.id, payload)+ : await api.createFlow(payload);+ console.debug('Response from the API:', newSavedAgent);+ setSavedAgent(newSavedAgent);++ // Update the node IDs in the frontend+ const updatedNodes = newSavedAgent.nodes.map(backendNode => {+ const key = `${backendNode.block_id}_${backendNode.metadata.position.x}_${backendNode.metadata.position.y}`;+ const frontendNodeId = blockIdToNodeIdMap[key];+ const frontendNode = nodes.find(node => node.id === frontendNodeId);++ return frontendNode+ ? {+ ...frontendNode,+ position: backendNode.metadata.position,+ data: {+ ...frontendNode.data,+ backend_id: backendNode.id,+ },+ }+ : null;+ }).filter(node => node !== null);++ setNodes(updatedNodes);++ return newSavedAgent.id;};const runAgent = async () => {try {const newAgentId = await saveAgent();if (!newAgentId) {- console.error('Error saving agent');+ console.error('Error saving agent; aborting run');return;}diff --git a/rnd/autogpt_builder/src/components/ui/dropdown-menu.tsx b/rnd/autogpt_builder/src/components/ui/dropdown-menu.tsxindex 07370260cb..9972335523 100644--- a/rnd/autogpt_builder/src/components/ui/dropdown-menu.tsx+++ b/rnd/autogpt_builder/src/components/ui/dropdown-menu.tsx@@ -128,7 +128,7 @@ const DropdownMenuRadioItem = React.forwardRef<<DropdownMenuPrimitive.RadioItemref={ref}className={cn(- "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-neutral-100 focus:text-neutral-900 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 dark:focus:bg-neutral-800 dark:focus:text-neutral-50",+ "relative flex cursor-pointer select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-neutral-100 focus:text-neutral-900 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 dark:focus:bg-neutral-800 dark:focus:text-neutral-50",className)}{...props}diff --git a/rnd/autogpt_builder/src/lib/autogpt_server_api.ts b/rnd/autogpt_builder/src/lib/autogpt_server_api.tsindex b4083e41d7..5a9326a8ec 100644--- a/rnd/autogpt_builder/src/lib/autogpt_server_api.ts+++ b/rnd/autogpt_builder/src/lib/autogpt_server_api.ts@@ -36,8 +36,11 @@ export default class AutoGPTServerAPI {}}- async getFlow(id: string): Promise<Flow> {- const path = `/graphs/${id}`;+ async getFlow(id: string, version?: number): Promise<Flow> {+ let path = `/graphs/${id}`;+ if (version !== undefined) {+ path += `?version=${version}`;+ }try {const response = await fetch(this.baseUrl + path);if (!response.ok) {@@ -51,15 +54,47 @@ export default class AutoGPTServerAPI {}}- async createFlow(flowCreateBody: FlowCreateBody): Promise<Flow> {- console.debug("POST /graphs payload:", flowCreateBody);+ async getFlowAllVersions(id: string): Promise<Flow[]> {+ let path = `/graphs/${id}/versions`;+ try {+ const response = await fetch(this.baseUrl + path);+ if (!response.ok) {+ console.warn(`GET ${path} returned non-OK response:`, response);+ throw new Error(`HTTP error ${response.status}!`);+ }+ return await response.json();+ } catch (error) {+ console.error(`Error fetching flow ${id} versions:`, error);+ throw error;+ }+ }++ async createFlow(flowCreateBody: FlowCreatable): Promise<Flow>;+ async createFlow(fromTemplateID: string, templateVersion: number): Promise<Flow>;+ async createFlow(+ flowOrTemplateID: FlowCreatable | string, templateVersion?: number+ ): Promise<Flow> {+ let requestBody: FlowCreateRequestBody;+ if (typeof(flowOrTemplateID) == "string") {+ if (templateVersion == undefined) {+ throw new Error("templateVersion not specified")+ }+ requestBody = {+ template_id: flowOrTemplateID,+ template_version: templateVersion,+ }+ } else {+ requestBody = { graph: flowOrTemplateID }+ }+ console.debug("POST /graphs payload:", requestBody);+try {const response = await fetch(`${this.baseUrl}/graphs`, {method: 'POST',headers: {'Content-Type': 'application/json',},- body: JSON.stringify(flowCreateBody),+ body: JSON.stringify(requestBody),});const response_data = await response.json();if (!response.ok) {@@ -75,6 +110,59 @@ export default class AutoGPTServerAPI {}}+ async updateFlow(flowID: string, flow: FlowUpdateable): Promise<Flow> {+ const path = `/graphs/${flowID}`;+ console.debug(`PUT ${path} payload:`, flow);++ try {+ const response = await fetch(`${this.baseUrl}${path}`, {+ method: 'PUT',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(flow),+ });+ const response_data = await response.json();+ if (!response.ok) {+ console.warn(+ `PUT ${path} returned non-OK response:`, response_data.detail, response+ );+ throw new Error(`HTTP error ${response.status}! ${response_data.detail}`)+ }+ return response_data;+ } catch (error) {+ console.error("Error updating flow:", error);+ throw error;+ }+ }++ async setFlowActiveVersion(flowID: string, version: number): Promise<Flow> {+ const path = `/graphs/${flowID}/versions/active`;+ const payload: { active_graph_version: number } = { active_graph_version: version };+ console.debug(`PUT ${path} payload:`, payload);++ try {+ const response = await fetch(`${this.baseUrl}${path}`, {+ method: 'PUT',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(payload),+ });+ const response_data = await response.json();+ if (!response.ok) {+ console.warn(+ `PUT ${path} returned non-OK response:`, response_data.detail, response+ );+ throw new Error(`HTTP error ${response.status}! ${response_data.detail}`)+ }+ return response_data;+ } catch (error) {+ console.error("Error updating flow:", error);+ throw error;+ }+ }+async executeFlow(flowId: string, inputData: { [key: string]: any } = {}): Promise<FlowExecuteResponse> {@@ -102,8 +190,11 @@ export default class AutoGPTServerAPI {}}- async listFlowRunIDs(flowId: string): Promise<string[]> {- const path = `/graphs/${flowId}/executions`+ async listFlowRunIDs(flowId: string, flowVersion?: number): Promise<string[]> {+ let path = `/graphs/${flowId}/executions`;+ if (flowVersion !== undefined) {+ path += `?graph_version=${flowVersion}`;+ }try {const response = await fetch(this.baseUrl + path);if (!response.ok) {@@ -152,7 +243,7 @@ export type Block = {export type Node = {id: string;block_id: string;- input_default: Map<string, any>;+ input_default: { [key: string]: any };input_nodes: Array<{ name: string, node_id: string }>;output_nodes: Array<{ name: string, node_id: string }>;metadata: {@@ -163,23 +254,50 @@ export type Node = {/* Mirror of autogpt_server/data/graph.py:Link */export type Link = {+ id: string;source_id: string;sink_id: string;source_name: string;sink_name: string;}-/* Mirror of autogpt_server/data/graph.py:Graph */-export type Flow = {+export type LinkCreatable = Omit<Link, "id"> & {+ id?: string;+}++/* Mirror of autogpt_server/data/graph.py:GraphMeta */+export type FlowMeta = {id: string;+ version: number;+ is_active: boolean;+ is_template: boolean;name: string;description: string;+}++/* Mirror of autogpt_server/data/graph.py:Graph */+export type Flow = FlowMeta & {nodes: Array<Node>;links: Array<Link>;};-export type FlowCreateBody = Flow | {- id?: string;+export type FlowUpdateable = Omit<+ Flow,+ "version" | "is_active" | "is_template" | "links"+> & {+ version?: number;+ is_active?: boolean;+ is_template?: boolean;+ links: Array<LinkCreatable>;+}++export type FlowCreatable = Omit<FlowUpdateable, "id"> & { id?: string }++export type FlowCreateRequestBody = {+ template_id: string;+ template_version: number;+} | {+ graph: FlowCreatable;}/* Derived from autogpt_server/executor/manager.py:ExecutionManager.add_execution */@@ -194,10 +312,12 @@ export type FlowExecuteResponse = {export type NodeExecutionResult = {graph_exec_id: string;node_exec_id: string;+ graph_id: string;+ graph_version: number;node_id: string;status: 'INCOMPLETE' | 'QUEUED' | 'RUNNING' | 'COMPLETED' | 'FAILED';- input_data: Map<string, any>;- output_data: Map<string, any[]>;+ input_data: { [key: string]: any };+ output_data: { [key: string]: Array<any> };add_time: Date;queue_time?: Date;start_time?: Date;diff --git a/rnd/autogpt_builder/src/lib/utils.ts b/rnd/autogpt_builder/src/lib/utils.tsindex 9ca3eac676..0c45fff844 100644--- a/rnd/autogpt_builder/src/lib/utils.ts+++ b/rnd/autogpt_builder/src/lib/utils.ts@@ -16,3 +16,16 @@ export function hashString(str: string): number {}return hash;}++/** Derived from https://stackoverflow.com/a/32922084 */+export function deepEquals(x: any, y: any): boolean {+ const ok = Object.keys, tx = typeof x, ty = typeof y;+ return x && y && tx === ty && (+ tx === 'object'+ ? (+ ok(x).length === ok(y).length &&+ ok(x).every(key => deepEquals(x[key], y[key]))+ )+ : (x === y)+ );+}diff --git a/rnd/autogpt_server/autogpt_server/cli.py b/rnd/autogpt_server/autogpt_server/cli.pyindex 8bb9415725..9126aa72e1 100755--- a/rnd/autogpt_server/autogpt_server/cli.py+++ b/rnd/autogpt_server/autogpt_server/cli.py@@ -215,21 +215,41 @@ Make sure to only comment on a relevant post.# Linkslinks = [- Link(reddit_get_post_node.id, text_formatter_node.id, "post", "named_texts"),- Link(text_formatter_node.id, llm_call_node.id, "output", "prompt"),- Link(llm_call_node.id, text_matcher_node.id, "response", "data"),- Link(llm_call_node.id, text_matcher_node.id, "response_#_is_relevant", "text"),Link(- text_matcher_node.id,- reddit_comment_node.id,- "positive_#_post_id",- "post_id",+ source_id=reddit_get_post_node.id,+ sink_id=text_formatter_node.id,+ source_name="post",+ sink_name="named_texts",),Link(- text_matcher_node.id,- reddit_comment_node.id,- "positive_#_marketing_text",- "comment",+ source_id=text_formatter_node.id,+ sink_id=llm_call_node.id,+ source_name="output",+ sink_name="prompt",+ ),+ Link(+ source_id=llm_call_node.id,+ sink_id=text_matcher_node.id,+ source_name="response",+ sink_name="data",+ ),+ Link(+ source_id=llm_call_node.id,+ sink_id=text_matcher_node.id,+ source_name="response_#_is_relevant",+ sink_name="text",+ ),+ Link(+ source_id=text_matcher_node.id,+ sink_id=reddit_comment_node.id,+ source_name="positive_#_post_id",+ sink_name="post_id",+ ),+ Link(+ source_id=text_matcher_node.id,+ sink_id=reddit_comment_node.id,+ source_name="positive_#_marketing_text",+ sink_name="comment",),]@@ -276,9 +296,24 @@ def populate_db(server_address: str):graph.Node(block_id=PrintingBlock().id),]links = [- graph.Link(nodes[0].id, nodes[2].id, "output", "texts_$_1"),- graph.Link(nodes[1].id, nodes[2].id, "output", "texts_$_2"),- graph.Link(nodes[2].id, nodes[3].id, "output", "text"),+ graph.Link(+ source_id=nodes[0].id,+ sink_id=nodes[2].id,+ source_name="output",+ sink_name="texts_$_1",+ ),+ graph.Link(+ source_id=nodes[1].id,+ sink_id=nodes[2].id,+ source_name="output",+ sink_name="texts_$_2",+ ),+ graph.Link(+ source_id=nodes[2].id,+ sink_id=nodes[3].id,+ source_name="output",+ sink_name="text",+ ),]test_graph = graph.Graph(name="TestGraph",@@ -337,9 +372,24 @@ def graph(server_address: str):graph.Node(block_id=PrintingBlock().id),]links = [- graph.Link(nodes[0].id, nodes[2].id, "output", "texts_$_1"),- graph.Link(nodes[1].id, nodes[2].id, "output", "texts_$_2"),- graph.Link(nodes[2].id, nodes[3].id, "output", "text"),+ graph.Link(+ source_id=nodes[0].id,+ sink_id=nodes[2].id,+ source_name="output",+ sink_name="texts_$_1",+ ),+ graph.Link(+ source_id=nodes[1].id,+ sink_id=nodes[2].id,+ source_name="output",+ sink_name="texts_$_2",+ ),+ graph.Link(+ source_id=nodes[2].id,+ sink_id=nodes[3].id,+ source_name="output",+ sink_name="text",+ ),]test_graph = graph.Graph(name="TestGraph",diff --git a/rnd/autogpt_server/autogpt_server/data/db.py b/rnd/autogpt_server/autogpt_server/data/db.pyindex 17d60187a7..abfb0873d1 100644--- a/rnd/autogpt_server/autogpt_server/data/db.py+++ b/rnd/autogpt_server/autogpt_server/data/db.py@@ -1,6 +1,6 @@from uuid import uuid4from prisma import Prisma-from pydantic import BaseModel+from pydantic import BaseModel, Field, field_validatorprisma = Prisma(auto_register=True)@@ -16,8 +16,9 @@ async def disconnect():class BaseDbModel(BaseModel):- id: str = ""+ id: str = Field(default_factory=lambda: str(uuid4()))- def __init__(self, id: str = "", **data):- data["id"] = id or str(uuid4())- super().__init__(**data)+ @field_validator("id", mode="before")+ def set_graph_id(cls, id: str) -> str:+ # In case an empty ID is submitted+ return id or str(uuid4())diff --git a/rnd/autogpt_server/autogpt_server/data/execution.py b/rnd/autogpt_server/autogpt_server/data/execution.pyindex eeb6cbf8d7..1ee3353892 100644--- a/rnd/autogpt_server/autogpt_server/data/execution.py+++ b/rnd/autogpt_server/autogpt_server/data/execution.py@@ -10,6 +10,7 @@ from prisma.models import (AgentNodeExecution,AgentNodeExecutionInputOutput,)+from prisma.types import AgentGraphExecutionWhereInputfrom pydantic import BaseModelfrom autogpt_server.util import json@@ -52,6 +53,7 @@ class ExecutionQueue:class ExecutionResult(BaseModel):graph_id: str+ graph_version: intgraph_exec_id: strnode_exec_id: strnode_id: str@@ -73,10 +75,11 @@ class ExecutionResult(BaseModel):for data in execution.Output or []:output_data[data.name].append(json.loads(data.data))- node: AgentNode | None = execution.AgentNode-+ graph_execution: AgentGraphExecution | None = execution.AgentGraphExecution+return ExecutionResult(- graph_id=node.agentGraphId if node else "",+ graph_id=graph_execution.agentGraphId if graph_execution else "",+ graph_version=graph_execution.agentGraphVersion if graph_execution else 0,graph_exec_id=execution.agentGraphExecutionId,node_exec_id=execution.id,node_id=execution.agentNodeId,@@ -94,7 +97,7 @@ class ExecutionResult(BaseModel):async def create_graph_execution(- graph_id: str, node_ids: list[str], data: dict[str, Any]+ graph_id: str, graph_version: int, node_ids: list[str], data: dict[str, Any]) -> tuple[str, list[ExecutionResult]]:"""Create a new AgentGraphExecution record.@@ -104,6 +107,7 @@ async def create_graph_execution(result = await AgentGraphExecution.prisma().create(data={"agentGraphId": graph_id,+ "agentGraphVersion": graph_version,"AgentNodeExecutions": {"create": [ # type: ignore{@@ -209,17 +213,18 @@ async def update_execution_status(node_exec_id: str, status: ExecutionStatus) ->raise ValueError(f"Execution {node_exec_id} not found.")-async def list_executions(graph_id: str) -> list[str]:- executions = await AgentGraphExecution.prisma().find_many(- where={"agentGraphId": graph_id},- )+async def list_executions(graph_id: str, graph_version: int | None = None) -> list[str]:+ where: AgentGraphExecutionWhereInput = {"agentGraphId": graph_id}+ if graph_version is not None:+ where["agentGraphVersion"] = graph_version+ executions = await AgentGraphExecution.prisma().find_many(where=where)return [execution.id for execution in executions]async def get_execution_results(graph_exec_id: str) -> list[ExecutionResult]:executions = await AgentNodeExecution.prisma().find_many(where={"agentGraphExecutionId": graph_exec_id},- include={"Input": True, "Output": True},+ include={"Input": True, "Output": True, "AgentGraphExecution": True},order={"addedTime": "asc"},)res = [ExecutionResult.from_db(execution) for execution in executions]@@ -231,7 +236,7 @@ async def get_execution_result() -> ExecutionResult:execution = await AgentNodeExecution.prisma().find_first_or_raise(where={"agentGraphExecutionId": graph_exec_id, "id": node_exec_id},- include={"Input": True, "Output": True, "AgentNode": True},+ include={"Input": True, "Output": True, "AgentGraphExecution": True},order={"addedTime": "asc"},)res = ExecutionResult.from_db(execution)diff --git a/rnd/autogpt_server/autogpt_server/data/graph.py b/rnd/autogpt_server/autogpt_server/data/graph.pyindex 92c5bcdafb..e5ae32cee8 100644--- a/rnd/autogpt_server/autogpt_server/data/graph.py+++ b/rnd/autogpt_server/autogpt_server/data/graph.py@@ -1,31 +1,25 @@import asyncioimport uuid+from typing import Any, Literal-from typing import Any+import prisma.typesfrom prisma.models import AgentGraph, AgentNode, AgentNodeLink-from pydantic import BaseModel, PrivateAttr+from pydantic import PrivateAttrfrom autogpt_server.data.db import BaseDbModelfrom autogpt_server.util import json-class Link(BaseModel):+class Link(BaseDbModel):source_id: strsink_id: strsource_name: strsink_name: str- def __init__(self, source_id: str, sink_id: str, source_name: str, sink_name: str):- super().__init__(- source_id=source_id,- sink_id=sink_id,- source_name=source_name,- sink_name=sink_name,- )-@staticmethoddef from_db(link: AgentNodeLink):return Link(+ id=link.id,source_name=link.sourceName,source_id=link.agentNodeSourceId,sink_name=link.sinkName,@@ -60,16 +54,34 @@ class Node(BaseDbModel):id=node.id,block_id=node.AgentBlock.id,input_default=json.loads(node.constantInput),- metadata=json.loads(node.metadata)+ metadata=json.loads(node.metadata),)obj._input_links = [Link.from_db(link) for link in node.Input or []]obj._output_links = [Link.from_db(link) for link in node.Output or []]return obj-class Graph(BaseDbModel):+class GraphMeta(BaseDbModel):+ version: int = 1+ is_active: bool = True+ is_template: bool = False+name: strdescription: str++ @staticmethod+ def from_db(graph: AgentGraph):+ return GraphMeta(+ id=graph.id,+ version=graph.version,+ is_active=graph.isActive,+ is_template=graph.isTemplate,+ name=graph.name or "",+ description=graph.description or "",+ )+++class Graph(GraphMeta):nodes: list[Node]links: list[Link]@@ -81,15 +93,15 @@ class Graph(BaseDbModel):@staticmethoddef from_db(graph: AgentGraph):return Graph(- id=graph.id,- name=graph.name or "",- description=graph.description or "",+ **GraphMeta.from_db(graph).model_dump(),nodes=[Node.from_db(node) for node in graph.AgentNodes or []],- links=list({- Link.from_db(link)- for node in graph.AgentNodes or []- for link in (node.Input or []) + (node.Output or [])- })+ links=list(+ {+ Link.from_db(link)+ for node in graph.AgentNodes or []+ for link in (node.Input or []) + (node.Output or [])+ }+ ),)@@ -111,50 +123,148 @@ async def get_node(node_id: str) -> Node | None:return Node.from_db(node) if node else None+# TODO: Delete thisasync def get_graph_ids() -> list[str]:- return [graph.id for graph in await AgentGraph.prisma().find_many()] # type: ignore+ return [+ graph.id+ for graph in await AgentGraph.prisma().find_many(+ distinct=["id"], where={"isActive": True}+ )+ ]-async def get_graph(graph_id: str) -> Graph | None:- graph = await AgentGraph.prisma().find_unique(- where={"id": graph_id},+async def get_graphs_meta(+ filter_by: Literal["active", "template"] | None = "active"+) -> list[GraphMeta]:+ """+ Retrieves graph metadata objects.+ Default behaviour is to get all currently active graphs.++ Args:+ filter: An optional filter to either select templates or active graphs.++ Returns:+ list[GraphMeta]: A list of GraphMeta objects representing the retrieved graph metadata.+ """+ where_clause: prisma.types.AgentGraphWhereInput = {}++ if filter_by == "active":+ where_clause["isActive"] = True+ elif filter_by == "template":+ where_clause["isTemplate"] = True++ graphs = await AgentGraph.prisma().find_many(+ where=where_clause,+ distinct=["id"],+ order={"version": "desc"},+ )++ if not graphs:+ return []++ return [GraphMeta.from_db(graph) for graph in graphs]+++async def get_graph(+ graph_id: str, version: int | None = None, template: bool = False+) -> Graph | None:+ """+ Retrieves a graph from the DB.+ Defaults to the version with `is_active` if `version` is not passed,+ or the latest version with `is_template` if `template=True`.++ Returns `None` if the record is not found.+ """+ where_clause: prisma.types.AgentGraphWhereInput = {+ "id": graph_id,+ "isTemplate": template,+ }+ if version is not None:+ where_clause["version"] = version+ elif not template:+ where_clause["isActive"] = True++ graph = await AgentGraph.prisma().find_first(+ where=where_clause,include={"AgentNodes": {"include": EXECUTION_NODE_INCLUDE}}, # type: ignore+ order={"version": "desc"},)return Graph.from_db(graph) if graph else None+async def set_graph_active_version(graph_id: str, version: int) -> None:+ updated_graph = await AgentGraph.prisma().update(+ data={"isActive": True},+ where={"graphVersionId": {"id": graph_id, "version": version}},+ )+ if not updated_graph:+ raise Exception(f"Graph #{graph_id} v{version} not found")++ # Deactivate all other versions+ await AgentGraph.prisma().update_many(+ data={"isActive": False},+ where={"id": graph_id, "version": {"not": version}},+ )+++async def get_graph_all_versions(graph_id: str) -> list[Graph]:+ graph_versions = await AgentGraph.prisma().find_many(+ where={"id": graph_id},+ order={"version": "desc"},+ include={"AgentNodes": {"include": EXECUTION_NODE_INCLUDE}}, # type: ignore+ )++ if not graph_versions:+ return []++ return [Graph.from_db(graph) for graph in graph_versions]++async def create_graph(graph: Graph) -> Graph:await AgentGraph.prisma().create(data={"id": graph.id,+ "version": graph.version,"name": graph.name,"description": graph.description,+ "isTemplate": graph.is_template,+ "isActive": graph.is_active,})# TODO: replace bulk creation using create_many- await asyncio.gather(*[- AgentNode.prisma().create({- "id": node.id,- "agentBlockId": node.block_id,- "agentGraphId": graph.id,- "constantInput": json.dumps(node.input_default),- "metadata": json.dumps(node.metadata),- }) for node in graph.nodes- ])-- await asyncio.gather(*[- AgentNodeLink.prisma().create({- "id": str(uuid.uuid4()),- "sourceName": link.source_name,- "sinkName": link.sink_name,- "agentNodeSourceId": link.source_id,- "agentNodeSinkId": link.sink_id,- })- for link in graph.links- ])-- if created_graph := await get_graph(graph.id):+ await asyncio.gather(+ *[+ AgentNode.prisma().create(+ {+ "id": node.id,+ "agentBlockId": node.block_id,+ "agentGraphId": graph.id,+ "agentGraphVersion": graph.version,+ "constantInput": json.dumps(node.input_default),+ "metadata": json.dumps(node.metadata),+ }+ )+ for node in graph.nodes+ ]+ )++ await asyncio.gather(+ *[+ AgentNodeLink.prisma().create(+ {+ "id": str(uuid.uuid4()),+ "sourceName": link.source_name,+ "sinkName": link.sink_name,+ "agentNodeSourceId": link.source_id,+ "agentNodeSinkId": link.sink_id,+ }+ )+ for link in graph.links+ ]+ )++ if created_graph := await get_graph(graph.id, graph.version):return created_graph- raise ValueError(f"Failed to create graph {graph.id}.")+ raise ValueError(f"Failed to create graph {graph.id}:{graph.version}.")diff --git a/rnd/autogpt_server/autogpt_server/data/schedule.py b/rnd/autogpt_server/autogpt_server/data/schedule.pyindex c1a28c7c94..1e24c4fd3c 100644--- a/rnd/autogpt_server/autogpt_server/data/schedule.py+++ b/rnd/autogpt_server/autogpt_server/data/schedule.py@@ -9,6 +9,7 @@ from autogpt_server.util import jsonclass ExecutionSchedule(BaseDbModel):graph_id: str+ graph_version: intschedule: stris_enabled: boolinput_data: dict[str, Any]@@ -28,6 +29,7 @@ class ExecutionSchedule(BaseDbModel):return ExecutionSchedule(id=schedule.id,graph_id=schedule.agentGraphId,+ graph_version=schedule.agentGraphVersion,schedule=schedule.schedule,is_enabled=schedule.isEnabled,last_updated=schedule.lastUpdated.replace(tzinfo=None),@@ -74,6 +76,7 @@ async def add_schedule(schedule: ExecutionSchedule) -> ExecutionSchedule:data={"id": schedule.id,"agentGraphId": schedule.graph_id,+ "agentGraphVersion": schedule.graph_version,"schedule": schedule.schedule,"isEnabled": schedule.is_enabled,"inputData": json.dumps(schedule.input_data),diff --git a/rnd/autogpt_server/autogpt_server/executor/manager.py b/rnd/autogpt_server/autogpt_server/executor/manager.pyindex 2b1acff05c..f2e4be4f08 100644--- a/rnd/autogpt_server/autogpt_server/executor/manager.py+++ b/rnd/autogpt_server/autogpt_server/executor/manager.py@@ -20,7 +20,7 @@ from autogpt_server.data.execution import (ExecutionStatus,ExecutionQueue,)-from autogpt_server.data.graph import Link, Node, get_node, get_graph+from autogpt_server.data.graph import Link, Node, get_node, get_graph, Graphfrom autogpt_server.util.service import AppService, expose, get_service_client # type: ignorelogger = logging.getLogger(__name__)@@ -254,7 +254,7 @@ class ExecutionManager(AppService):@exposedef add_execution(self, graph_id: str, data: dict[str, Any]) -> dict[Any, Any]:- graph = self.run_and_wait(get_graph(graph_id))+ graph: Graph | None = self.run_and_wait(get_graph(graph_id))if not graph:raise Exception(f"Graph #{graph_id} not found.")@@ -268,6 +268,7 @@ class ExecutionManager(AppService):graph_exec_id, node_execs = self.run_and_wait(create_graph_execution(graph_id=graph_id,+ graph_version=graph.version,node_ids=[node.id for node in graph.starting_nodes],data=data,)diff --git a/rnd/autogpt_server/autogpt_server/executor/scheduler.py b/rnd/autogpt_server/autogpt_server/executor/scheduler.pyindex c547d2d012..1e1e69a5bb 100644--- a/rnd/autogpt_server/autogpt_server/executor/scheduler.py+++ b/rnd/autogpt_server/autogpt_server/executor/scheduler.py@@ -1,5 +1,6 @@import loggingimport time+from typing import Anyfrom apscheduler.schedulers.background import BackgroundSchedulerfrom apscheduler.triggers.cron import CronTrigger@@ -66,9 +67,12 @@ class ExecutionScheduler(AppService):return schedule_id@expose- def add_execution_schedule(self, graph_id: str, cron: str, input_data: dict) -> str:+ def add_execution_schedule(+ self, graph_id: str, graph_version: int, cron: str, input_data: dict[str, Any]+ ) -> str:schedule = model.ExecutionSchedule(graph_id=graph_id,+ graph_version=graph_version,schedule=cron,input_data=input_data,)diff --git a/rnd/autogpt_server/autogpt_server/server/model.py b/rnd/autogpt_server/autogpt_server/server/model.pyindex 051bdc88ba..6ca24535f4 100644--- a/rnd/autogpt_server/autogpt_server/server/model.py+++ b/rnd/autogpt_server/autogpt_server/server/model.py@@ -3,6 +3,9 @@ import typingimport pydantic+import autogpt_server.data.graph++class Methods(enum.Enum):SUBSCRIBE = "subscribe"UNSUBSCRIBE = "unsubscribe"@@ -37,3 +40,13 @@ class SubscriptionDetails(pydantic.BaseModel):event_type: strchannel: strgraph_id: str+++class CreateGraph(pydantic.BaseModel):+ template_id: str | None = None+ template_version: int | None = None+ graph: autogpt_server.data.graph.Graph | None = None+++class SetGraphActiveVersion(pydantic.BaseModel):+ active_graph_version: intdiff --git a/rnd/autogpt_server/autogpt_server/server/server.py b/rnd/autogpt_server/autogpt_server/server/server.pyindex af04474ec4..ce272efb49 100644--- a/rnd/autogpt_server/autogpt_server/server/server.py+++ b/rnd/autogpt_server/autogpt_server/server/server.py@@ -1,12 +1,9 @@import asyncioimport uuid+from contextlib import asynccontextmanagerfrom typing import Annotated, Any, Dictimport uvicorn-from fastapi.responses import JSONResponse-from fastapi.staticfiles import StaticFiles--from contextlib import asynccontextmanagerfrom fastapi import (APIRouter,Body,@@ -16,22 +13,23 @@ from fastapi import (WebSocketDisconnect,)from fastapi.middleware.cors import CORSMiddleware+from fastapi.responses import JSONResponse+from fastapi.staticfiles import StaticFiles-from autogpt_server.data import db, execution, block-from autogpt_server.data.graph import (- create_graph,- get_graph,- get_graph_ids,- Graph,-)+import autogpt_server.server.ws_api+from autogpt_server.data import block, db, execution, graph as graph_dbfrom autogpt_server.executor import ExecutionManager, ExecutionSchedulerfrom autogpt_server.server.conn_manager import ConnectionManager-import autogpt_server.server.ws_api+from autogpt_server.server.model import (+ CreateGraph,+ Methods,+ SetGraphActiveVersion,+ WsMessage,+)from autogpt_server.util.data import get_frontend_pathfrom autogpt_server.util.service import expose # type: ignorefrom autogpt_server.util.service import AppService, get_service_clientfrom autogpt_server.util.settings import Settings-from autogpt_server.server.model import WsMessage, Methodsclass AgentServer(AppService):@@ -89,8 +87,8 @@ class AgentServer(AppService):methods=["GET"],)router.add_api_route(- path="/graphs/{graph_id}",- endpoint=self.get_graph,+ path="/templates",+ endpoint=self.get_templates,methods=["GET"],)router.add_api_route(@@ -98,6 +96,51 @@ class AgentServer(AppService):endpoint=self.create_new_graph,methods=["POST"],)+ router.add_api_route(+ path="/templates",+ endpoint=self.create_new_template,+ methods=["POST"],+ )+ router.add_api_route(+ path="/graphs/{graph_id}",+ endpoint=self.get_graph,+ methods=["GET"],+ )+ router.add_api_route(+ path="/templates/{graph_id}",+ endpoint=self.get_template,+ methods=["GET"],+ )+ router.add_api_route(+ path="/graphs/{graph_id}",+ endpoint=self.update_graph,+ methods=["PUT"],+ )+ router.add_api_route(+ path="/templates/{graph_id}",+ endpoint=self.update_graph,+ methods=["PUT"],+ )+ router.add_api_route(+ path="/graphs/{graph_id}/versions",+ endpoint=self.get_graph_all_versions,+ methods=["GET"],+ )+ router.add_api_route(+ path="/templates/{graph_id}/versions",+ endpoint=self.get_graph_all_versions,+ methods=["GET"],+ )+ router.add_api_route(+ path="/graphs/{graph_id}/versions/{version}",+ endpoint=self.get_graph,+ methods=["GET"],+ )+ router.add_api_route(+ path="/graphs/{graph_id}/versions/active",+ endpoint=self.set_graph_active_version,+ methods=["PUT"],+ )router.add_api_route(path="/graphs/{graph_id}/execute",endpoint=self.execute_graph, # type: ignore@@ -230,8 +273,8 @@ class AgentServer(AppService):print("Get graph request received")elif message.method == Methods.CREATE_GRAPH:assert isinstance(message.data, dict), "Data must be a dictionary"- graph = Graph.model_validate(message.data)- data = await self.create_new_graph(graph)+ create_graph = CreateGraph.model_validate(message.data)+ data = await self.create_new_graph(create_graph)await websocket.send_text(WsMessage(method=Methods.CREATE_GRAPH,@@ -351,19 +394,74 @@ class AgentServer(AppService):@classmethodasync def get_graphs(cls) -> list[str]:- return await get_graph_ids()+ # TODO: get_graph_ids() -> get_graphs_meta()+ return await graph_db.get_graph_ids()@classmethod- async def get_graph(cls, graph_id: str) -> Graph:- graph = await get_graph(graph_id)+ async def get_templates(cls) -> list[graph_db.GraphMeta]:+ return await graph_db.get_graphs_meta(filter_by="template")++ @classmethod+ async def get_graph(+ cls, graph_id: str, version: int | None = None+ ) -> graph_db.Graph:+ graph = await graph_db.get_graph(graph_id, version)if not graph:raise HTTPException(status_code=404, detail=f"Graph #{graph_id} not found.")return graph@classmethod- async def create_new_graph(cls, graph: Graph) -> Graph:+ async def get_template(+ cls, graph_id: str, version: int | None = None+ ) -> graph_db.Graph:+ graph = await graph_db.get_graph(graph_id, version, template=True)+ if not graph:+ raise HTTPException(+ status_code=404, detail=f"Template #{graph_id} not found."+ )+ return graph++ @classmethod+ async def get_graph_all_versions(cls, graph_id: str) -> list[graph_db.Graph]:+ graphs = await graph_db.get_graph_all_versions(graph_id)+ if not graphs:+ raise HTTPException(status_code=404, detail=f"Graph #{graph_id} not found.")+ return graphs++ @classmethod+ async def create_new_graph(cls, create_graph: CreateGraph) -> graph_db.Graph:+ return await cls.create_graph(create_graph, is_template=False)++ @classmethod+ async def create_new_template(cls, create_graph: CreateGraph) -> graph_db.Graph:+ return await cls.create_graph(create_graph, is_template=True)++ @classmethod+ async def create_graph(+ cls, create_graph: CreateGraph, is_template: bool+ ) -> graph_db.Graph:+ if create_graph.graph:+ graph = create_graph.graph+ elif create_graph.template_id:+ graph = await graph_db.get_graph(+ create_graph.template_id, create_graph.template_version, template=True+ )+ if not graph:+ raise HTTPException(+ 400, detail=f"Template #{create_graph.template_id} not found"+ )+ graph.version = 1+ else:+ raise HTTPException(+ status_code=400, detail="Either graph or template_id must be provided."+ )+# TODO: replace uuid generation here to DB generated uuids.graph.id = str(uuid.uuid4())++ graph.is_template = is_template+ graph.is_active = not is_template+id_map = {node.id: str(uuid.uuid4()) for node in graph.nodes}for node in graph.nodes:@@ -373,7 +471,60 @@ class AgentServer(AppService):link.source_id = id_map[link.source_id]link.sink_id = id_map[link.sink_id]- return await create_graph(graph)+ return await graph_db.create_graph(graph)++ @classmethod+ async def update_graph(cls, graph_id: str, graph: graph_db.Graph) -> graph_db.Graph:+ # Sanity check+ if graph.id and graph.id != graph_id:+ raise HTTPException(400, detail="Graph ID does not match ID in URI")++ # Determine new version+ existing_versions = await graph_db.get_graph_all_versions(graph_id)+ if not existing_versions:+ raise HTTPException(404, detail=f"Graph #{graph_id} not found")+ latest_version_number = max(g.version for g in existing_versions)+ graph.version = latest_version_number + 1++ latest_version_graph = next(+ v for v in existing_versions if v.version == latest_version_number+ )+ if latest_version_graph.is_template != graph.is_template:+ raise HTTPException(+ 400, detail="Changing is_template on an existing graph is forbidden"+ )+ graph.is_active = not graph.is_template++ # Assign new UUIDs to all nodes and links+ id_map = {node.id: str(uuid.uuid4()) for node in graph.nodes}+ for node in graph.nodes:+ node.id = id_map[node.id]+ for link in graph.links:+ link.source_id = id_map[link.source_id]+ link.sink_id = id_map[link.sink_id]++ new_graph_version = await graph_db.create_graph(graph)++ if new_graph_version.is_active:+ # Ensure new version is the only active version+ await graph_db.set_graph_active_version(+ graph_id=graph_id, version=new_graph_version.version+ )++ return new_graph_version++ @classmethod+ async def set_graph_active_version(+ cls, graph_id: str, request_body: SetGraphActiveVersion+ ):+ new_active_version = request_body.active_graph_version+ if not await graph_db.get_graph(graph_id, new_active_version):+ raise HTTPException(+ 404, f"Graph #{graph_id} v{new_active_version} not found"+ )+ await graph_db.set_graph_active_version(+ graph_id=graph_id, version=request_body.active_graph_version+ )async def execute_graph(self, graph_id: str, node_input: dict[Any, Any]@@ -385,32 +536,39 @@ class AgentServer(AppService):raise HTTPException(status_code=400, detail=msg)@classmethod- async def list_graph_runs(cls, graph_id: str) -> list[str]:- graph = await get_graph(graph_id)+ async def list_graph_runs(+ cls, graph_id: str, graph_version: int | None = None+ ) -> list[str]:+ graph = await graph_db.get_graph(graph_id, graph_version)if not graph:- raise HTTPException(status_code=404, detail=f"Agent #{graph_id} not found.")+ rev = "" if graph_version is None else f" v{graph_version}"+ raise HTTPException(+ status_code=404, detail=f"Agent #{graph_id}{rev} not found."+ )- return await execution.list_executions(graph_id)+ return await execution.list_executions(graph_id, graph_version)@classmethodasync def get_run_execution_results(cls, graph_id: str, run_id: str) -> list[execution.ExecutionResult]:- graph = await get_graph(graph_id)+ graph = await graph_db.get_graph(graph_id)if not graph:- raise HTTPException(status_code=404, detail=f"Agent #{graph_id} not found.")+ raise HTTPException(status_code=404, detail=f"Graph #{graph_id} not found.")return await execution.get_execution_results(run_id)async def create_schedule(self, graph_id: str, cron: str, input_data: dict[Any, Any]) -> dict[Any, Any]:- graph = await get_graph(graph_id)+ graph = await graph_db.get_graph(graph_id)if not graph:raise HTTPException(status_code=404, detail=f"Graph #{graph_id} not found.")execution_scheduler = self.execution_scheduler_clientreturn {- "id": execution_scheduler.add_execution_schedule(graph_id, cron, input_data) # type: ignore+ "id": execution_scheduler.add_execution_schedule(+ graph_id, graph.version, cron, input_data+ )}def update_schedule(diff --git a/rnd/autogpt_server/schema.prisma b/rnd/autogpt_server/schema.prismaindex fa2db7cd46..9e03edc027 100644--- a/rnd/autogpt_server/schema.prisma+++ b/rnd/autogpt_server/schema.prisma@@ -11,13 +11,19 @@ generator client {// This model describes the Agent Graph/Flow (Multi Agent System).model AgentGraph {- id String @id @default(uuid())+ id String @default(uuid())+ version Int @default(1)+name String?description String?+ isActive Boolean @default(true)+ isTemplate Boolean @default(false)AgentNodes AgentNode[]AgentGraphExecution AgentGraphExecution[]AgentGraphExecutionSchedule AgentGraphExecutionSchedule[]++ @@id(name: "graphVersionId", [id, version])}// This model describes a single node in the Agent Graph/Flow (Multi Agent System).@@ -27,8 +33,9 @@ model AgentNode {agentBlockId StringAgentBlock AgentBlock @relation(fields: [agentBlockId], references: [id])- agentGraphId String- AgentGraph AgentGraph @relation(fields: [agentGraphId], references: [id])+ agentGraphId String+ agentGraphVersion Int @default(1)+ AgentGraph AgentGraph @relation(fields: [agentGraphId, agentGraphVersion], references: [id, version])// List of consumed input, that the parent node should provide.Input AgentNodeLink[] @relation("AgentNodeSink")@@ -78,8 +85,9 @@ model AgentBlock {model AgentGraphExecution {id String @id @default(uuid())- agentGraphId String- AgentGraph AgentGraph @relation(fields: [agentGraphId], references: [id])+ agentGraphId String+ agentGraphVersion Int @default(1)+ AgentGraph AgentGraph @relation(fields: [agentGraphId, agentGraphVersion], references: [id, version])AgentNodeExecutions AgentNodeExecution[]}@@ -125,8 +133,9 @@ model AgentNodeExecutionInputOutput {model AgentGraphExecutionSchedule {id String @id- agentGraphId String- AgentGraph AgentGraph @relation(fields: [agentGraphId], references: [id])+ agentGraphId String+ agentGraphVersion Int @default(1)+ AgentGraph AgentGraph @relation(fields: [agentGraphId, agentGraphVersion], references: [id, version])schedule String // cron expressionisEnabled Boolean @default(true)diff --git a/rnd/autogpt_server/test/executor/test_manager.py b/rnd/autogpt_server/test/executor/test_manager.pyindex ca3c696b5b..5eaba62f49 100644--- a/rnd/autogpt_server/test/executor/test_manager.py+++ b/rnd/autogpt_server/test/executor/test_manager.py@@ -31,12 +31,28 @@ async def create_test_graph() -> graph.Graph:graph.Node(block_id=PrintingBlock().id),]links = [- graph.Link(nodes[0].id, nodes[2].id, "output", "texts_$_1"),- graph.Link(nodes[1].id, nodes[2].id, "output", "texts_$_2"),- graph.Link(nodes[2].id, nodes[3].id, "output", "text"),+ graph.Link(+ source_id=nodes[0].id,+ sink_id=nodes[2].id,+ source_name="output",+ sink_name="texts_$_1",+ ),+ graph.Link(+ source_id=nodes[1].id,+ sink_id=nodes[2].id,+ source_name="output",+ sink_name="texts_$_2",+ ),+ graph.Link(+ source_id=nodes[2].id,+ sink_id=nodes[3].id,+ source_name="output",+ sink_name="text",+ ),]test_graph = graph.Graph(name="TestGraph",+ version=1,description="Test graph",nodes=nodes,links=links,diff --git a/rnd/autogpt_server/test/executor/test_scheduler.py b/rnd/autogpt_server/test/executor/test_scheduler.pyindex 4ea154d060..622b70cfcd 100644--- a/rnd/autogpt_server/test/executor/test_scheduler.py+++ b/rnd/autogpt_server/test/executor/test_scheduler.py@@ -3,6 +3,7 @@ import pytestimport test_managerfrom autogpt_server.executor.scheduler import ExecutionSchedulerfrom autogpt_server.util.service import PyroNameServer, get_service_client+from autogpt_server.server import AgentServer@pytest.mark.asyncio(scope="session")@@ -11,23 +12,25 @@ async def test_agent_schedule():test_graph = await test_manager.create_test_graph()with PyroNameServer():- with ExecutionScheduler():- scheduler = get_service_client(ExecutionScheduler)-- schedules = scheduler.get_execution_schedules(test_graph.id)- assert len(schedules) == 0-- schedule_id = scheduler.add_execution_schedule(- test_graph.id,- "0 0 * * *",- {"input": "data"}- )- assert schedule_id-- schedules = scheduler.get_execution_schedules(test_graph.id)- assert len(schedules) == 1- assert schedules[schedule_id] == "0 0 * * *"-- scheduler.update_schedule(schedule_id, is_enabled=False)- schedules = scheduler.get_execution_schedules(test_graph.id)- assert len(schedules) == 0+ with AgentServer():+ with ExecutionScheduler():+ scheduler = get_service_client(ExecutionScheduler)++ schedules = scheduler.get_execution_schedules(test_graph.id)+ assert len(schedules) == 0++ schedule_id = scheduler.add_execution_schedule(+ graph_id=test_graph.id,+ graph_version=1,+ cron="0 0 * * *",+ input_data={"input": "data"},+ )+ assert schedule_id++ schedules = scheduler.get_execution_schedules(test_graph.id)+ assert len(schedules) == 1+ assert schedules[schedule_id] == "0 0 * * *"++ scheduler.update_schedule(schedule_id, is_enabled=False)+ schedules = scheduler.get_execution_schedules(test_graph.id)+ assert len(schedules) == 0diff --git a/rnd/autogpt_server/test/server/test_con_manager.py b/rnd/autogpt_server/test/server/test_con_manager.pyindex 8d5adac7d2..aff25c0901 100644--- a/rnd/autogpt_server/test/server/test_con_manager.py+++ b/rnd/autogpt_server/test/server/test_con_manager.py@@ -68,6 +68,7 @@ async def test_send_execution_result(connection_manager.subscriptions["test_graph"] = {mock_websocket}result: ExecutionResult = ExecutionResult(graph_id="test_graph",+ graph_version=1,graph_exec_id="test_exec_id",node_exec_id="test_node_exec_id",node_id="test_node_id",@@ -97,6 +98,7 @@ async def test_send_execution_result_no_subscribers() -> None:result: ExecutionResult = ExecutionResult(graph_id="test_graph",+ graph_version=1,graph_exec_id="test_exec_id",node_exec_id="test_node_exec_id",node_id="test_node_id",diff --git a/rnd/autogpt_server/test/usecases/reddit_marketing.py b/rnd/autogpt_server/test/usecases/reddit_marketing.pyindex 03253fa6d9..7b15e8858c 100644--- a/rnd/autogpt_server/test/usecases/reddit_marketing.py+++ b/rnd/autogpt_server/test/usecases/reddit_marketing.py@@ -28,7 +28,7 @@ async def create_test_graph() -> Graph:user_agent="TODO_FILL_OUT_THIS",)openai_api_key = "TODO_FILL_OUT_THIS"-+# Hardcoded inputsreddit_get_post_input = {"creds": reddit_creds,@@ -69,10 +69,7 @@ Make sure to only comment on a relevant post.block_id=TextFormatterBlock().id,input_default=text_formatter_input,)- llm_call_node = Node(- block_id=LlmCallBlock().id,- input_default=llm_call_input- )+ llm_call_node = Node(block_id=LlmCallBlock().id, input_default=llm_call_input)text_matcher_node = Node(block_id=TextMatcherBlock().id,input_default=text_matcher_input,@@ -92,14 +89,42 @@ Make sure to only comment on a relevant post.# Linkslinks = [- Link(reddit_get_post_node.id, text_formatter_node.id, "post", "named_texts"),- Link(text_formatter_node.id, llm_call_node.id, "output", "prompt"),- Link(llm_call_node.id, text_matcher_node.id, "response", "data"),- Link(llm_call_node.id, text_matcher_node.id, "response_#_is_relevant", "text"),- Link(text_matcher_node.id, reddit_comment_node.id, "positive_#_post_id",- "post_id"),- Link(text_matcher_node.id, reddit_comment_node.id, "positive_#_marketing_text",- "comment"),+ Link(+ source_id=reddit_get_post_node.id,+ sink_id=text_formatter_node.id,+ source_name="post",+ sink_name="named_texts",+ ),+ Link(+ source_id=text_formatter_node.id,+ sink_id=llm_call_node.id,+ source_name="output",+ sink_name="prompt",+ ),+ Link(+ source_id=llm_call_node.id,+ sink_id=text_matcher_node.id,+ source_name="response",+ sink_name="data",+ ),+ Link(+ source_id=llm_call_node.id,+ sink_id=text_matcher_node.id,+ source_name="response_#_is_relevant",+ sink_name="text",+ ),+ Link(+ source_id=text_matcher_node.id,+ sink_id=reddit_comment_node.id,+ source_name="positive_#_post_id",+ sink_name="post_id",+ ),+ Link(+ source_id=text_matcher_node.id,+ sink_id=reddit_comment_node.id,+ source_name="positive_#_marketing_text",+ sink_name="comment",+ ),]# Create graph@@ -125,9 +150,13 @@ async def wait_execution(test_manager, graph_id, graph_exec_id) -> list:Total: 13"""print("--------> Execution count: ", len(execs), [str(v.status) for v in execs])- return test_manager.queue.empty() and len(execs) == 13 and all(- v.status in [ExecutionStatus.COMPLETED, ExecutionStatus.FAILED]- for v in execs+ return (+ test_manager.queue.empty()+ and len(execs) == 13+ and all(+ v.status in [ExecutionStatus.COMPLETED, ExecutionStatus.FAILED]+ for v in execs+ ))# Wait for the executions to complete