AI Agent系列(八) -基于ReAct架构的前端开发助手(DeepSeek)

AI Agent系列【八】


项目目标

开发一个能够协助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。

python 复制代码
# 安装必要库
pip install openai flask python-dotenv requests json

3.2 定义AI前端生成的类

在这个类库中,需要考虑如下功能的实现:

  1. 初始化,需要实现基于LLM的API的客户端初始化,基于ReAct架构的提示词;
  2. 获取响应,基于LLM和系统提示词,用户输入的需求获取的响应信息;
  3. 响应解析,解析基于ReAct架构的响应;
  4. 生成html文件,基于响应的解析结果,生成html文件;
python 复制代码
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

python 复制代码
# Flask应用
app = Flask(__name__)
assistant = DeepSeekAICodeAssistant()

3.5 Flask路由

在路由中定义POST方法,当前端中输入了对应的需求后,将调用之前定义的获取响应和生成对应的html文件的功能。

当文件生成后,系统自动重定向到对应的文件进行代码的验证。

python 复制代码
@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即可。

python 复制代码
if __name__ == "__main__":
    app.run(debug=True)

四、 功能测试

代码执行后,在浏览器输入如下地址:http://127.0.0.1:5000,输入需求-生成一个科学计算器。
点击代码生成后,系统将调转到生成的网页,进行功能测试。

相关推荐
終不似少年遊*几秒前
国产之光DeepSeek架构理解与应用分析04
人工智能·python·深度学习·算法·大模型·ds
訾博ZiBo37 分钟前
AI日报 - 2025年4月23日
人工智能
羊小猪~~43 分钟前
深度学习基础--CNN经典网络之InceptionV3详解与复现(pytorch)
网络·人工智能·pytorch·python·深度学习·机器学习·cnn
筱小虾米1 小时前
Dify忘记管理员密码,重置的问题
人工智能·学习·dify
果冻人工智能1 小时前
人类终于打开了AI的黑箱!
人工智能
深度学习lover1 小时前
<项目代码>YOLO小船识别<目标检测>
人工智能·python·yolo·目标检测·计算机视觉·小船识别
Want5951 小时前
大模型安全吗?数据泄露与AI伦理的黑暗面!
网络·人工智能·安全·aigc
橙色小博1 小时前
RBF(径向基神经网络)基础解析与代码实例:拟合任意函数
人工智能·pytorch·深度学习·神经网络·rbf
飞哥数智坊1 小时前
艺术家的梦想要实现了?即梦3.0作品提示词
人工智能
九丘教育1 小时前
【仓颉 + 鸿蒙 + AI Agent】CangjieMagic框架(15):NaiveExecutor
人工智能·华为·harmonyos