DeepSeek AI-Powered Code Generator with API
import os
import requests
import json
import subprocess
from flask import Flask, request, jsonify
# DeepSeek API Configuration
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"
API_KEY = "your_deepseek_api_key"
# Flask App Initialization
app = Flask(__name__)
def generate_code(prompt, model="deepseek-coder"):
"""
Uses DeepSeek API to generate Python code based on a given prompt.
"""
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}"
}
data = {
"model": model,
"messages": [
{"role": "system", "content": "You are an expert AI software developer."},
{"role": "user", "content": prompt}
],
"temperature": 0.7
}
response = requests.post(DEEPSEEK_API_URL, headers=headers, json=data)
response_json = response.json()
return response_json["choices"][0]["message"]["content"]
def save_code(filename, code):
"""
Saves generated code to a file.
"""
with open(filename, "w") as f:
f.write(code)
def execute_code(filename):
"""
Executes the generated code file.
"""
result = subprocess.run(["python", filename], capture_output=True, text=True)
return result.stdout, result.stderr
@app.route('/generate-code', methods=['POST'])
def generate_and_run():
"""
API Endpoint to generate and execute AI-generated code.
"""
data = request.get_json()
prompt = data.get("prompt", "Write a fully functional AI-powered microscope camera app
for skin analysis in Python.")
for i in range(5): # AI refines code over 5 iterations
print(f"Iteration {i+1}: Generating code...")
code = generate_code(prompt)
filename = f"generated_code_{i+1}.py"
save_code(filename, code)
print(f"Executing {filename}...")
output, error = execute_code(filename)
if error:
print(f"Error detected:\n{error}")
prompt += f"\nFix the following errors: {error}"
else:
print("Code executed successfully!\nOutput:", output)
return jsonify({"status": "success", "output": output, "generated_code": code})
return jsonify({"status": "error", "message": "Code generation failed after multiple
attempts."})
@app.route('/test-ai', methods=['GET'])
def test_ai():
"""
Simple API Test Endpoint.
"""
return jsonify({"status": "running", "message": "AI Code Generator API is active!"})
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=5000)