python+openai兼容api实现项目文件ai编程助手代码

代码语言:python

所属分类:其他

代码描述:python+openai兼容api实现项目文件ai编程助手代码

代码标签: python openai 兼容 api 项目 文件 ai 编程 助手 代码

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

#!/usr/local/python3/bin/python3
# -*- coding: utf-8 -*
from google import genai
from google.genai import types
import os
import json
import re
import sys
import subprocess
from pathlib import Path
from typing import List, Dict
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

# --- Gemini API 配置 ---
# 请将 "" 替换为您的真实 API 密钥
try:
    gemini_client = genai.Client(
      api_key="", # <-- 在此处填入你的API Key
    )
    print(C.SUCCESS + "Gemini 客户端初始化成功。")
except Exception as e:
    print(C.ERROR + f"Gemini 客户端初始化失败: {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.versions_dir.mkdir(exist_ok=True)
        
        self.custom_prompt = ""
        self._load_custom_prompt()
        
        self.decision_model = 'gemini-2.0-flash' # 建议使用更快的模型做决策
        self.generation_model = 'gemini-2.0-flash' # 建议使用 Flash 或 Pro

    def _load_custom_prompt(self):
        """加载项目根目录下的 ai.rule 自定义提示词"""
        rule_file = self.project_dir / "ai.rule"
        self.custom_prompt = ""
        if rule_file.is_file():
            try:
                with open(rule_file, 'r', encoding='utf-8') as f:
                    self.custom_prompt = f.read().strip()
                if self.custom_prompt:
                    print(C.SUCCESS + "已成功加载自定义提示词 ai.rule。")
            except Exception as e:
                print(C.ERROR + f"读取 ai.rule 文件时出错: {e}", file=sys.stderr)

    def _get_text_file_extensions(self) -> set:
        return {
            '.php', '.sql', '.js', '.html', '.css', '.json', '.py', '.java', '.cpp', '.c.........完整代码请登录后点击上方下载按钮下载查看

网友评论0