Add support to use LLM's (gemni) to create functions, also create documentation page

This commit is contained in:
Peter Stockings
2025-06-21 19:04:00 +10:00
parent 525471d8c0
commit 917189b3d9
4 changed files with 610 additions and 186 deletions

113
app.py
View File

@@ -114,6 +114,10 @@ def map_isolator_response_to_flask_response(response):
def home():
return render_template("home.html", name='Try me', script=DEFAULT_SCRIPT, environment_info=DEFAULT_ENVIRONMENT)
@app.route("/documentation", methods=["GET"])
def documentation():
return render_template("documentation.html")
@ app.route("/dashboard", methods=["GET"])
@login_required
def dashboard():
@@ -257,6 +261,115 @@ def get_http_function_history(function_id):
return render_block(app.jinja_env, 'dashboard/http_functions/history.html', 'page', user_id=user_id, function_id=function_id, name=name, http_function=http_function, http_function_history=http_function_history, original_script=original_script)
return render_template("dashboard/http_functions/history.html", user_id=user_id, name=name, function_id=function_id, http_function=http_function, http_function_history=http_function_history, original_script=original_script)
def _generate_script_from_natural_language(natural_query):
"""Generates a Javascript function from natural language using Gemini REST API."""
gemni_model = os.environ.get("GEMINI_MODEL", "gemini-1.5-flash")
api_key = os.environ.get("GEMINI_API_KEY")
if not api_key:
return None, "GEMINI_API_KEY environment variable not set."
api_url = f"https://generativelanguage.googleapis.com/v1beta/models/{gemni_model}:generateContent?key={api_key}"
headers = {'Content-Type': 'application/json'}
try:
prompt = f"""
You are an expert Javascript developer. Your task is to write a complete, production-ready Javascript async function based on the user's request.
**Environment & Constraints:**
- The function will be executed in a simple, sandboxed Javascript environment.
- **DO NOT** use `require()`, `import`, or any other module loading system. The environment does not support it.
- **DO NOT** access the file system (`fs` module) or make network requests.
- The function must be a single `async` arrow function.
- You have access to a persistent JSON object called `environment`. You can read from and write to it. For example: `environment.my_variable = 'hello'`.
- You also have access to a `console.log()` function for logging.
**Input:**
The function receives one argument: `req`, an object containing details about the incoming HTTP request. It has properties like `req.method`, `req.headers`, `req.body`, `req.query`, etc.
**Output:**
You must use one of the following helper functions to return a response:
- `HtmlResponse(body)`: Returns an HTML response.
- `JsonResponse(body)`: Returns a JSON response. The `body` will be automatically stringified.
- `TextResponse(body)`: Returns a plain text response.
- `RedirectResponse(url)`: Redirects the user to a different URL.
**Example:**
```javascript
async (req) => {{
if (!environment.counter) {{
environment.counter = 0;
}}
environment.counter++;
console.log("The counter is now " + environment.counter);
return HtmlResponse(`<h1>Counter: ${{environment.counter}}</h1>`);
}}
```
**User's request:** "{natural_query}"
Return ONLY the complete Javascript function code, without any explanation, comments, or surrounding text/markdown.
"""
payload = json.dumps({
"contents": [{"parts": [{"text": prompt}]}]
})
response = requests.post(api_url, headers=headers, data=payload)
response.raise_for_status()
response_data = response.json()
candidates = response_data.get('candidates', [])
if not candidates:
return None, "No candidates found in API response."
content = candidates[0].get('content', {})
parts = content.get('parts', [])
if not parts:
return None, "No parts found in API response content."
generated_script = parts[0].get('text', '').strip()
# More robustly extract from markdown
if generated_script.startswith("```javascript"):
generated_script = generated_script[12:]
if generated_script.endswith("```"):
generated_script = generated_script[:-3]
generated_script = generated_script.strip()
# Remove any leading non-code characters
if not generated_script.startswith('async ('):
async_start = generated_script.find('async (')
if async_start != -1:
generated_script = generated_script[async_start:]
return generated_script.strip(), None
except requests.exceptions.RequestException as e:
app.logger.error(f"Gemini API request error: {e}")
return None, f"Error communicating with API: {e}"
except (KeyError, IndexError, Exception) as e:
app.logger.error(f"Error processing Gemini API response: {e} - Response: {response_data if 'response_data' in locals() else 'N/A'}")
return None, f"Error processing API response: {e}"
@app.route("/api/generate_script", methods=["POST"])
@login_required
def generate_script():
try:
natural_query = request.json.get('natural_query')
if not natural_query:
return jsonify({"error": "natural_query is required"}), 400
script_content, error = _generate_script_from_natural_language(natural_query)
if error:
return jsonify({"error": error}), 500
return jsonify({"script_content": script_content})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/execute', methods=['POST'])
def execute_code():
try: