python+qwen3-coder实现中大型项目源码编程助手cli示例代码

代码语言:python

所属分类:其他

代码描述:python+qwen3-coder实现中大型项目源码编程助手cli示例代码,支持ai代码变动自动备份,执行系统shell,多项目目录切换,对话记录保存等功能。

代码标签: python qwen3-coder 中大型 项目 源码 编程 助手 cli 示例 代码

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

#!/usr/local/python3/bin/python3
# -*- coding: utf-8 -*

# 导入 OpenAI
try:
    import openai
except ImportError:
    print("错误: 请先安装 openai 库 (pip install openai)", file=sys.stderr)
    sys.exit(1)

import os
import json
import re
import sys
import subprocess
from pathlib import Path
from typing import List, Dict, Tuple, Optional
from datetime import datetime
import shutil

# 导入并初始化 colorama
try:
    import colorama
    from colorama import Fore, Style, init
    init(autoreset=True) # 关键:让每次print后自动重置颜色
except ImportError:
    print("错误: 请先安装 colorama 库 (pip install colorama)", file=sys.stderr)
    sys.exit(1)

# --- 颜色定义类 ---
class C:
    """集中管理颜色代码,方便统一修改风格"""
    PROMPT = Fore.CYAN + Style.BRIGHT
    INFO = Fore.GREEN
    AI_DECISION = Fore.YELLOW
    ACTION = Fore.BLUE + Style.BRIGHT
    SUCCESS = Fore.GREEN + Style.BRIGHT
    WARN = Fore.YELLOW + Style.BRIGHT
    ERROR = Fore.RED + Style.BRIGHT
    AI_OUTPUT = Fore.WHITE + Style.BRIGHT
    CMD = Fore.YELLOW
    DESC = Fore.CYAN
    RESET = Style.RESET_ALL

# --- OpenAI API 配置 ---
try:
    openai_client = openai.Client(
      api_key="sk-", 
      base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", 
    )
    # 进行一次简单的API调用来验证密钥
    openai_client.models.list()
    print(C.SUCCESS + "OpenAI 客户端初始化并验证成功。")
except openai.AuthenticationError as e:
    print(C.ERROR + "OpenAI API 密钥无效或未设置,请检查。", file=sys.stderr)
    sys.exit(1)
except Exception as e:
    print(C.ERROR + f"OpenAI 客户端初始化失败: {e}", file=sys.stderr)
    sys.exit(1)


class CodeAssistant:
    def __init__(self, project_dir: str):
        """初始化代码助手"""
        self.project_dir = Path(project_dir).resolve()
        self.project_dir.mkdir(parents=True, exist_ok=True)
        
        # 版本控制和历史记录目录
        self.versions_dir = self.project_dir / ".versions"
        self.history_dir = self.project_dir / ".history"
        self.versions_dir.mkdir(exist_ok=True)
        self.history_dir.mkdir(exist_ok=True)

        self.custom_prompt = ""
        self._load_custom_prompt()
        
        # 切换为 OpenAI 模型
        self.decision_model = 'qwen-max'  # 用于决策的模型
        self.generation_model = 'qwen3-coder-plus' # 用于生成的模型 (可选: gpt-4-turbo, gpt-3.5-turbo)


    def _load_custom_prompt(self):
        """加载项目根目录下的 ai.rule 自定义提示词"""
        rule_file = self.project_dir / "ai.rule"
        self.custom_prompt = ""
        if rule_file.is_file():
            try:
                wit.........完整代码请登录后点击上方下载按钮下载查看

网友评论0