Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Show API url after deploy
Vasek Mlejnsky99a1a2e80684
diff --git a/api-service/app.py b/api-service/app.pyindex a8e27f69e..1bfd2dee6 100644--- a/api-service/app.py+++ b/api-service/app.py@@ -1,9 +1,16 @@import os-from codegen.base import generate_req_handler+import uuid+import subprocess+from flask import Flask, requestfrom flask_cors import CORS-import subprocess+from codegen.base import generate_req_handler+from codegen.db.base import Database, DeploymentState++url = os.environ.get("SUPABASE_URL")+key = os.environ.get("SUPABASE_KEY")+db = Database(url, key)app = Flask(__name__)CORS(app)@@ -30,6 +37,7 @@ def health():def generate():body = request.json+ run_id = str(uuid.uuid4())project_id = body["projectID"]route_id = body["routeID"]blocks = body["blocks"]@@ -37,12 +45,16 @@ def generate():route = body["route"]final_prompt, js_code = generate_req_handler(- project_id=project_id, route_id=route_id, blocks=blocks, method=method+ run_id=run_id,+ db=db,+ project_id=project_id,+ route_id=route_id,+ blocks=blocks,+ method=method,)- # TODO: Change deployments.state field in db to "deploying"- # and after finishing deploying to "finished" (or "error")- # (use Database.update_state from codegen/db/base)+ # TODO: Change deployments.state field in db to "deploying"+ db.update_state(run_id=run_id, state=DeploymentState.Deploying)cf_worker_dir_path = (os.path.abspath(os.path.dirname(__file__)) + "/cf-worker-template"@@ -69,12 +81,13 @@ def generate():with subprocess.Popen(cmd, stdout=subprocess.PIPE) as proc:print(proc.stdout.read().decode())- # TODO: Report back the URL of deployed API+ db.update_state(run_id=run_id, state=DeploymentState.Finished)+ # TODO: Report back the URL of deployed APIreturn {"code": js_code.strip("`").strip(),"prompt": final_prompt,- "host": f"https://{project_id}.devbook.workers.dev",+ "url": f"https://{project_id}.devbook.workers.dev",}diff --git a/api-service/cf-worker-template/index.js b/api-service/cf-worker-template/index.jsindex a35ed7e9e..948217346 100644--- a/api-service/cf-worker-template/index.js+++ b/api-service/cf-worker-template/index.js@@ -3,13 +3,13 @@ import { Router } from 'itty-router'const router = Router()async function handlepostRequest(request) {- const body = await request.json()- const { email } = body- const regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/+ const data = await request.json();+ const { email } = data;+ const regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;if (!regex.test(String(email).toLowerCase())) {- return new Response(JSON.stringify({ error: 'Invalid email' }), { status: 400 })+ return new Response(JSON.stringify({ error: 'Invalid email' }), { status: 400 });}- return new Response(JSON.stringify({ message: 'Ok' }))+ return new Response(JSON.stringify({ message: 'Ok' }), { status: 200 });}router.post('/', handlepostRequest)diff --git a/api-service/codegen/base.py b/api-service/codegen/base.pyindex bfaac26ee..3a91223dc 100644--- a/api-service/codegen/base.py+++ b/api-service/codegen/base.py@@ -1,17 +1,23 @@from typing import List-import uuidfrom langchain.llms.openai import OpenAIChat, OpenAIfrom codegen.tools.javascript.tool import JavascriptEvalToolfrom codegen.tools.documentation.tool import ReadDocumentationfrom codegen.js_agent.base import create_js_agentfrom codegen.prompt import PREFIX, SUFFIX+from codegen.db.base import Database-def generate_req_handler(project_id: str, route_id: str, blocks: List[str], method: str) -> str:- run_id = str(uuid.uuid4())-+def generate_req_handler(+ db: Database,+ run_id: str,+ project_id: str,+ route_id: str,+ blocks: List[str],+ method: str,+) -> str:executor = create_js_agent(+ db=db,run_id=run_id,project_id=project_id,route_id=route_id,diff --git a/api-service/codegen/db/base.py b/api-service/codegen/db/base.pyindex 1c730bbd6..310bba224 100644--- a/api-service/codegen/db/base.py+++ b/api-service/codegen/db/base.py@@ -2,32 +2,35 @@ from typing import Listfrom enum import Enumfrom supabase import create_client+class DeploymentState(Enum):Generating = "generating"Deploying = "deploying"Finished = "finished"Error = "error"-class Database():- def __init__(self, url: str, key: str):- self.client = create_client(url, key)- def push_logs(self, run_id: str, project_id: str, route_id: str, logs: List[str]) -> None:- if len(logs) > 0:- self.client.table('deployments').upsert(- json={- 'id': run_id,- 'logs': logs,- 'project_id': project_id,- 'route_id': route_id,- 'state': DeploymentState.Generating.value,- },- ).execute()+class Database:+ def __init__(self, url: str, key: str):+ self.client = create_client(url, key)++ def push_logs(+ self, run_id: str, project_id: str, route_id: str, logs: List[str]+ ) -> None:+ if len(logs) > 0:+ self.client.table("deployments").upsert(+ json={+ "id": run_id,+ "logs": logs,+ "project_id": project_id,+ "route_id": route_id,+ "state": DeploymentState.Generating.value,+ },+ ).execute()- def update_state(self, run_id: str, state: DeploymentState) -> None:- self.client.table('deployments').update(- json={- 'id': run_id,- 'state': state.value,- },- ).execute()+ def update_state(self, run_id: str, state: DeploymentState) -> None:+ self.client.table("deployments").update(+ {+ "state": state.value,+ }+ ).eq("id", run_id).execute()diff --git a/api-service/codegen/js_agent/base.py b/api-service/codegen/js_agent/base.pyindex 531e280c9..492f7ac74 100644--- a/api-service/codegen/js_agent/base.py+++ b/api-service/codegen/js_agent/base.py@@ -12,12 +12,14 @@ from langchain.tools.base import BaseTool# from codegen.tools.javascript.tool import JavascriptEvalToolfrom codegen.js_agent.callbacks.log import LoggerCallbackHandler+from codegen.db.base import Database# from js_agent.prompt import PREFIX# from tools.javascript.tool import JavascriptEvalTooldef create_js_agent(+ db: Database,run_id: str,project_id: str,route_id: str,@@ -40,7 +42,9 @@ def create_js_agent(cb_manager = SharedCallbackManager()cb_manager.set_handler(- LoggerCallbackHandler(run_id=run_id, project_id=project_id, route_id=route_id)+ LoggerCallbackHandler(+ db=db, run_id=run_id, project_id=project_id, route_id=route_id+ ))return AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=verbose, callback_manager=cb_managerdiff --git a/api-service/codegen/js_agent/callbacks/log.py b/api-service/codegen/js_agent/callbacks/log.pyindex 9916a21bf..b281e29b7 100644--- a/api-service/codegen/js_agent/callbacks/log.py+++ b/api-service/codegen/js_agent/callbacks/log.py@@ -1,5 +1,4 @@from typing import List, Dict, Optional, Any, Union-import osfrom langchain.callbacks.base import BaseCallbackHandlerfrom langchain.input import print_text, get_colored_text@@ -13,13 +12,16 @@ class LoggerCallbackHandler(BaseCallbackHandler):"""Callback Handler that prints to std out."""def __init__(- self, run_id: str, project_id: str, route_id: str, color: Optional[str] = None+ self,+ db: Database,+ run_id: str,+ project_id: str,+ route_id: str,+ color: Optional[str] = None,) -> None:"""Initialize callback handler."""- url = os.environ.get("SUPABASE_URL")- key = os.environ.get("SUPABASE_KEY")- self.db = Database(url, key)+ self.db = dbself.run_id = run_idself.route_id = route_id@@ -62,7 +64,7 @@ class LoggerCallbackHandler(BaseCallbackHandler):) -> None:"""Print out that we are entering a chain."""class_name = serialized["name"]- db_log = f"**Entering new {class_name} chain...**\n\n---\n"+ db_log = f"**Entering new {class_name} chain...**\n\n---"self.push_log(db_log)log = f"\n\n\033[1m> Entering new {class_name} chain...\033[0m"@@ -111,16 +113,16 @@ class LoggerCallbackHandler(BaseCallbackHandler):) -> None:"""If not the final action, print out observation."""- if output:- db_log = f"\n{observation_prefix}\n\n---"- db_log += f"\noutput\n\n---\n"- db_log += f"\n{llm_prefix}\n"- self.push_log(db_log)+ db_log = f"\n{observation_prefix}\n\n---"+ db_log += f"\n{output}\n\n---\n"+ db_log += f"\n{llm_prefix}\n"+ self.push_log(db_log)- c = color if color else self.color- print_text(f"\n{observation_prefix}")- print_text(output, color=c)- print_text(f"\n{llm_prefix}")+ c = color if color else self.color+ print_text(f"\n{observation_prefix}")+ print_text(output, color=c)+ print_text(f"\n{llm_prefix}")+ # if output:def on_tool_error(self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any@@ -137,7 +139,7 @@ class LoggerCallbackHandler(BaseCallbackHandler):) -> None:"""Run when agent ends."""- db_log = f"{text}\n{end}\n\n---\n"+ db_log = f"{text}\n{end}\n\n---"self.push_log(db_log)c = color if color else self.color@@ -148,7 +150,7 @@ class LoggerCallbackHandler(BaseCallbackHandler):) -> None:"""Run on agent end."""- db_log = f"{finish.log}\n\n---\n"+ db_log = f"{finish.log}\n\n---"self.push_log(db_log)print_text(finish.log, color=color if self.color else color, end="\n")diff --git a/components/Editor/Logs.tsx b/components/Editor/Logs.tsxindex 64be51a56..5d6e5b278 100644--- a/components/Editor/Logs.tsx+++ b/components/Editor/Logs.tsx@@ -6,15 +6,18 @@ import { Log } from '.'import { Fragment } from 'react'import Button from 'components/Button'import Sidebar from 'components/Sidebar'+import Text from 'components/Text'export interface Props {logs?: Log[]deploy: () => void+ deployedURL: string}function Logs({logs,deploy,+ deployedURL,}: Props) {useEffect(function highlightCode() {@@ -32,13 +35,28 @@ function Logs({space-y-4">- <div>+ <div className="+ flex+ items-center+ justify-start+ space-x-2+ "><Buttontext="Deploy"onClick={deploy}variant={Button.variant.Full}/>-+ <a+ href={deployedURL}+ className="+ underline+ "+ >+ <Text+ size={Text.size.S3}+ text={deployedURL.substring('https://'.length)}+ />+ </a></div><div className="max-w-fulldiff --git a/components/Editor/index.tsx b/components/Editor/index.tsxindex 23227c915..a63814a96 100644--- a/components/Editor/index.tsx+++ b/components/Editor/index.tsx@@ -58,6 +58,7 @@ function Editor({ project }: Props) {const changeRoute = store.use.changeRoute()const addRoute = store.use.addRoute()+ const [deployedURL, setDeployedURL] = useState('')const [selectedRouteID, setSelectedRouteID] = useState(() => routes.length > 0 ? routes[0].id : undefined)const selectedRoute = routes.find(s => s.id === selectedRouteID)@@ -88,8 +89,8 @@ function Editor({ project }: Props) {projectID: project.id,route: selectedRoute,})- console.log(response.code)- console.log(response.host)++ setDeployedURL(response.url)}return (@@ -192,6 +193,7 @@ function Editor({ project }: Props) {<Logslogs={logs}deploy={deploy}+ deployedURL={deployedURL}/></>}