python+vue打造一个类似cursor的ai编程助手后端代码

代码语言:python

所属分类:其他

代码描述:python+vue打造一个类似cursor的ai编程助手后端代码

代码标签: python vue 打造 类似 cursor ai 编程 助手 后端 代码

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

#!/usr/local/python3/bin/python3
# -*- coding: utf-8 -*
from pathlib import Path
from flask import Flask, jsonify, request, send_from_directory, Response
import os
import shutil
from openai import OpenAI

#前端代码:https://blog.bfw.wiki/user12308/17365091279276340051.html
#https://code.bfw.wiki/code/17365097178752150072.html
app
= Flask(__name__)

# 根目录为当前脚本所在目录下的 file_manager 文件夹
BASE_DIR
= os.path.join(os.getcwd(), 'file_manager')

# 如果根目录不存在,则创建
if not os.path.exists(BASE_DIR):
    os
.makedirs(BASE_DIR)

@app.route('/')
def index():
   
return send_from_directory('static', 'index.html')



# API configuration
API_URL
= "https://api.deepseek.com"
API_KEY
= "sk-apikey"#自己去申请
MAIN_MODEL
= "deepseek-chat"

client
= OpenAI(api_key=API_KEY, base_url=API_URL)

def _get_file_context(project,files) -> str:
       
"""获取项目目录中所有代码文件的内容作为上下文"""
        context
= []
       

       
if files:
           
print(files)
           
           
for file in files:
                file_path
= file.get('path')
               
#file_name = file.get('name')
                file_handle
=Path(os.path.join(BASE_DIR, project,file_path))
               
print(file_handle)
               
try:
                   
with open(file_handle, 'r', encoding='utf-8') as f:
                        content
= f.read()
                        context
.append(f"File: {file_path}\n{content}\n")
               
except Exception as e:
                   
print(f"Error reading file {file_path}: {e}")
       
else:
           
# 生成目录结构树

           
            project_dir
= Path(os.path.join(BASE_DIR, project))
           
print("all")
           
def generate_tree(directory, prefix=""):
                tree
= []
                entries
= sorted(directory.iterdir())
               
for index, entry in enumerate(entries):
                   
if entry.is_dir():
                        tree
.append(f"{prefix}├── {entry.name}/")
                        tree
.extend(generate_tree(entry, prefix + "│   "))
                   
elif entry.is_file():
                        tree
.append(f"{prefix}├── {entry.name}")
               
return tree

           
# 生成目录结构树字符串
            tree_structure
= generate_tree(project_dir)
            tree_structure_str
= "\n".join(tree_structure)
            context
.append(f"Directory Structure:\n{tree_structure_str}\n")

           
# 合并指定类型的文件内容
           
for file_path in project_dir.rglob("*"):
               
if file_path.is_file() and file_path.suffix in [
                   
'.php', '.js', '.html', '.css', '.json', '.py', '.java', '.cpp', '.c', '.vue'
                   
'.cs', '.rb', '.go', '.rs', '.ts', '.swift', '.kt', '.m', '.sh', '.xml', '.txt','.md'
                   
'.yml', '.yaml', '.sql', '.r', '.pl', '.lua', '.scala', '.vb', '.hs',
                   
'.erl', '.ex', '.exs', '.dart', '.jl', '.f90', '.f95', '.f03', '.f08'
               
]:
                   
try:
                        relative_path
= file_path.relative_to(project_dir)
                       
with open(file_path, 'r', encoding='utf-8') as f:
                            content
= f.read()
                            context
.append(f"File: {relative_path}\n{content}\n")
                   
except Exception as e:
                       
print(f"Error reading file {file_path}: {e}")

       
return "\n".join(context)


@app.route('/list_directory', methods=['GET'])
def list_directory():
    path
= request.args.get('path', '')
    project
=  request.args.get('project', '')
    full_path
= os.path.join(BASE_DIR,project, path)
   
if not os.path.exists(full_path):
       
return jsonify({'error': 'Directory not found'}), 404

    items
= []
   
for item.........完整代码请登录后点击上方下载按钮下载查看

网友评论0