python+qwen3-coder+vue实现多项目ai对话生成ui原型图效果图应用代码

代码语言:python

所属分类:人工智能

代码描述:python+qwen3-coder+vue实现多项目ai对话生成ui原型图效果图应用代码

代码标签: python qwen coder vue 多项目 ai 对话 生成 ui 原型图 效果图

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

#!/usr/local/python3/bin/python3
# -*- coding: utf-8 -*
import os
import json
import uvicorn
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse, JSONResponse
from pydantic import BaseModel
from openai import OpenAI
from typing import List, Dict
import openai

# ##################################################################
# 配置部分
# ##################################################################

# --- OpenAI API 密钥 ---
# 强烈建议使用环境变量来管理密钥。
# 在这里替换为您自己的通义千问 API 密钥
OPENAI_API_KEY = "sk-" 

# --- UI原型项目数据存储目录 ---
PROJECTS_DIR = "ui_prototypes"
if not os.path.exists(PROJECTS_DIR):
    os.makedirs(PROJECTS_DIR)

# --- 初始化 FastAPI 应用 ---
app = FastAPI()

# --- 初始化 OpenAI 客户端 ---
try:
    client = openai.OpenAI(api_key=OPENAI_API_KEY, base_url="https://dashscope.aliyuncs.com/compatible-mode/v1")
except Exception as e:
    print(f"初始化 OpenAI 客户端时出错: {e}")
    client = None
# ##################################################################
# Pydantic 模型定义
# ##################################################################

class ChatRequest(BaseModel):
    """定义聊天请求的请求体结构"""
    message: str

# --- 新增 ---
# 用于接收前端确认后的最终需求文档
class RequirementsRequest(BaseModel):
    """定义提交最终需求文档的请求体结构。"""
    requirements: str

# ##################################################################
# 后端逻辑部分
# ##################################################################

@app.get("/api/projects", response_model=List[str])
async def get_projects():
    """获取所有已创建UI原型项目的列表。"""
    projects = [f.replace(".json", "") for f in os.listdir(PROJECTS_DIR) if f.endswith(".json")]
    return sorted(projects)

@app.post("/api/projects/{project_name}")
async def create_project(project_name: str):
    """创建一个新项目,并为其生成一个空的聊天记录 JSON 文件。"""
    if not project_name or not project_name.strip():
        raise HTTPException(status_code=400, detail="项目名称不能为空。")
    
    file_path = os.path.join(PROJECTS_DIR, f"{project_name}.json")
    if os.path.exists(file_path):
        raise HTTPException(status_code=400, detail="项目名称已存在,请换一个。")
    
    with open(file_path, 'w', encoding='utf-8') as f:
        json.dump([], f)
        
    return {"message": f"项目 '{project_name}' 创建成功。"}

@app.get("/api/chat/{project_name}", response_model=List[Dict])
async def get_chat_history(project_name: str):
    """获取指定项目的聊天历史记录。"""
    file_path = os.path.join(PROJECTS_DIR, f"{project_name}.json")
    if not os.path.exists(file_path):
        raise HTTPException(status_code=404, detail="项目未找到。")
    with open(file_path, 'r', encoding='utf-8') as f:
        return json.load(f)

# --- 新增 ---
# 第一步:根据用户初步想法生成详细的需求文档
@app.post("/api/chat/{project_name}/generate-requirements")
async def generate_requirements(project_name: str, request: ChatRequest):
    """接收用户初步想法,生成详细的需求文档,并返回给用户编辑。"""
    file_path = os.path.join(PROJECTS_DIR, f"{project_name}.json")
    if not os.path.exists(file_path):
        raise HTTPException(status_code=404, detail="项目未找到。")

    with open(file_path, 'r', encoding='utf-8') as f:
        chat_history = json.load(f)
    
    chat_history.append({"role": "user", "content": request.message})

    requirements_content = generate_requirements_with_openai(request.message)

    # 在AI返回的消息中增加一个 `is_requirements` 标志
    ai_response = {
        "role": "assistant", 
        "content": requirements_content,
        "is_requirements": True  # 这是给前端的信号
    }
    
    chat_history.append(ai_response)
    save_chat_history(project_name, chat_history)

    return JSONResponse(content={"chat_response": ai_response})

# --- 修改 ---
# 第二步:根据用户确认的需求文档生成画布式UI原型
@app.post("/api/chat/{project_name}/generate-prototype-from-requirements")
async def generate_prototype_from_requirements(project_name: str, request: RequirementsRequest):
    """接收用户确认的需求文档,生成可拖拽、缩放的平铺式UI原型。"""
    file_path = os.path.join(PROJECTS_DIR, f"{project_name}.json")
    if not os.path.exists(file_path):
        raise HTTPException(status_code=404, detail="项目未找到。")

    with open(file_path, 'r', encoding='utf-8') as f:
        chat_history = json.load(f)
    
    # 更新聊天记录中最后一条AI消息(即需求文档)的内容为用户最终确认的版本
    for message in reversed(chat_history):
        if message.get("is_requirements"):
            message["content"] = request.requirements
            message["is_requirements"] = False # 锁定,不再是可编辑状态
            break
            
    # 使用最终的需求文档来生成HTML
    generated_html = generate_ui_prototype_with_openai(request.requirements)

    ai_response_message = "UI原型已生成!您可以在右侧的画布中拖拽和缩放来查看所有页面。"
    ai_chat_response = {"role": "assistant", "content": ai_response_message}
    
    full_ai_response_for_saving = .........完整代码请登录后点击上方下载按钮下载查看

网友评论0