Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Deploy
Vasek Mlejnsky6a9506b32707
diff --git a/api-service/app.py b/api-service/app.pyindex dc03799b8..0271a08a7 100644--- a/api-service/app.py+++ b/api-service/app.py@@ -2,10 +2,11 @@ import osfrom codegen.base import generate_req_handlerfrom flask import Flask, requestfrom flask_cors import CORS-import CloudFlare-import json-import requests-import time+import subprocess+++app = Flask(__name__)+CORS(app)def dump(obj):@@ -13,105 +14,11 @@ def dump(obj):print("obj.%s = %r" % (attr, getattr(obj, attr)))-# cf_email = os.environ["CLOUDFLARE_EMAIL"]-# cf_api_key = os.environ["CLOUDFLARE_API_KEY"]-# cf_api_cert = os.environ["CLOUDFLARE_API_CERTKEY"]--# cf = CloudFlare.CloudFlare(-# email=cf_email, key=cf_api_key, certtoken=cf_api_cert, debug=False-# )--# cf_token = os.environ.get("CLOUDFLARE_API_TOKEN")-# cf = CloudFlare.CloudFlare(debug=True)--# cf_acc_id = os.environ.get("CLOUDFLARE_ACC_ID")--# ws = cf.accounts.workers.scripts.get(cf_acc_id)-# print(ws)--# js_code = str.encode(-# """-# module.exports = {{-# async fetch(request) {{-# return new Response("Hello World!", {{ headers: {{'Content-Type': 'text/html'}} }});-# }},-# }};-# """-# )--# script_name = "my_script_new"--# cf_url = "https://api.cloudflare.com/client/v4/accounts/{account_id}/workers/services/{script_name}/environments/production".format(-# account_id=cf_acc_id, script_name=script_name-# )-# headers = {-# "X-Auth-Email": cf_email,-# "X-Auth-Key": cf_api_key,-# }-# >>>>>>>>> THIS WORKS-# response = requests.put(-# cf_url,-# headers=headers,-# files={-# "worker.js": (-# "worker.js",-# open("worker.js", "rb"),-# "application/javascript+module",-# ),-# "package.json": (-# "package.json",-# open("package.json", "rb"),-# "application/json",-# ),-# "metadata": (-# None,-# str.encode('{"bindings": [], "main_module": "worker.js"}'),-# "application/json",-# ),-# },-# )-# response = requests.put(-# cf_url,-# headers=headers,-# files={-# "index.js": str.encode(-# """export default {{-# async fetch(request) {{-# return new Response("Hello World!");-# }},-# }};"""-# )-# },-# )-# print("RESPONSE 1")-# print(response.request.headers)-# print(response.content)-# print(response.json())--# Enable subdomain, eg: https://my_script.devbook.workers.dev/-# time.sleep(5)-# zone_id = "72aff3fa4f548f5fc3bbcc223037f444"-# cf_url = "https://api.cloudflare.com/client/v4/zones/{zone_id}/workers/routes".format(-# zone_id=zone_id-# )-# print(cf_url)-# response = requests.post(-# cf_url,-# headers=headers,-# json={-# "pattern": "{script_name}.devbook.workers.dev".format(script_name=script_name),-# "script": script_name,-# },-# )-# # response = requests.post(cf_url, headers=headers, json={"enabled": "true"})-# print("RESPONSE 2")-# print(response.request.headers)-# # print(response.content)-# print(response.json())---app = Flask(__name__)-CORS(app)+def replace_file_content(fp_in: str, fp_out: str, old: str, new: str) -> None:+ with open(fp_in, "rt") as fin:+ with open(fp_out, "wt") as fout:+ for line in fin:+ fout.write(line.replace(old, new))@app.route("/health", methods=["GET"])@@ -131,7 +38,38 @@ def generate():project_id=project_id, blocks=blocks, method=method)- return {"code": js_code.strip("`").strip(), "prompt": final_prompt}+ cf_worker_dir_path = (+ os.path.abspath(os.path.dirname(__file__)) + "/cf-worker-template"+ )+ index_js_path = cf_worker_dir_path + "/index.js"+ wrangler_template_path = cf_worker_dir_path + "/wrangler.template.toml"+ wrangler_path = cf_worker_dir_path + "/wrangler.toml"++ # TODO: Inject code to cf-worker-template/index.js+ code = js_code.strip("`").strip()+ with open(index_js_path, "w") as file:+ file.write(code)++ # TODO: Update name in cf-worker-template/wrangler.template.toml+ replace_file_content(+ wrangler_template_path,+ wrangler_path,+ "<NAME>",+ f'"{project_id}"',+ )++ # TODO: Call npm run deploy+ cmd = ["npm", "run", "deploy", "--prefix", cf_worker_dir_path]+ with subprocess.Popen(cmd, stdout=subprocess.PIPE) as proc:+ print(proc.stdout.read().decode())++ # TODO: Report back the URL of deployed API++ return {+ "code": js_code.strip("`").strip(),+ "prompt": final_prompt,+ "host": f"https://{project_id}.devbook.workers.dev",+ }if __name__ == "__main__":diff --git a/api-service/cf-worker-template/index.js b/api-service/cf-worker-template/index.jsindex 095a717c5..e9f11690b 100644--- a/api-service/cf-worker-template/index.js+++ b/api-service/cf-worker-template/index.js@@ -1,31 +1,13 @@import { Router } from 'itty-router'-const router = Router()async function handlepostRequest(request) {- // Get the email from the request JSON payload- const b = await request.json()- const email = b.email-- // Check if the email is valid- const isValidEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)-- // If the email isn't valid, respond with JSON containing the error message- if (!isValidEmail) {- return new Response(JSON.stringify({- error: 'Invalid email'- }), {- status: 400- })+ const { email } = await request.json();+ if (!/^\S+@\S+$/.test(email)) {+ return new Response(JSON.stringify({ error: 'Invalid email' }), { status: 400 });}-- // If the email is valid respond with JSON and payload containing "Ok"- return new Response(JSON.stringify({- message: 'Ok'- }), {- status: 200- })+ return new Response(JSON.stringify({ message: 'Ok' }));}router.post('/', handlepostRequest)@@ -33,5 +15,4 @@ router.get('*', () => new Response('Not found', { status: 404 }))export default {fetch: router.handle-}-+}\ No newline at end of filediff --git a/api-service/cf-worker-template/wrangler.template.toml b/api-service/cf-worker-template/wrangler.template.tomlnew file mode 100644index 000000000..abf88b9a1--- /dev/null+++ b/api-service/cf-worker-template/wrangler.template.toml@@ -0,0 +1,7 @@+# This wrangler file will be injected withl values during runtime and saved as wrangler.toml++name = <NAME>+main = "./index.js"+# route = ''+compatibility_date = "2022-05-03"+send_metrics = falsediff --git a/api-service/cf-worker-template/wrangler.toml b/api-service/cf-worker-template/wrangler.tomlindex f45b719d7..6120e7819 100644--- a/api-service/cf-worker-template/wrangler.toml+++ b/api-service/cf-worker-template/wrangler.toml@@ -1,4 +1,6 @@-name = "cf-worker-template" # todo+# This wrangler file will be injected withl values during runtime and saved as wrangler.toml++name = "460355b3"main = "./index.js"# route = ''compatibility_date = "2022-05-03"diff --git a/api-service/codegen/base.py b/api-service/codegen/base.pyindex 03428e70d..0c1ea57ec 100644--- a/api-service/codegen/base.py+++ b/api-service/codegen/base.py@@ -4,84 +4,7 @@ import uuidfrom langchain.llms.openai import OpenAIChat, OpenAIfrom codegen.tools.javascript.tool import JavascriptEvalToolfrom codegen.js_agent.base import create_js_agent---# PREFIX = """Complete a body of nodejs function that handles incoming {method} requests inside an Express server.--# You must follow these rules:-# - Don't write anything else but the body of function. Once you have the body function written, you should finish and output the code you have so far.-# - You have access to the following environment variables and you can use them if needed: SUPABASE_URL, SUPABASE_KEY.--# If you cannot follow any of the rules above, finish with the last code you wrote. Don't try in any way to go around the rules or come up with other solutions.---# The code must perform following logic:-# """--PREFIX = """You are a skilled programmer that knows nodejs and javascript.-You are building a serverless API with Cloudflare Workers using the 'itty-router' package (code and docs is here https://github.com/kwhitley/itty-router).-You need to complete the `handle{method}Request` function that handles the incoming {method} requests.--Here is some already written code that handles the initialization. The function that you need to complete is marked with a TODO comment:-```-import {{ Router }} from 'itty-router'--const router = Router()--function handle{method}Request(request) {{- // TODO-}}--addEventListener('fetch', (event) => {{- router- .{method}('/', handle{method}Request)- .get('*', () => new Response("Not found", {{ status: 404 }}))- router.handle(event.request)-}})-```--The code must perform the following logic:-"""--# SUFFIX = """-# Here's the code that must be completed:-# ```-# const express = require('express');-# const app = express();--# app.use(express.json());--# app.{method}(/, function(req, res) {{-# // TODO: Implement body of this function based on the required logic-# }})--# app.listen(8080, () => console.log('Listening on port 8080'));-# ```-# """--# SUFFIX = """Here is already written code that handles the initialization. You don't need to rewrite that.-# The part that you need to complete is marked with a TODO comment:-# ```-# import {{ Router }} from 'itty-router'--# const router = Router()--# function handleRequest(request) {{-# router-# .get('/', async function(req) {{-# // TODO-# })-# .get('*', () => new Response("Not found", {{ status: 404 }}))-# router.handle(request)-# }--# addEventListener('fetch', (event) => {{-# event.respondWith(handleRequest(event.request))-# }})-# ```-# """--SUFFIX = ""+from codegen.prompt import PREFIX, SUFFIXdef generate_req_handler(project_id: str, blocks: List[str], method: str) -> str:diff --git a/api-service/codegen/prompt.py b/api-service/codegen/prompt.pynew file mode 100644index 000000000..d6ebba0d9--- /dev/null+++ b/api-service/codegen/prompt.py@@ -0,0 +1,76 @@+# PREFIX = """Complete a body of nodejs function that handles incoming {method} requests inside an Express server.++# You must follow these rules:+# - Don't write anything else but the body of function. Once you have the body function written, you should finish and output the code you have so far.+# - You have access to the following environment variables and you can use them if needed: SUPABASE_URL, SUPABASE_KEY.++# If you cannot follow any of the rules above, finish with the last code you wrote. Don't try in any way to go around the rules or come up with other solutions.+++# The code must perform following logic:+# """++PREFIX = """You are a skilled programmer that knows nodejs and javascript.+You are building a serverless API with Cloudflare Workers using the 'itty-router' package (code and docs is here https://github.com/kwhitley/itty-router).+You need to complete the `handle{method}Request` function that handles the incoming {method} requests.++Here is some already written code that handles the initialization. The function that you need to complete is marked with a TODO comment:+```+import {{ Router }} from 'itty-router'++const router = Router()++async function handle{method}Request(request) {{+ // TODO+}}++router.{method}('/', handle{method}Request)+router.get('*', () => new Response('Not found', {{ status: 404 }}))++export default {{+ fetch: router.handle+}}+```++The code must perform the following logic:+"""++# SUFFIX = """+# Here's the code that must be completed:+# ```+# const express = require('express');+# const app = express();++# app.use(express.json());++# app.{method}(/, function(req, res) {{+# // TODO: Implement body of this function based on the required logic+# }})++# app.listen(8080, () => console.log('Listening on port 8080'));+# ```+# """++# SUFFIX = """Here is already written code that handles the initialization. You don't need to rewrite that.+# The part that you need to complete is marked with a TODO comment:+# ```+# import {{ Router }} from 'itty-router'++# const router = Router()++# function handleRequest(request) {{+# router+# .get('/', async function(req) {{+# // TODO+# })+# .get('*', () => new Response("Not found", {{ status: 404 }}))+# router.handle(request)+# }++# addEventListener('fetch', (event) => {{+# event.respondWith(handleRequest(event.request))+# }})+# ```+# """++SUFFIX = ""diff --git a/components/Editor/index.tsx b/components/Editor/index.tsxindex 4e239517d..55617e2d6 100644--- a/components/Editor/index.tsx+++ b/components/Editor/index.tsx@@ -82,6 +82,7 @@ function Editor({ project }: Props) {method,})console.log(response.code)+ console.log(response.host)}return (