项目目的
开发一个可以大概协助HTML+JS+CSS前端设计的AI Agent,通过在网页中输入相应的问题,此应用能自动天生对应的html文件设计的前端程序,并通过flask架构下实现自动跳转到对应界面来完成功能验证。
一、核心功能设计
AI Agent应该具备以下能力:
- 根据天然语言形貌天生前端代码
- 分析现有代码并提供优化建议
- 回答前端相干问题
- 自动修复常见错误
二、技能栈选择
- 语言模子: DeepSeek
- 开发框架: Flask
- 前端交互: html +CSS +JS
三、Python实现
3.1 设置基础情况
必要安装的工具包包罗LLM的API工具包openai,网页应用开发框架flask,dot的python情况python-dotenv,Json文件解析json。
- # 安装必要库
- pip install openai flask python-dotenv requests json
复制代码 3.2 界说AI前端天生的类
在这个类库中,必要考虑如下功能的实现:
- 初始化,必要实现基于LLM的API的客户端初始化,基于ReAct架构的提示词;
- 获取响应,基于LLM和体系提示词,用户输入的需求获取的响应信息;
- 响应解析,解析基于ReAct架构的响应;
- 天生html文件,基于响应的解析结果,天生html文件;
- import os
- from dotenv import load_dotenv
- from datetime import datetime
- from flask import Flask, request, render_template
- from openai import OpenAI
- import json
- load_dotenv()
- class DeepSeekAICodeAssistant:
- def __init__(self):
- self.api_key = os.getenv("DEEPSEEK_API_KEY")
- self.base_url = "https://api.deepseek.com"
- self.model = "deepseek-chat"
- self.client = OpenAI(api_key=self.api_key, base_url=self.base_url)
- self.context = []
- self.system_prompt = """
- 你是一个专业的前端开发助手,采用ReAct(Reasoning+Acting)架构工作。
- 请按照以下JSON格式响应:
- {
- "thought": "分析...",
- "action": "执行...",
- "code": "生成的代码...",
- "advice": "优化建议..."
- }
- """
- self._init_context()
- def _init_context(self):
- """初始化对话上下文"""
- self.context = [
- {"role": "system", "content": self.system_prompt}
- ]
- def generate_response(self, user_input):
- """
- 调用DeepSeek API生成响应
- :param user_input: 用户输入
- :return: 解析后的响应内容或错误信息
- """
- try:
- self.context.append({"role": "user", "content": user_input})
- response = self.client.chat.completions.create(
- model=self.model,
- messages=self.context,
- stream=False
- )
- assistant_reply = response.choices[0].message.content
- self.context.append({"role": "assistant", "content": assistant_reply})
- return self._parse_react_response(assistant_reply)
- except (KeyError, json.JSONDecodeError) as e:
- return {"error": f"响应解析失败: {str(e)}"}
- except Exception as e:
- return {"error": f"未知错误: {str(e)}"}
- def _parse_react_response(self, response_text):
- """解析ReAct格式的响应"""
- try:
- data = json.loads(response_text)
- return {
- "thought": data.get("thought", "无"),
- "action": data.get("action", "无"),
- "code": data.get("code", "无代码生成"),
- "advice": data.get("advice", "无优化建议")
- }
- except json.JSONDecodeError:
- return {
- "thought": "直接响应",
- "action": "生成代码",
- "code": response_text,
- "advice": ""
- }
- def generate_html_output(self, react_response, output_file="templates/output.html"):
- """生成HTML输出文件,仅保存生成的代码"""
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
- # 只提取代码部分
- generated_code = react_response.get('code', '无代码生成')
- html_template = f"""<!DOCTYPE html>
- <html>
- <head>
- <title>AI前端助手 - {timestamp}</title>
- <style>
- body {{ font-family: Arial, sans-serif; margin: 20px; }}
- pre {{ background: #eee; padding: 10px; overflow-x: auto; }}
- </style>
- </head>
- <body>
- <h1>生成的响应式导航栏</h1>
- <pre>{generated_code}</pre>
- </body>
- </html>"""
- os.makedirs(os.path.dirname(output_file), exist_ok=True)
- with open(output_file, "w", encoding="utf-8") as f:
- f.write(html_template)
- return output_file
-
复制代码 3.4 实例化
必要实例化flask和预界说的 DeepSeekAICodeAssistant
- # Flask应用
- app = Flask(__name__)
- assistant = DeepSeekAICodeAssistant()
复制代码 3.5 Flask路由
在路由中界说POST方法,当前端中输入了对应的需求后,将调用之前界说的获取响应和天生对应的html文件的功能。
当文件天生后,体系自动重定向到对应的文件举行代码的验证。
- @app.route("/", methods=["GET", "POST"])
- def index():
- if request.method == "POST":
- prompt = request.form.get("prompt")
- if prompt:
- result = assistant.generate_response(prompt)
- if "error" not in result:
- assistant.generate_html_output(result)
- return render_template("output.html")
- return f"<p style='color:red'>错误: {result['error']}</p>"
- return """
- <form method="POST">
- <h2>DeepSeek前端助手</h2>
- <textarea name="prompt" rows="5" cols="60" placeholder="输入你的前端需求..."></textarea><br>
- <button type="submit">生成代码</button>
- </form>
- """
复制代码 3.6 主程序实行
至此,我们只必要通过main函数实行flask即可。
- if __name__ == "__main__":
- app.run(debug=True)
复制代码 四、 功能测试
代码实行后,在浏览器输入如下地点:http://127.0.0.1:5000,输入需求-天生一个科学计算器。
点击代码天生后,体系将调转到天生的网页,举行功能测试。
AI Agent系列(八) -基于ReAct架构的前端开发助手(DeepSeek)
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |