mirror of
https://github.com/Significant-Gravitas/AutoGPT.git
synced 2026-04-08 03:00:28 -04:00
add client side calls
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import { createClient } from "../supabase/client";
|
||||
import {
|
||||
Block,
|
||||
Graph,
|
||||
@@ -6,17 +7,17 @@ import {
|
||||
GraphMeta,
|
||||
GraphExecuteResponse,
|
||||
NodeExecutionResult,
|
||||
} from "./types";
|
||||
} from "./types"
|
||||
|
||||
export default class AutoGPTServerAPI {
|
||||
private baseUrl: string;
|
||||
private wsUrl: string;
|
||||
private socket: WebSocket | null = null;
|
||||
private messageHandlers: { [key: string]: (data: any) => void } = {};
|
||||
private supabaseClient = createClient();
|
||||
|
||||
constructor(
|
||||
baseUrl: string = process.env.NEXT_PUBLIC_AGPT_SERVER_URL ||
|
||||
"http://localhost:8000/api",
|
||||
baseUrl: string = process.env.AGPT_SERVER_URL || "http://localhost:8000/api"
|
||||
) {
|
||||
this.baseUrl = baseUrl;
|
||||
this.wsUrl = `ws://${new URL(this.baseUrl).host}/ws`;
|
||||
@@ -27,11 +28,11 @@ export default class AutoGPTServerAPI {
|
||||
}
|
||||
|
||||
async listGraphs(): Promise<GraphMeta[]> {
|
||||
return this._get("/graphs");
|
||||
return this._get("/graphs")
|
||||
}
|
||||
|
||||
async listTemplates(): Promise<GraphMeta[]> {
|
||||
return this._get("/templates");
|
||||
return this._get("/templates")
|
||||
}
|
||||
|
||||
async getGraph(id: string, version?: number): Promise<Graph> {
|
||||
@@ -53,26 +54,22 @@ export default class AutoGPTServerAPI {
|
||||
}
|
||||
|
||||
async createGraph(graphCreateBody: GraphCreatable): Promise<Graph>;
|
||||
async createGraph(fromTemplateID: string, templateVersion: number): Promise<Graph>;
|
||||
async createGraph(
|
||||
fromTemplateID: string,
|
||||
templateVersion: number,
|
||||
): Promise<Graph>;
|
||||
async createGraph(
|
||||
graphOrTemplateID: GraphCreatable | string,
|
||||
templateVersion?: number,
|
||||
graphOrTemplateID: GraphCreatable | string, templateVersion?: number
|
||||
): Promise<Graph> {
|
||||
let requestBody: GraphCreateRequestBody;
|
||||
|
||||
if (typeof graphOrTemplateID == "string") {
|
||||
if (typeof(graphOrTemplateID) == "string") {
|
||||
if (templateVersion == undefined) {
|
||||
throw new Error("templateVersion not specified");
|
||||
throw new Error("templateVersion not specified")
|
||||
}
|
||||
requestBody = {
|
||||
template_id: graphOrTemplateID,
|
||||
template_version: templateVersion,
|
||||
};
|
||||
}
|
||||
} else {
|
||||
requestBody = { graph: graphOrTemplateID };
|
||||
requestBody = { graph: graphOrTemplateID }
|
||||
}
|
||||
|
||||
return this._request("POST", "/graphs", requestBody);
|
||||
@@ -92,40 +89,31 @@ export default class AutoGPTServerAPI {
|
||||
}
|
||||
|
||||
async setGraphActiveVersion(id: string, version: number): Promise<Graph> {
|
||||
return this._request("PUT", `/graphs/${id}/versions/active`, {
|
||||
active_graph_version: version,
|
||||
});
|
||||
return this._request(
|
||||
"PUT", `/graphs/${id}/versions/active`, { active_graph_version: version }
|
||||
);
|
||||
}
|
||||
|
||||
async executeGraph(
|
||||
id: string,
|
||||
inputData: { [key: string]: any } = {},
|
||||
id: string, inputData: { [key: string]: any } = {}
|
||||
): Promise<GraphExecuteResponse> {
|
||||
return this._request("POST", `/graphs/${id}/execute`, inputData);
|
||||
}
|
||||
|
||||
async listGraphRunIDs(
|
||||
graphID: string,
|
||||
graphVersion?: number,
|
||||
): Promise<string[]> {
|
||||
const query =
|
||||
graphVersion !== undefined ? `?graph_version=${graphVersion}` : "";
|
||||
async listGraphRunIDs(graphID: string, graphVersion?: number): Promise<string[]> {
|
||||
const query = graphVersion !== undefined ? `?graph_version=${graphVersion}` : "";
|
||||
return this._get(`/graphs/${graphID}/executions` + query);
|
||||
}
|
||||
|
||||
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 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,
|
||||
}));
|
||||
}
|
||||
|
||||
private async _get(path: string) {
|
||||
@@ -141,25 +129,24 @@ export default class AutoGPTServerAPI {
|
||||
console.debug(`${method} ${path} payload:`, payload);
|
||||
}
|
||||
|
||||
const token = (((await this.supabaseClient?.auth.getSession())?.data.session?.access_token) || "");
|
||||
|
||||
const response = await fetch(
|
||||
this.baseUrl + path,
|
||||
method != "GET"
|
||||
? {
|
||||
method,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
}
|
||||
: undefined,
|
||||
);
|
||||
this.baseUrl + path, {
|
||||
method,
|
||||
headers: method != 'GET' ? {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': (token ? `Bearer ${token}` : ''),
|
||||
} : {
|
||||
'Authorization': (token ? `Bearer ${token}` : ''),
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const response_data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
console.warn(
|
||||
`${method} ${path} returned non-OK response:`,
|
||||
response_data.detail,
|
||||
response,
|
||||
`${method} ${path} returned non-OK response:`, response_data.detail, response
|
||||
);
|
||||
throw new Error(`HTTP error ${response.status}! ${response_data.detail}`);
|
||||
}
|
||||
@@ -171,17 +158,17 @@ export default class AutoGPTServerAPI {
|
||||
this.socket = new WebSocket(this.wsUrl);
|
||||
|
||||
this.socket.onopen = () => {
|
||||
console.log("WebSocket connection established");
|
||||
console.log('WebSocket connection established');
|
||||
resolve();
|
||||
};
|
||||
|
||||
this.socket.onclose = (event) => {
|
||||
console.log("WebSocket connection closed", event);
|
||||
console.log('WebSocket connection closed', event);
|
||||
this.socket = null;
|
||||
};
|
||||
|
||||
this.socket.onerror = (error) => {
|
||||
console.error("WebSocket error:", error);
|
||||
console.error('WebSocket error:', error);
|
||||
reject(error);
|
||||
};
|
||||
|
||||
@@ -201,48 +188,42 @@ export default class AutoGPTServerAPI {
|
||||
}
|
||||
|
||||
sendWebSocketMessage<M extends keyof WebsocketMessageTypeMap>(
|
||||
method: M,
|
||||
data: WebsocketMessageTypeMap[M],
|
||||
method: M, data: WebsocketMessageTypeMap[M]
|
||||
) {
|
||||
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
|
||||
this.socket.send(JSON.stringify({ method, data }));
|
||||
} else {
|
||||
console.error("WebSocket is not connected");
|
||||
console.error('WebSocket is not connected');
|
||||
}
|
||||
}
|
||||
|
||||
onWebSocketMessage<M extends keyof WebsocketMessageTypeMap>(
|
||||
method: M,
|
||||
handler: (data: WebsocketMessageTypeMap[M]) => void,
|
||||
method: M, handler: (data: WebsocketMessageTypeMap[M]) => void
|
||||
) {
|
||||
this.messageHandlers[method] = handler;
|
||||
}
|
||||
|
||||
subscribeToExecution(graphId: string) {
|
||||
this.sendWebSocketMessage("subscribe", { graph_id: graphId });
|
||||
this.sendWebSocketMessage('subscribe', { graph_id: graphId });
|
||||
}
|
||||
|
||||
runGraph(
|
||||
graphId: string,
|
||||
data: WebsocketMessageTypeMap["run_graph"]["data"] = {},
|
||||
) {
|
||||
this.sendWebSocketMessage("run_graph", { graph_id: graphId, data });
|
||||
runGraph(graphId: string, data: WebsocketMessageTypeMap["run_graph"]["data"] = {}) {
|
||||
this.sendWebSocketMessage('run_graph', { graph_id: graphId, data });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* *** UTILITY TYPES *** */
|
||||
|
||||
type GraphCreateRequestBody =
|
||||
| {
|
||||
template_id: string;
|
||||
template_version: number;
|
||||
}
|
||||
| {
|
||||
graph: GraphCreatable;
|
||||
};
|
||||
type GraphCreateRequestBody = {
|
||||
template_id: string;
|
||||
template_version: number;
|
||||
} | {
|
||||
graph: GraphCreatable;
|
||||
}
|
||||
|
||||
type WebsocketMessageTypeMap = {
|
||||
subscribe: { graph_id: string };
|
||||
run_graph: { graph_id: string; data: { [key: string]: any } };
|
||||
subscribe: { graph_id: string; };
|
||||
run_graph: { graph_id: string; data: { [key: string]: any }; };
|
||||
execution_event: NodeExecutionResult;
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user