python+deepseek v3 api实现类似cursor的AI编程助手代码

代码语言:python

所属分类:人工智能

代码描述:python+deepseek v3 api实现类似cursor的AI编程助手代码

代码标签: python deepseek v3 cursor AI 编程 助手 代码

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

#!/usr/local/python3/bin/python3
# -*- coding: utf-8 -*
from asynchat import async_chat
from itertools import tee
import os
import json
import re
import sys
from pathlib import Path
from typing import List, Dict
from openai import OpenAI

api_key
="sk-apikey"#api申请地址:https://platform.deepseek.com/api_keys
base_url
="https://api.deepseek.com"
main_model
="deepseek-chat"
code_model
="deepseek-chat"

class CodeAssistant:
   
def __init__(self, project_dir: str):
       
"""初始化代码助手"""
        self
.project_dir = Path(project_dir)
        self
.project_dir.mkdir(parents=True, exist_ok=True)
       
   
def _get_file_context(self) -> str:
       
"""获取项目目录中所有代码文件的内容作为上下文"""
        context
= []
       
for file_path in self.project_dir.rglob("*"):
           
if file_path.is_file() and file_path.suffix in [
               
'.php', '.js', '.html', '.css', '.json', '.py', '.java', '.cpp', '.c',
               
'.cs', '.rb', '.go', '.rs', '.ts', '.swift', '.kt', '.m', '.sh', '.xml',
               
'.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(self.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)

   
def _save_files(self, files: List[Dict[str, str]]):
       
"""保存生成的代码文件"""
       
for file_info in files:
            file_path
= self.project_dir / file_info['name']
            file_path
.parent.mkdir(parents=True, exist_ok=True)
            content
= file_info['content']

   
           
# 处理内容中的转义字符,将 \n 转换为实际的换行符
           
# content = file_info['content'].encode().decode('unicode_escape')
           
           
with open(file_path, 'w', encoding='utf-8') as f:
                f
.write(content)

           
if file_info['action']=="edit":
               
print(f"Updated file: {file_path}")
           
if file_info['action']=="add":
               
print(f"created file: {file_path}")
           
if file_info['action']=="del":
               
print(f"del file: {file_path}")
               
#content= self.megre_code(file_path,content)
           
           
    async
def talktoai(self, requirement: str):
       
"""根据需求判断是否修改或新增代码"""
        system_prompt
= """你是一个专业的代码助手。根据用户的需求文字,判断是否是只读还是写入操作。
        返回格式必须是一个JSON字符串:iswritecode: 是否需要生成、修改或新增代码。例如 :{"iswritecode": false}"""


        user_message
= f"用户需求:{requirement} "
       
#print(user_message)
        client
= OpenAI(
        api_key
=api_key,
        base_url
=base_url)
        response
=  client.chat.completions.create(
            model
=main_model,
            messages
=[
               
{"role": "system", "content": system_prompt},
               
{"role": "user", "content": user_message}
           
],
            temperature
=1,
            response_format
={ &qu.........完整代码请登录后点击上方下载按钮下载查看

网友评论0