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.
refactor(builder): Clean up `AutoGPTServerAPI` implementation (#7468)
Reinier van der Leere128bfaf5f58
diff --git a/rnd/autogpt_builder/src/app/monitor/page.tsx b/rnd/autogpt_builder/src/app/monitor/page.tsxindex ff14973f03..f1bdf00e55 100644--- a/rnd/autogpt_builder/src/app/monitor/page.tsx+++ b/rnd/autogpt_builder/src/app/monitor/page.tsx@@ -23,7 +23,7 @@ import {DropdownMenuTrigger,} from "@/components/ui/dropdown-menu"import { ClockIcon, Pencil2Icon } from '@radix-ui/react-icons';-import AutoGPTServerAPI, { Flow, NodeExecutionResult } from '@/lib/autogpt_server_api';+import AutoGPTServerAPI, { Graph, NodeExecutionResult } from '@/lib/autogpt_server_api';import { cn, hashString } from '@/lib/utils';import { Badge } from "@/components/ui/badge";import { Button, buttonVariants } from "@/components/ui/button";@@ -33,9 +33,9 @@ import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popoverimport { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";const Monitor = () => {- const [flows, setFlows] = useState<Flow[]>([]);+ const [flows, setFlows] = useState<Graph[]>([]);const [flowRuns, setFlowRuns] = useState<FlowRun[]>([]);- const [selectedFlow, setSelectedFlow] = useState<Flow | null>(null);+ const [selectedFlow, setSelectedFlow] = useState<Graph | null>(null);const [selectedRun, setSelectedRun] = useState<FlowRun | null>(null);const api = new AutoGPTServerAPI();@@ -48,13 +48,13 @@ const Monitor = () => {function fetchFlowsAndRuns() {// Fetch flow IDs- api.listFlowIDs()+ api.listGraphIDs().then(flowIDs => {Promise.all(flowIDs.map(flowID => {refreshFlowRuns(flowID);// Fetch flow- return api.getFlow(flowID);+ return api.getGraph(flowID);})).then(flows => setFlows(flows));});@@ -62,7 +62,7 @@ const Monitor = () => {function refreshFlowRuns(flowID: string) {// Fetch flow run IDs- api.listFlowRunIDs(flowID)+ api.listGraphRunIDs(flowID).then(runIDs => runIDs.map(runID => {let run;if (@@ -73,7 +73,7 @@ const Monitor = () => {}// Fetch flow run- api.getFlowExecutionInfo(flowID, runID)+ api.getGraphExecutionInfo(flowID, runID).then(execInfo => setFlowRuns(flowRuns => {if (execInfo.length == 0) return flowRuns;@@ -108,7 +108,7 @@ const Monitor = () => {runs={(selectedFlow- ? flowRuns.filter(v => v.flowID == selectedFlow.id)+ ? flowRuns.filter(v => v.graphID == selectedFlow.id): flowRuns).toSorted((a, b) => Number(a.startTime) - Number(b.startTime))@@ -119,13 +119,13 @@ const Monitor = () => {<div className="col-span-full xl:col-span-4 xxl:col-span-5">{selectedRun && (<FlowRunInfo- flow={selectedFlow || flows.find(f => f.id == selectedRun.flowID)!}+ flow={selectedFlow || flows.find(f => f.id == selectedRun.graphID)!}flowRun={selectedRun}/>) || selectedFlow && (<FlowInfoflow={selectedFlow}- flowRuns={flowRuns.filter(r => r.flowID == selectedFlow.id)}+ flowRuns={flowRuns.filter(r => r.graphID == selectedFlow.id)}/>) || (<Card className="p-6">@@ -139,8 +139,8 @@ const Monitor = () => {type FlowRun = {id: string- flowID: string- flowVersion: number+ graphID: string+ graphVersion: numberstatus: 'running' | 'waiting' | 'success' | 'failed'startTime: number // unix timestamp (ms)endTime: number // unix timestamp (ms)@@ -186,8 +186,8 @@ function flowRunFromNodeExecutionResults(return {id: nodeExecutionResults[0].graph_exec_id,- flowID: nodeExecutionResults[0].graph_id,- flowVersion: nodeExecutionResults[0].graph_version,+ graphID: nodeExecutionResults[0].graph_id,+ graphVersion: nodeExecutionResults[0].graph_version,status,startTime,endTime,@@ -199,10 +199,10 @@ function flowRunFromNodeExecutionResults(const AgentFlowList = ({ flows, flowRuns, selectedFlow, onSelectFlow, className }: {- flows: Flow[],+ flows: Graph[],flowRuns?: FlowRun[],- selectedFlow: Flow | null,- onSelectFlow: (f: Flow) => void,+ selectedFlow: Graph | null,+ onSelectFlow: (f: Graph) => void,className?: string,}) => (@@ -226,7 +226,7 @@ const AgentFlowList = (.map((flow) => {let runCount = 0, lastRun: FlowRun | null = null;if (flowRuns) {- const _flowRuns = flowRuns.filter(r => r.flowID == flow.id);+ const _flowRuns = flowRuns.filter(r => r.graphID == flow.id);runCount = _flowRuns.length;lastRun = runCount == 0 ? null : _flowRuns.reduce((a, c) => a.startTime > c.startTime ? a : c@@ -280,7 +280,7 @@ const FlowStatusBadge = ({ status }: { status: "active" | "disabled" | "failing");const FlowRunsList: React.FC<{- flows: Flow[];+ flows: Graph[];runs: FlowRun[];className?: string;selectedRun?: FlowRun | null;@@ -308,7 +308,7 @@ const FlowRunsList: React.FC<{onClick={() => onSelectRun(run)}data-state={selectedRun?.id == run.id ? "selected" : null}>- <TableCell>{flows.find(f => f.id == run.flowID)!.name}</TableCell>+ <TableCell>{flows.find(f => f.id == run.graphID)!.name}</TableCell><TableCell>{moment(run.startTime).format("HH:mm")}</TableCell><TableCell><FlowRunStatusBadge status={run.status} /></TableCell><TableCell>{formatDuration(run.duration)}</TableCell>@@ -339,17 +339,17 @@ const FlowRunStatusBadge: React.FC<{);const FlowInfo: React.FC<{- flow: Flow;+ flow: Graph;flowRuns: FlowRun[];flowVersion?: number | "all";}> = ({ flow, flowRuns, flowVersion }) => {const api = new AutoGPTServerAPI();- const [flowVersions, setFlowVersions] = useState<Flow[] | null>(null);+ const [flowVersions, setFlowVersions] = useState<Graph[] | null>(null);const [selectedVersion, setSelectedFlowVersion] = useState(flowVersion ?? "all");useEffect(() => {- api.getFlowAllVersions(flow.id).then(result => setFlowVersions(result));+ api.getGraphAllVersions(flow.id).then(result => setFlowVersions(result));}, [flow.id]);return <Card>@@ -400,8 +400,8 @@ const FlowInfo: React.FC<{: flow]}flowRuns={flowRuns.filter(r =>- r.flowID == flow.id- && (selectedVersion == "all" || r.flowVersion == selectedVersion)+ r.graphID == flow.id+ && (selectedVersion == "all" || r.graphVersion == selectedVersion))}/></CardContent>@@ -409,10 +409,10 @@ const FlowInfo: React.FC<{};const FlowRunInfo: React.FC<{- flow: Flow;+ flow: Graph;flowRun: FlowRun;}> = ({ flow, flowRun }) => {- if (flowRun.flowID != flow.id) {+ if (flowRun.graphID != flow.id) {throw new Error(`FlowRunInfo can't be used with non-matching flowRun.flowID and flow.id`)}@@ -440,7 +440,7 @@ const FlowRunInfo: React.FC<{};const FlowRunsStats: React.FC<{- flows: Flow[],+ flows: Graph[],flowRuns: FlowRun[],title?: string,className?: string,@@ -501,7 +501,7 @@ const FlowRunsStats: React.FC<{const FlowRunsTimeline = ({ flows, flowRuns, dataMin, className }: {- flows: Flow[],+ flows: Graph[],flowRuns: FlowRun[],dataMin: "dataMin" | number,className?: string,@@ -541,7 +541,7 @@ const FlowRunsTimeline = (content={({ payload, label }) => {if (payload && payload.length) {const data: FlowRun & { time: number, _duration: number } = payload[0].payload;- const flow = flows.find(f => f.id === data.flowID);+ const flow = flows.find(f => f.id === data.graphID);return (<Card className="p-2 text-xs leading-normal"><p><strong>Agent:</strong> {flow ? flow.name : 'Unknown'}</p>@@ -562,7 +562,7 @@ const FlowRunsTimeline = ({flows.map((flow) => (<Scatterkey={flow.id}- data={flowRuns.filter(fr => fr.flowID == flow.id).map(fr => ({+ data={flowRuns.filter(fr => fr.graphID == flow.id).map(fr => ({...fr,time: fr.startTime + (fr.totalRunTime * 1000),_duration: fr.totalRunTime,@@ -580,7 +580,7 @@ const FlowRunsTimeline = ({ ...run, time: run.startTime, _duration: 0 },{ ...run, time: run.endTime, _duration: run.totalRunTime }]}- stroke={`hsl(${hashString(run.flowID) * 137.5 % 360}, 70%, 50%)`}+ stroke={`hsl(${hashString(run.graphID) * 137.5 % 360}, 70%, 50%)`}strokeWidth={2}dot={false}legendType="none"diff --git a/rnd/autogpt_builder/src/components/Flow.tsx b/rnd/autogpt_builder/src/components/Flow.tsxindex 1b1bf66408..7532525039 100644--- a/rnd/autogpt_builder/src/components/Flow.tsx+++ b/rnd/autogpt_builder/src/components/Flow.tsx@@ -15,7 +15,7 @@ import ReactFlow, {import 'reactflow/dist/style.css';import CustomNode from './CustomNode';import './flow.css';-import AutoGPTServerAPI, { Block, Flow } from '@/lib/autogpt_server_api';+import AutoGPTServerAPI, { Block, Graph } from '@/lib/autogpt_server_api';import { ObjectSchema } from '@/lib/types';import { Button } from './ui/button';import { Input } from './ui/input';@@ -77,7 +77,7 @@ const FlowEditor: React.FC<{ flowID?: string; className?: string }> = ({const [nodeId, setNodeId] = useState<number>(1);const [availableNodes, setAvailableNodes] = useState<Block[]>([]);const [isSidebarOpen, setIsSidebarOpen] = useState(true);- const [savedAgent, setSavedAgent] = useState<Flow | null>(null);+ const [savedAgent, setSavedAgent] = useState<Graph | null>(null);const [agentDescription, setAgentDescription] = useState<string>('');const [agentName, setAgentName] = useState<string>('');@@ -107,12 +107,12 @@ const FlowEditor: React.FC<{ flowID?: string; className?: string }> = ({.catch();}, []);- // Load existing flow+ // Load existing graphuseEffect(() => {if (!flowID || availableNodes.length == 0) return;- api.getFlow(flowID)- .then(flow => loadFlow(flow));+ api.getGraph(flowID)+ .then(graph => loadGraph(graph));}, [flowID, availableNodes]);const nodeTypes: NodeTypes = useMemo(() => ({ custom: CustomNode }), []);@@ -214,12 +214,12 @@ const FlowEditor: React.FC<{ flowID?: string; className?: string }> = ({setNodeId((prevId) => prevId + 1);};- function loadFlow(flow: Flow) {- setSavedAgent(flow);- setAgentName(flow.name);- setAgentDescription(flow.description);+ function loadGraph(graph: Graph) {+ setSavedAgent(graph);+ setAgentName(graph.name);+ setAgentDescription(graph.description);- setNodes(flow.nodes.map(node => {+ setNodes(graph.nodes.map(node => {const block = availableNodes.find(block => block.id === node.block_id)!;const newNode = {id: node.id,@@ -245,7 +245,7 @@ const FlowEditor: React.FC<{ flowID?: string; className?: string }> = ({return newNode;}));- setEdges(flow.links.map(link => ({+ setEdges(graph.links.map(link => ({id: `${link.source_id}_${link.source_name}_${link.sink_id}_${link.sink_name}`,source: link.source_id,target: link.sink_id,@@ -359,8 +359,8 @@ const FlowEditor: React.FC<{ flowID?: string; className?: string }> = ({}const newSavedAgent = savedAgent- ? await api.updateFlow(savedAgent.id, payload)- : await api.createFlow(payload);+ ? await api.updateGraph(savedAgent.id, payload)+ : await api.createGraph(payload);console.debug('Response from the API:', newSavedAgent);setSavedAgent(newSavedAgent);diff --git a/rnd/autogpt_builder/src/lib/autogpt_server_api.ts b/rnd/autogpt_builder/src/lib/autogpt_server_api.tsindex 3f9bee6215..36073533e6 100644--- a/rnd/autogpt_builder/src/lib/autogpt_server_api.ts+++ b/rnd/autogpt_builder/src/lib/autogpt_server_api.ts@@ -13,224 +13,108 @@ export default class AutoGPTServerAPI {}async getBlocks(): Promise<Block[]> {- try {- const response = await fetch(`${this.baseUrl}/blocks`);- if (!response.ok) {- console.warn("GET /blocks returned non-OK response:", response);- throw new Error(`HTTP error ${response.status}!`);- }- return await response.json();- } catch (error) {- console.error('Error fetching blocks:', error);- throw error;- }+ return await this._get("/blocks");}- async listFlowIDs(): Promise<string[]> {- try {- const response = await fetch(`${this.baseUrl}/graphs`);- if (!response.ok) {- console.warn("GET /graphs returned non-OK response:", response);- throw new Error(`HTTP error ${response.status}!`);- }- return await response.json();- } catch (error) {- console.error('Error fetching flows:', error);- throw error;- }+ async listGraphIDs(): Promise<string[]> {+ return this._get("/graphs")}- 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) {- 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:', error);- throw error;- }+ async getGraph(id: string, version?: number): Promise<Graph> {+ const query = version !== undefined ? `?version=${version}` : "";+ return this._get(`/graphs/${id}` + query);}- 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 getGraphAllVersions(id: string): Promise<Graph[]> {+ return this._get(`/graphs/${id}/versions`);}- 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") {+ async createGraph(graphCreateBody: GraphCreatable): Promise<Graph>;+ async createGraph(fromTemplateID: string, templateVersion: number): Promise<Graph>;+ async createGraph(+ graphOrTemplateID: GraphCreatable | string, templateVersion?: number+ ): Promise<Graph> {+ let requestBody: GraphCreateRequestBody;++ if (typeof(graphOrTemplateID) == "string") {if (templateVersion == undefined) {throw new Error("templateVersion not specified")}requestBody = {- template_id: flowOrTemplateID,+ template_id: graphOrTemplateID,template_version: templateVersion,}} else {- requestBody = { graph: flowOrTemplateID }+ requestBody = { graph: graphOrTemplateID }}- console.debug("POST /graphs payload:", requestBody);- try {- const response = await fetch(`${this.baseUrl}/graphs`, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- },- body: JSON.stringify(requestBody),- });- const response_data = await response.json();- if (!response.ok) {- console.warn(- `POST /graphs 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 storing flow:", error);- throw error;- }+ return this._request("POST", "/graphs", requestBody);}- async updateFlow(flowID: string, flow: FlowUpdateable): Promise<Flow> {- const path = `/graphs/${flowID}`;- console.debug(`PUT ${path} payload:`, flow);+ async updateGraph(id: string, graph: GraphUpdateable): Promise<Graph> {+ return await this._request("PUT", `/graphs/${id}`, graph);+ }- 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 setGraphActiveVersion(id: string, version: number): Promise<Graph> {+ return this._request(+ "PUT", `/graphs/${id}/versions/active`, { active_graph_version: version }+ );+ }++ async executeGraph(+ id: string, inputData: { [key: string]: any } = {}+ ): Promise<GraphExecuteResponse> {+ return this._request("POST", `/graphs/${id}/execute`, inputData);}- 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);+ async listGraphRunIDs(graphID: string, graphVersion?: number): Promise<string[]> {+ const query = graphVersion !== undefined ? `?graph_version=${graphVersion}` : "";+ return this._get(`/graphs/${graphID}/executions` + query);+ }- 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 getGraphExecutionInfo(graphID: string, runID: string): Promise<NodeExecutionResult[]> {+ return (await this._get(`/graphs/${graphID}/executions/${runID}`))+ .map((result: any) => ({+ ...result,+ add_time: new Date(result.add_time),+ queue_time: result.queue_time ? new Date(result.queue_time) : undefined,+ start_time: result.start_time ? new Date(result.start_time) : undefined,+ end_time: result.end_time ? new Date(result.end_time) : undefined,+ }));}- async executeFlow(- flowId: string, inputData: { [key: string]: any } = {}- ): Promise<FlowExecuteResponse> {- const path = `/graphs/${flowId}/execute`;- console.debug(`POST ${path}`);- try {- const response = await fetch(this.baseUrl + path, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- },- body: JSON.stringify(inputData),- });- const response_data = await response.json();- if (!response.ok) {- console.warn(- `POST ${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 executing flow:", error);- throw error;- }+ private async _get(path: string) {+ return this._request("GET", path);}- 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) {- 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 runs:', error);- throw error;+ private async _request(+ method: "GET" | "POST" | "PUT" | "PATCH",+ path: string,+ payload?: { [key: string]: any },+ ) {+ if (method != "GET") {+ console.debug(`${method} ${path} payload:`, payload);}- }- async getFlowExecutionInfo(flowId: string, runId: string): Promise<NodeExecutionResult[]> {- const path = `/graphs/${flowId}/executions/${runId}`;- 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()).map((result: any) => ({- ...result,- add_time: new Date(result.add_time),- queue_time: result.queue_time ? new Date(result.queue_time) : undefined,- start_time: result.start_time ? new Date(result.start_time) : undefined,- end_time: result.end_time ? new Date(result.end_time) : undefined,- }));- } catch (error) {- console.error('Error fetching execution status:', error);- throw error;+ const response = await fetch(+ this.baseUrl + path,+ method != "GET" ? {+ method,+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(payload),+ } : undefined+ );+ const response_data = await response.json();++ if (!response.ok) {+ console.warn(+ `${method} ${path} returned non-OK response:`, response_data.detail, response+ );+ throw new Error(`HTTP error ${response.status}! ${response_data.detail}`);}+ return response_data;}connectWebSocket(): Promise<void> {@@ -324,7 +208,7 @@ export type LinkCreatable = Omit<Link, "id"> & {}/* Mirror of autogpt_server/data/graph.py:GraphMeta */-export type FlowMeta = {+export type GraphMeta = {id: string;version: number;is_active: boolean;@@ -334,13 +218,13 @@ export type FlowMeta = {}/* Mirror of autogpt_server/data/graph.py:Graph */-export type Flow = FlowMeta & {+export type Graph = GraphMeta & {nodes: Array<Node>;links: Array<Link>;};-export type FlowUpdateable = Omit<- Flow,+export type GraphUpdateable = Omit<+ Graph,"version" | "is_active" | "is_template" | "links"> & {version?: number;@@ -349,17 +233,17 @@ export type FlowUpdateable = Omit<links: Array<LinkCreatable>;}-export type FlowCreatable = Omit<FlowUpdateable, "id"> & { id?: string }+export type GraphCreatable = Omit<GraphUpdateable, "id"> & { id?: string }-export type FlowCreateRequestBody = {+export type GraphCreateRequestBody = {template_id: string;template_version: number;} | {- graph: FlowCreatable;+ graph: GraphCreatable;}/* Derived from autogpt_server/executor/manager.py:ExecutionManager.add_execution */-export type FlowExecuteResponse = {+export type GraphExecuteResponse = {/* ID of the initiated run */id: string;/* List of node executions */@@ -380,4 +264,4 @@ export type NodeExecutionResult = {queue_time?: Date;start_time?: Date;end_time?: Date;-};\ No newline at end of file+};