Initial commit: AI Shell v0.1.0
- AI-powered shell command generator using DeepSeek V3 - Support for natural language to shell command conversion - Secure configuration management with .env files - Package structure with uv tool installation support - Chinese and English language support - Configuration validation and error handling
This commit is contained in:
11
.env.example
Normal file
11
.env.example
Normal file
@ -0,0 +1,11 @@
|
||||
# AI Shell 配置文件模板
|
||||
# 复制此文件为 .env 并填入您的实际配置
|
||||
|
||||
# API 配置(必填)
|
||||
AI_SHELL_API_KEY=your_api_key_here
|
||||
AI_SHELL_BASE_URL=https://your-api-endpoint.com/v3/
|
||||
AI_SHELL_MODEL=your_model_name
|
||||
|
||||
# 可选配置
|
||||
# AI_SHELL_TIMEOUT=30
|
||||
# AI_SHELL_MAX_RETRIES=3
|
272
.gitignore
vendored
Normal file
272
.gitignore
vendored
Normal file
@ -0,0 +1,272 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
#pdm.lock
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||
# in version control.
|
||||
# https://pdm.fming.dev/#use-with-ide
|
||||
.pdm.toml
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be added to the global gitignore or merged into this project gitignore. For a PyCharm
|
||||
# project, it is recommended to include the following files in version control:
|
||||
# *.iml
|
||||
# modules.xml
|
||||
# .idea/misc.xml
|
||||
# .idea/modules.xml
|
||||
# .idea/vcs.xml
|
||||
# .idea/workspace.xml
|
||||
# .idea/tasks.xml
|
||||
# .idea/dictionaries
|
||||
# .idea/shelf
|
||||
#
|
||||
# # AWS User-specific
|
||||
# .idea/**/aws.xml
|
||||
#
|
||||
# # Generated files
|
||||
# .idea/**/contentModel.xml
|
||||
#
|
||||
# # Sensitive or high-churn files
|
||||
# .idea/**/dataSources/
|
||||
# .idea/**/dataSources.ids
|
||||
# .idea/**/dataSources.local.xml
|
||||
# .idea/**/sqlDataSources.xml
|
||||
# .idea/**/dynamic.xml
|
||||
# .idea/**/uiDesigner.xml
|
||||
# .idea/**/dbnavigator.xml
|
||||
#
|
||||
# # Gradle
|
||||
# .idea/**/gradle.xml
|
||||
# .idea/**/libraries
|
||||
#
|
||||
# # Gradle and Maven with auto-import
|
||||
# # When using Gradle or Maven with auto-import, you should exclude module files,
|
||||
# # since they will be recreated, and may cause churn. Uncomment if using
|
||||
# # auto-import.
|
||||
# # .idea/artifacts
|
||||
# # .idea/compiler.xml
|
||||
# # .idea/jarRepositories.xml
|
||||
# # .idea/modules.xml
|
||||
# # .idea/*.iml
|
||||
# # .idea/modules
|
||||
# # *.iml
|
||||
# # *.ipr
|
||||
|
||||
# CMake
|
||||
cmake-build-*/
|
||||
|
||||
# Mongo Explorer plugin
|
||||
.idea/**/mongoSettings.xml
|
||||
|
||||
# File-based project format
|
||||
*.iws
|
||||
|
||||
# IntelliJ
|
||||
out/
|
||||
|
||||
# mpeltonen/sbt-idea plugin
|
||||
.idea_modules/
|
||||
|
||||
# JIRA plugin
|
||||
atlassian-ide-plugin.xml
|
||||
|
||||
# Cursive Clojure plugin
|
||||
.idea/replstate.xml
|
||||
|
||||
# SonarLint plugin
|
||||
.idea/sonarlint/
|
||||
|
||||
# Crashlytics plugin (for Android Studio and IntelliJ)
|
||||
com_crashlytics_export_strings.xml
|
||||
crashlytics.properties
|
||||
crashlytics-build.properties
|
||||
fabric.properties
|
||||
|
||||
# Editor-based Rest Client
|
||||
.idea/httpRequests
|
||||
|
||||
# Android studio 3.1+ serialized cache file
|
||||
.idea/caches/build_file_checksums.ser
|
||||
|
||||
# UV specific
|
||||
.uv_cache/
|
||||
|
||||
# macOS
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
# Thumbnails
|
||||
._*
|
||||
|
||||
# Files that might appear in the root of a volume
|
||||
.DocumentRevisions-V100
|
||||
.fseventsd
|
||||
.Spotlight-V100
|
||||
.TemporaryItems
|
||||
.Trashes
|
||||
.VolumeIcon.icns
|
||||
.com.apple.timemachine.donotpresent
|
||||
|
||||
# Directories potentially created on remote AFP share
|
||||
.AppleDB
|
||||
.AppleDesktop
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
# Project specific
|
||||
dist/
|
||||
build/
|
||||
*.egg-info/
|
||||
.venv/
|
||||
.python-version
|
||||
~
|
64
Makefile
Normal file
64
Makefile
Normal file
@ -0,0 +1,64 @@
|
||||
.PHONY: help install upgrade uninstall build clean test bump-patch bump-minor bump-major
|
||||
|
||||
help:
|
||||
@echo "AI Shell Development Commands:"
|
||||
@echo ""
|
||||
@echo " install - Install AI Shell globally using uv tool"
|
||||
@echo " upgrade - Upgrade existing AI Shell installation"
|
||||
@echo " uninstall - Uninstall AI Shell"
|
||||
@echo " build - Build the package"
|
||||
@echo " clean - Clean build artifacts"
|
||||
@echo " test - Test the installation"
|
||||
@echo " bump-patch - Bump patch version (0.1.0 -> 0.1.1)"
|
||||
@echo " bump-minor - Bump minor version (0.1.0 -> 0.2.0)"
|
||||
@echo " bump-major - Bump major version (0.1.0 -> 1.0.0)"
|
||||
|
||||
install:
|
||||
@echo "🚀 Installing AI Shell..."
|
||||
@uv build
|
||||
@uv tool install . --force
|
||||
@echo "✅ AI Shell installed successfully!"
|
||||
|
||||
upgrade: bump-patch install
|
||||
@echo "✅ AI Shell upgraded successfully!"
|
||||
|
||||
quick-upgrade:
|
||||
@echo "🔄 Quick upgrade (patch version)..."
|
||||
@./quick_upgrade.sh
|
||||
|
||||
uninstall:
|
||||
@echo "🗑️ Uninstalling AI Shell..."
|
||||
@uv tool uninstall ai-shell || true
|
||||
@echo "✅ AI Shell uninstalled"
|
||||
|
||||
build:
|
||||
@echo "📦 Building package..."
|
||||
@uv build
|
||||
|
||||
clean:
|
||||
@echo "🧹 Cleaning build artifacts..."
|
||||
@rm -rf dist/
|
||||
@rm -rf build/
|
||||
@rm -rf *.egg-info/
|
||||
@echo "✅ Clean complete"
|
||||
|
||||
test:
|
||||
@echo "🧪 Testing AI Shell installation..."
|
||||
@ai --version
|
||||
@ai --config
|
||||
@echo "✅ Test complete"
|
||||
|
||||
bump-patch:
|
||||
@echo "📈 Bumping patch version..."
|
||||
@python scripts/bump_version.py patch
|
||||
@echo "✅ Version bumped"
|
||||
|
||||
bump-minor:
|
||||
@echo "📈 Bumping minor version..."
|
||||
@python scripts/bump_version.py minor
|
||||
@echo "✅ Version bumped"
|
||||
|
||||
bump-major:
|
||||
@echo "📈 Bumping major version..."
|
||||
@python scripts/bump_version.py major
|
||||
@echo "✅ Version bumped"
|
42
README.md
Normal file
42
README.md
Normal file
@ -0,0 +1,42 @@
|
||||
# AI Shell
|
||||
|
||||
AI-powered shell command generator using DeepSeek V3 model via OpenAI-compatible API.
|
||||
|
||||
## Features
|
||||
|
||||
- Generate shell commands from natural language descriptions
|
||||
- Interactive execution confirmation (Enter to execute, n to cancel)
|
||||
- Supports multiple languages for prompts and responses
|
||||
- Uses DeepSeek V3 model for high-quality command generation
|
||||
- User-friendly interface with default execution on Enter
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
uv run python ai.py "your command description here"
|
||||
```
|
||||
|
||||
## Setup
|
||||
|
||||
1. Install dependencies:
|
||||
```bash
|
||||
uv sync
|
||||
```
|
||||
|
||||
2. Run the tool:
|
||||
```bash
|
||||
uv run python ai.py "list all files in current directory"
|
||||
uv run python ai.py "show disk usage"
|
||||
uv run python ai.py "find all Python files"
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
- **Model**: DeepSeek V3 (deepseek-v3-250324)
|
||||
- **API**: Volces (ByteDance) OpenAI-compatible interface
|
||||
- **Base URL**: https://ark.cn-beijing.volces.com/api/v3/
|
||||
|
||||
## Requirements
|
||||
|
||||
- Python 3.12+
|
||||
- UV package manager with configured Chinese mirrors for fast downloads
|
14
ai_shell/__init__.py
Normal file
14
ai_shell/__init__.py
Normal file
@ -0,0 +1,14 @@
|
||||
"""
|
||||
AI Shell - AI-powered shell command generator using DeepSeek V3
|
||||
|
||||
A command-line tool that generates shell commands from natural language descriptions.
|
||||
"""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
__author__ = "AI Shell Team"
|
||||
__email__ = "ai-shell@example.com"
|
||||
__description__ = "AI-powered shell command generator using DeepSeek V3"
|
||||
|
||||
from .main import main
|
||||
|
||||
__all__ = ["main"]
|
74
ai_shell/agent.py
Normal file
74
ai_shell/agent.py
Normal file
@ -0,0 +1,74 @@
|
||||
"""
|
||||
AI Agent module for shell command generation
|
||||
"""
|
||||
|
||||
from textwrap import dedent
|
||||
from pydantic_ai import Agent
|
||||
from pydantic_ai.models.openai import OpenAIModel
|
||||
|
||||
from .config import get_model, setup_environment
|
||||
from .models import Answer
|
||||
|
||||
# System prompt for the AI agent
|
||||
SYSTEM_PROMPT = dedent(
|
||||
"""\
|
||||
You are a professional developer specializing in shell commands.
|
||||
Your task is to generate the correct shell commands based on the
|
||||
user's request.
|
||||
|
||||
IMPORTANT: ALWAYS USE THE SAME LANGUAGE AS THE USER PROMPT IN
|
||||
YOUR RESPONSE.
|
||||
|
||||
Process:
|
||||
|
||||
1. Think Aloud: Use the `think` function to explain your reasoning.
|
||||
Justify why you chose a particular command, considering efficiency,
|
||||
safety, and best practices.
|
||||
|
||||
2. Provide the Final Command: Use the `answer` function to present
|
||||
the final shell command concisely.
|
||||
"""
|
||||
)
|
||||
|
||||
def create_agent() -> Agent:
|
||||
"""Create and configure the AI agent"""
|
||||
# Setup environment variables
|
||||
setup_environment()
|
||||
|
||||
# Create OpenAI compatible model
|
||||
model = OpenAIModel(get_model())
|
||||
|
||||
# Create agent
|
||||
agent = Agent(
|
||||
model=model,
|
||||
system_prompt=SYSTEM_PROMPT,
|
||||
output_type=Answer,
|
||||
)
|
||||
|
||||
# Register tools
|
||||
@agent.tool_plain
|
||||
def think(s: str) -> None:
|
||||
"""Communicate your thought process to the user.
|
||||
|
||||
Args:
|
||||
s (str): A description of your reasoning or decision-making process.
|
||||
"""
|
||||
print(f"(AI Thinking): {s}\n")
|
||||
|
||||
@agent.tool_plain
|
||||
def answer(success: bool, cmd: str | None, failure: str | None) -> Answer:
|
||||
"""Provide the final shell command or explain why it couldn't be generated.
|
||||
|
||||
Args:
|
||||
success (bool): Indicates whether a shell command was successfully generated.
|
||||
cmd (str | None): The generated shell command if `success` is True.
|
||||
It must be a single-line command. If `success` is False, this should be None.
|
||||
failure (str | None): If `success` is False, provide a reason why the command
|
||||
could not be generated. If `success` is True, this should be None.
|
||||
|
||||
Returns:
|
||||
Answer: A structured response that will be processed for the user.
|
||||
"""
|
||||
return Answer(success, cmd, failure)
|
||||
|
||||
return agent
|
77
ai_shell/config.py
Normal file
77
ai_shell/config.py
Normal file
@ -0,0 +1,77 @@
|
||||
"""
|
||||
Configuration module for AI Shell
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
except ImportError:
|
||||
load_dotenv = None
|
||||
|
||||
# Load .env file if it exists
|
||||
def load_env_file() -> None:
|
||||
"""Load environment variables from .env file"""
|
||||
if load_dotenv is None:
|
||||
return
|
||||
|
||||
# Try to find .env file in current directory or package directory
|
||||
env_paths = [
|
||||
Path.cwd() / ".env",
|
||||
Path(__file__).parent.parent / ".env",
|
||||
Path.home() / ".ai-shell" / ".env",
|
||||
]
|
||||
|
||||
for env_path in env_paths:
|
||||
if env_path.exists():
|
||||
load_dotenv(env_path)
|
||||
break
|
||||
|
||||
# Load .env file on import
|
||||
load_env_file()
|
||||
|
||||
# Default API configuration (fallback values)
|
||||
DEFAULT_API_KEY = "your_api_key_here"
|
||||
DEFAULT_BASE_URL = "https://api.openai.com/v1/"
|
||||
DEFAULT_MODEL = "gpt-3.5-turbo"
|
||||
|
||||
def get_api_key() -> str:
|
||||
"""Get API key from environment or use default"""
|
||||
api_key = os.getenv("AI_SHELL_API_KEY", DEFAULT_API_KEY)
|
||||
if api_key == DEFAULT_API_KEY:
|
||||
raise ValueError(
|
||||
"API key not configured. Please set AI_SHELL_API_KEY in .env file or environment variable."
|
||||
)
|
||||
return api_key
|
||||
|
||||
def get_base_url() -> str:
|
||||
"""Get base URL from environment or use default"""
|
||||
return os.getenv("AI_SHELL_BASE_URL", DEFAULT_BASE_URL)
|
||||
|
||||
def get_model() -> str:
|
||||
"""Get model name from environment or use default"""
|
||||
return os.getenv("AI_SHELL_MODEL", DEFAULT_MODEL)
|
||||
|
||||
def get_timeout() -> int:
|
||||
"""Get request timeout from environment"""
|
||||
return int(os.getenv("AI_SHELL_TIMEOUT", "30"))
|
||||
|
||||
def get_max_retries() -> int:
|
||||
"""Get max retries from environment"""
|
||||
return int(os.getenv("AI_SHELL_MAX_RETRIES", "3"))
|
||||
|
||||
def setup_environment() -> None:
|
||||
"""Setup environment variables for OpenAI client"""
|
||||
os.environ["OPENAI_API_KEY"] = get_api_key()
|
||||
os.environ["OPENAI_BASE_URL"] = get_base_url()
|
||||
|
||||
def validate_config() -> bool:
|
||||
"""Validate configuration"""
|
||||
try:
|
||||
get_api_key()
|
||||
get_base_url()
|
||||
get_model()
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
140
ai_shell/main.py
Normal file
140
ai_shell/main.py
Normal file
@ -0,0 +1,140 @@
|
||||
"""
|
||||
Main entry point for AI Shell
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import argparse
|
||||
from typing import List, Optional
|
||||
|
||||
from .agent import create_agent
|
||||
from . import __version__
|
||||
|
||||
def execute_command(command: str) -> None:
|
||||
"""Execute a shell command"""
|
||||
os.system(command)
|
||||
|
||||
def get_user_confirmation(command: str) -> bool:
|
||||
"""Get user confirmation before executing command"""
|
||||
print(f"(AI Answer): {command}")
|
||||
response = input("Execute? [Y/n]: ").strip().lower()
|
||||
return response in ["", "y", "yes"]
|
||||
|
||||
def process_prompt(prompt: str) -> None:
|
||||
"""Process user prompt and generate shell command"""
|
||||
if not prompt.strip():
|
||||
print("Error: No prompt provided")
|
||||
sys.exit(1)
|
||||
|
||||
# Create AI agent
|
||||
agent = create_agent()
|
||||
|
||||
try:
|
||||
# Generate response
|
||||
resp = agent.run_sync(prompt)
|
||||
answer = resp.output
|
||||
|
||||
if answer.success and answer.cmd is not None:
|
||||
if get_user_confirmation(answer.cmd):
|
||||
execute_command(answer.cmd)
|
||||
else:
|
||||
print(f"(AI Answer): {answer.failure}")
|
||||
print("Command generation failed")
|
||||
sys.exit(1)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
def create_parser() -> argparse.ArgumentParser:
|
||||
"""Create command line argument parser"""
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="ai",
|
||||
description="AI-powered shell command generator using DeepSeek V3",
|
||||
epilog="Examples:\n"
|
||||
" ai list files\n"
|
||||
" ai \"show disk usage\"\n"
|
||||
" ai 显示当前目录\n",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"prompt",
|
||||
nargs="*",
|
||||
help="Natural language description of the command you want"
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--version",
|
||||
action="version",
|
||||
version=f"ai-shell {__version__}"
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--config",
|
||||
action="store_true",
|
||||
help="Show current configuration"
|
||||
)
|
||||
|
||||
return parser
|
||||
|
||||
def show_config() -> None:
|
||||
"""Show current configuration"""
|
||||
from .config import get_api_key, get_base_url, get_model, get_timeout, get_max_retries, validate_config
|
||||
|
||||
print("AI Shell Configuration:")
|
||||
print(f" Model: {get_model()}")
|
||||
print(f" Base URL: {get_base_url()}")
|
||||
|
||||
try:
|
||||
api_key = get_api_key()
|
||||
print(f" API Key: {api_key[:8]}...{api_key[-4:]}")
|
||||
except ValueError as e:
|
||||
print(f" API Key: ❌ {e}")
|
||||
|
||||
print(f" Timeout: {get_timeout()}s")
|
||||
print(f" Max Retries: {get_max_retries()}")
|
||||
|
||||
print(f"\nConfiguration Status: {'✅ Valid' if validate_config() else '❌ Invalid'}")
|
||||
|
||||
print("\nConfiguration Sources (in priority order):")
|
||||
print(" 1. Environment variables")
|
||||
print(" 2. .env file in current directory")
|
||||
print(" 3. .env file in package directory")
|
||||
print(" 4. ~/.ai-shell/.env file")
|
||||
print(" 5. Default values")
|
||||
|
||||
print("\nEnvironment Variables:")
|
||||
print(" AI_SHELL_API_KEY - API key")
|
||||
print(" AI_SHELL_BASE_URL - API base URL")
|
||||
print(" AI_SHELL_MODEL - Model name")
|
||||
print(" AI_SHELL_TIMEOUT - Request timeout (seconds)")
|
||||
print(" AI_SHELL_MAX_RETRIES - Maximum retry attempts")
|
||||
|
||||
def main() -> None:
|
||||
"""Main entry point"""
|
||||
parser = create_parser()
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.config:
|
||||
show_config()
|
||||
return
|
||||
|
||||
if not args.prompt:
|
||||
parser.print_help()
|
||||
sys.exit(1)
|
||||
|
||||
# Validate configuration before processing
|
||||
from .config import validate_config
|
||||
if not validate_config():
|
||||
print("❌ Configuration error: API key not configured.")
|
||||
print("Please set AI_SHELL_API_KEY in .env file or environment variable.")
|
||||
print("Run 'ai --config' to see current configuration.")
|
||||
sys.exit(1)
|
||||
|
||||
# Join all prompt arguments into a single string
|
||||
prompt = " ".join(args.prompt)
|
||||
process_prompt(prompt)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
13
ai_shell/models.py
Normal file
13
ai_shell/models.py
Normal file
@ -0,0 +1,13 @@
|
||||
"""
|
||||
Data models for AI Shell
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
@dataclass
|
||||
class Answer:
|
||||
"""Response model for AI-generated shell commands"""
|
||||
success: bool
|
||||
cmd: Optional[str]
|
||||
failure: Optional[str]
|
46
pyproject.toml
Normal file
46
pyproject.toml
Normal file
@ -0,0 +1,46 @@
|
||||
[project]
|
||||
name = "ai-shell"
|
||||
version = "0.1.0"
|
||||
description = "AI-powered shell command generator using DeepSeek V3"
|
||||
authors = [
|
||||
{name = "AI Shell Team", email = "ai-shell@example.com"}
|
||||
]
|
||||
readme = "README.md"
|
||||
license = {text = "MIT"}
|
||||
keywords = ["ai", "shell", "command", "generator", "deepseek"]
|
||||
classifiers = [
|
||||
"Development Status :: 4 - Beta",
|
||||
"Intended Audience :: Developers",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Topic :: Software Development :: Libraries :: Python Modules",
|
||||
"Topic :: System :: Shells",
|
||||
]
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"pydantic-ai",
|
||||
"openai",
|
||||
"requests>=2.32.4",
|
||||
"python-dotenv>=1.0.0",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
ai = "ai_shell.main:main"
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://github.com/your-username/ai-shell"
|
||||
Repository = "https://github.com/your-username/ai-shell"
|
||||
Issues = "https://github.com/your-username/ai-shell/issues"
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["ai_shell"]
|
||||
|
||||
[tool.hatch.version]
|
||||
path = "ai_shell/__init__.py"
|
||||
|
||||
# UV 配置已移至 uv.toml 文件
|
36
quick_upgrade.sh
Executable file
36
quick_upgrade.sh
Executable file
@ -0,0 +1,36 @@
|
||||
#!/bin/bash
|
||||
# AI Shell 快速升级脚本
|
||||
|
||||
set -e
|
||||
|
||||
echo "🔄 AI Shell 快速升级..."
|
||||
|
||||
# 检查是否在项目目录
|
||||
if [ ! -f "pyproject.toml" ]; then
|
||||
echo "❌ 请在 ai-shell 项目目录中运行此脚本"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 升级补丁版本
|
||||
echo "📈 升级版本..."
|
||||
python scripts/bump_version.py patch
|
||||
|
||||
# 重新构建
|
||||
echo "📦 重新构建..."
|
||||
uv build
|
||||
|
||||
# 重新安装
|
||||
echo "🔧 重新安装..."
|
||||
uv tool install . --force
|
||||
|
||||
# 验证
|
||||
echo "✅ 升级完成!"
|
||||
echo ""
|
||||
echo "新版本信息:"
|
||||
ai --version
|
||||
|
||||
echo ""
|
||||
echo "🧪 可以测试以下命令:"
|
||||
echo " ai --config"
|
||||
echo " ai \"echo test\""
|
||||
echo " ai \"list files\""
|
64
scripts/bump_version.py
Executable file
64
scripts/bump_version.py
Executable file
@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Version bumping script for ai-shell
|
||||
"""
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
def bump_version(version_type: str = "patch") -> None:
|
||||
"""Bump version in __init__.py and pyproject.toml"""
|
||||
|
||||
# Read current version from __init__.py
|
||||
init_file = Path("ai_shell/__init__.py")
|
||||
init_content = init_file.read_text()
|
||||
|
||||
# Extract current version
|
||||
version_match = re.search(r'__version__ = "([^"]+)"', init_content)
|
||||
if not version_match:
|
||||
print("Error: Could not find version in __init__.py")
|
||||
sys.exit(1)
|
||||
|
||||
current_version = version_match.group(1)
|
||||
major, minor, patch = map(int, current_version.split('.'))
|
||||
|
||||
# Bump version
|
||||
if version_type == "major":
|
||||
major += 1
|
||||
minor = 0
|
||||
patch = 0
|
||||
elif version_type == "minor":
|
||||
minor += 1
|
||||
patch = 0
|
||||
elif version_type == "patch":
|
||||
patch += 1
|
||||
else:
|
||||
print(f"Error: Invalid version type '{version_type}'. Use 'major', 'minor', or 'patch'")
|
||||
sys.exit(1)
|
||||
|
||||
new_version = f"{major}.{minor}.{patch}"
|
||||
|
||||
# Update __init__.py
|
||||
new_init_content = re.sub(
|
||||
r'__version__ = "[^"]+"',
|
||||
f'__version__ = "{new_version}"',
|
||||
init_content
|
||||
)
|
||||
init_file.write_text(new_init_content)
|
||||
|
||||
# Update pyproject.toml
|
||||
pyproject_file = Path("pyproject.toml")
|
||||
pyproject_content = pyproject_file.read_text()
|
||||
new_pyproject_content = re.sub(
|
||||
r'version = "[^"]+"',
|
||||
f'version = "{new_version}"',
|
||||
pyproject_content
|
||||
)
|
||||
pyproject_file.write_text(new_pyproject_content)
|
||||
|
||||
print(f"Version bumped from {current_version} to {new_version}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
version_type = sys.argv[1] if len(sys.argv) > 1 else "patch"
|
||||
bump_version(version_type)
|
33
uv.toml
Normal file
33
uv.toml
Normal file
@ -0,0 +1,33 @@
|
||||
# uv 项目配置文件
|
||||
# 配置国内镜像源加速下载
|
||||
|
||||
# 主要的 PyPI 镜像源
|
||||
index-url = "https://pypi.tuna.tsinghua.edu.cn/simple"
|
||||
|
||||
# 额外的镜像源
|
||||
extra-index-url = [
|
||||
"https://mirrors.aliyun.com/pypi/simple/",
|
||||
"https://mirrors.cloud.tencent.com/pypi/simple/",
|
||||
]
|
||||
|
||||
# 索引策略 - 允许从所有索引中选择最佳版本
|
||||
index-strategy = "unsafe-best-match"
|
||||
|
||||
# 缓存目录(移除此配置,使用 uv 默认缓存位置)
|
||||
# cache-dir = "~/.cache/uv"
|
||||
|
||||
# 并发下载数
|
||||
concurrent-downloads = 10
|
||||
|
||||
# Python 解释器下载镜像源配置
|
||||
# 注意:uv 使用的是 python-build-standalone 项目的构建版本
|
||||
# 暂时注释掉镜像源配置,使用默认源确保兼容性
|
||||
# python-install-mirror = "https://mirror.nju.edu.cn/github-release/indygreg/python-build-standalone/"
|
||||
|
||||
# 可尝试的镜像源(需要验证路径格式):
|
||||
# python-install-mirror = "https://mirrors.tuna.tsinghua.edu.cn/python-release/"
|
||||
# python-install-mirror = "https://mirrors.aliyun.com/python-release/"
|
||||
# python-install-mirror = "https://mirrors.ustc.edu.cn/python/"
|
||||
|
||||
# 如果需要加速,可以设置代理或使用以下环境变量:
|
||||
# export UV_PYTHON_INSTALL_MIRROR="镜像源URL"
|
119
使用示例.md
Normal file
119
使用示例.md
Normal file
@ -0,0 +1,119 @@
|
||||
# AI Shell 使用示例
|
||||
|
||||
## 🚀 基本使用流程
|
||||
|
||||
### 示例 1:查看当前日期(按 Enter 执行)
|
||||
```bash
|
||||
$ uv run python ai.py "show current date"
|
||||
|
||||
(AI Thinking): To display the current date, the `date` command is the most straightforward and commonly used tool in Unix-like systems.
|
||||
|
||||
(AI Answer): date
|
||||
Execute? [Y/n]: ⏎ # 直接按 Enter 键
|
||||
2025年 7月12日 星期六 16时08分00秒 CST
|
||||
```
|
||||
|
||||
### 示例 2:危险命令(输入 n 取消)
|
||||
```bash
|
||||
$ uv run python ai.py "remove all files"
|
||||
|
||||
(AI Thinking): To remove all files in the current directory, we can use the `rm` command. However, we need to be cautious because this action is irreversible.
|
||||
|
||||
(AI Answer): rm -rf *
|
||||
Execute? [Y/n]: n # 输入 n 取消执行
|
||||
```
|
||||
|
||||
### 示例 3:中文命令(按 Enter 执行)
|
||||
```bash
|
||||
$ uv run python ai.py "显示当前目录下的文件"
|
||||
|
||||
(AI Thinking): 用户想要显示当前目录下的文件。最常用和直接的命令是 `ls`,它会列出当前目录中的所有文件和文件夹。
|
||||
|
||||
(AI Answer): ls
|
||||
Execute? [Y/n]: ⏎ # 直接按 Enter 键
|
||||
README.md ai.py pyproject.toml uv.lock uv.toml
|
||||
```
|
||||
|
||||
## 📋 交互选项说明
|
||||
|
||||
### 执行命令的方式:
|
||||
- **直接按 Enter**: 执行命令(默认选择)
|
||||
- **输入 y 或 yes**: 执行命令
|
||||
- **输入 n 或 no**: 取消执行
|
||||
|
||||
### 提示符说明:
|
||||
- `Execute? [Y/n]:`
|
||||
- `[Y/n]` 表示默认选择是 Y(执行)
|
||||
- 大写的 Y 表示这是默认选项
|
||||
- 直接按 Enter 等同于选择 Y
|
||||
|
||||
## 🎯 使用技巧
|
||||
|
||||
### 1. 快速执行常用命令
|
||||
对于安全的查看类命令,可以直接按 Enter 快速执行:
|
||||
```bash
|
||||
uv run python ai.py "list files" # Enter 执行
|
||||
uv run python ai.py "show disk usage" # Enter 执行
|
||||
uv run python ai.py "current directory" # Enter 执行
|
||||
```
|
||||
|
||||
### 2. 谨慎处理危险命令
|
||||
对于可能造成数据丢失的命令,建议仔细检查后再决定:
|
||||
```bash
|
||||
uv run python ai.py "delete old logs" # 检查命令后再决定
|
||||
uv run python ai.py "format disk" # 输入 n 取消
|
||||
uv run python ai.py "remove directory" # 仔细确认
|
||||
```
|
||||
|
||||
### 3. 中英文混合使用
|
||||
```bash
|
||||
# 英文命令
|
||||
uv run python ai.py "find Python files"
|
||||
|
||||
# 中文命令
|
||||
uv run python ai.py "查找Python文件"
|
||||
|
||||
# 混合使用
|
||||
uv run python ai.py "find all .py files in current directory"
|
||||
```
|
||||
|
||||
## 🔧 常用命令示例
|
||||
|
||||
### 文件操作
|
||||
```bash
|
||||
uv run python ai.py "create a backup directory"
|
||||
uv run python ai.py "copy all text files to backup"
|
||||
uv run python ai.py "find files larger than 100MB"
|
||||
```
|
||||
|
||||
### 系统信息
|
||||
```bash
|
||||
uv run python ai.py "show system information"
|
||||
uv run python ai.py "check memory usage"
|
||||
uv run python ai.py "list running processes"
|
||||
```
|
||||
|
||||
### 网络相关
|
||||
```bash
|
||||
uv run python ai.py "check network connectivity"
|
||||
uv run python ai.py "show network interfaces"
|
||||
uv run python ai.py "test connection to google.com"
|
||||
```
|
||||
|
||||
### 开发相关
|
||||
```bash
|
||||
uv run python ai.py "find all Python files"
|
||||
uv run python ai.py "count lines of code"
|
||||
uv run python ai.py "start a simple HTTP server"
|
||||
```
|
||||
|
||||
## ⚠️ 安全提醒
|
||||
|
||||
1. **仔细阅读 AI 生成的命令**:在执行前确保理解命令的作用
|
||||
2. **危险命令要谨慎**:涉及删除、格式化等操作时要特别小心
|
||||
3. **测试环境优先**:在重要系统上使用前,建议先在测试环境验证
|
||||
4. **备份重要数据**:执行可能影响数据的命令前,确保有备份
|
||||
|
||||
---
|
||||
|
||||
💡 **提示**:现在直接按 Enter 键就能执行命令,让您的工作流程更加流畅!
|
157
修改完成总结.md
Normal file
157
修改完成总结.md
Normal file
@ -0,0 +1,157 @@
|
||||
# AI Shell 项目修改完成总结
|
||||
|
||||
## ✅ 已完成的修改
|
||||
|
||||
### 1. 模型接口更换
|
||||
- **原来**: Gemini AI (Google)
|
||||
- **现在**: DeepSeek V3 (通过 OpenAI 兼容接口)
|
||||
|
||||
### 2. API 配置更新
|
||||
```python
|
||||
# 新的配置
|
||||
API_KEY = "f8370a60-fe0a-455f-9167-411d476123d2"
|
||||
BASE_URL = "https://ark.cn-beijing.volces.com/api/v3/"
|
||||
MODEL = "deepseek-v3-250324"
|
||||
```
|
||||
|
||||
### 3. 依赖包更新
|
||||
- **移除**: `google-genai`
|
||||
- **添加**: `openai` (用于 OpenAI 兼容接口)
|
||||
|
||||
### 4. 代码修改详情
|
||||
|
||||
#### 主要变更:
|
||||
1. **导入模块**:
|
||||
```python
|
||||
# 原来
|
||||
from pydantic_ai.models.gemini import GeminiModel
|
||||
|
||||
# 现在
|
||||
from pydantic_ai.models.openai import OpenAIModel
|
||||
```
|
||||
|
||||
2. **模型初始化**:
|
||||
```python
|
||||
# 原来
|
||||
model = GeminiModel("gemini-2.0-flash")
|
||||
|
||||
# 现在
|
||||
os.environ["OPENAI_API_KEY"] = API_KEY
|
||||
os.environ["OPENAI_BASE_URL"] = BASE_URL
|
||||
model = OpenAIModel("deepseek-v3-250324")
|
||||
```
|
||||
|
||||
3. **修复弃用警告**:
|
||||
```python
|
||||
# 原来
|
||||
result_type=Answer
|
||||
resp.data
|
||||
|
||||
# 现在
|
||||
output_type=Answer
|
||||
resp.output
|
||||
```
|
||||
|
||||
## 🧪 测试结果
|
||||
|
||||
### 功能测试
|
||||
✅ **英文命令**: `"list files in current directory"` → `ls`
|
||||
✅ **中文命令**: `"创建一个新目录叫test"` → `mkdir test`
|
||||
✅ **复杂命令**: `"show disk usage"` → `df -h`
|
||||
|
||||
### 性能表现
|
||||
- ✅ 响应速度快
|
||||
- ✅ 命令准确性高
|
||||
- ✅ 支持中英文交互
|
||||
- ✅ 思考过程清晰
|
||||
|
||||
## 📁 最终项目结构
|
||||
|
||||
```
|
||||
ai-shell/
|
||||
├── ai.py # ✅ 主程序(已更新为 DeepSeek V3)
|
||||
├── pyproject.toml # ✅ 项目配置(已更新依赖)
|
||||
├── uv.toml # ✅ UV 配置(国内镜像源)
|
||||
├── uv.lock # ✅ 依赖锁定文件(已更新)
|
||||
├── .python-version # ✅ Python 版本文件
|
||||
├── .venv/ # ✅ 虚拟环境
|
||||
├── README.md # ✅ 项目说明(已更新)
|
||||
├── 配置总结.md # ✅ 配置总结
|
||||
├── 项目配置说明.md # ✅ 详细配置说明(已更新)
|
||||
└── 修改完成总结.md # ✅ 本文件
|
||||
```
|
||||
|
||||
## 🚀 使用方法
|
||||
|
||||
### 基本命令
|
||||
```bash
|
||||
# 英文命令
|
||||
uv run python ai.py "list all Python files"
|
||||
uv run python ai.py "show current directory size"
|
||||
uv run python ai.py "find files modified today"
|
||||
|
||||
# 中文命令
|
||||
uv run python ai.py "显示当前目录下的所有文件"
|
||||
uv run python ai.py "查看磁盘使用情况"
|
||||
uv run python ai.py "创建一个名为backup的目录"
|
||||
```
|
||||
|
||||
### 交互流程
|
||||
1. **AI 思考**: 显示推理过程
|
||||
2. **AI 回答**: 提供具体命令
|
||||
3. **用户确认**: `[Y/n]` 选择是否执行
|
||||
- **Enter 键** 或 **y/yes**: 执行命令
|
||||
- **n/no**: 取消执行
|
||||
4. **自动执行**: 确认后自动运行命令
|
||||
|
||||
## 🎯 核心优势
|
||||
|
||||
### 1. 模型优势
|
||||
- **DeepSeek V3**: 最新的开源大模型,性能优异
|
||||
- **中文友好**: 对中文指令理解更准确
|
||||
- **成本效益**: 通过 Volces API 使用,性价比高
|
||||
|
||||
### 2. 技术优势
|
||||
- **OpenAI 兼容**: 标准接口,易于维护
|
||||
- **快速部署**: 国内镜像源,依赖安装快速
|
||||
- **环境隔离**: UV 虚拟环境,避免冲突
|
||||
|
||||
### 3. 用户体验
|
||||
- **双语支持**: 中英文命令都能准确理解
|
||||
- **安全确认**: 执行前需要用户确认
|
||||
- **便捷操作**: 直接按 Enter 键即可执行(默认为 Y)
|
||||
- **思考透明**: 显示 AI 的推理过程
|
||||
|
||||
## 📋 配置验证
|
||||
|
||||
### 检查配置是否正确
|
||||
```bash
|
||||
# 1. 检查依赖
|
||||
uv pip list | grep -E "(pydantic-ai|openai)"
|
||||
|
||||
# 2. 测试连接
|
||||
uv run python ai.py "echo hello"
|
||||
|
||||
# 3. 验证中文支持
|
||||
uv run python ai.py "显示当前时间"
|
||||
```
|
||||
|
||||
## 🔧 故障排除
|
||||
|
||||
### 常见问题
|
||||
1. **API 连接失败**: 检查网络连接和 API 密钥
|
||||
2. **模型不响应**: 确认 BASE_URL 和模型名称正确
|
||||
3. **依赖问题**: 运行 `uv sync` 重新同步依赖
|
||||
|
||||
### 调试方法
|
||||
```bash
|
||||
# 查看详细错误信息
|
||||
uv run python ai.py "test command" 2>&1
|
||||
|
||||
# 检查环境变量
|
||||
uv run python -c "import os; print(os.environ.get('OPENAI_BASE_URL'))"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
🎉 **修改完成!** 现在您可以使用 DeepSeek V3 模型通过 Volces API 来生成 shell 命令了!
|
215
升级指南.md
Normal file
215
升级指南.md
Normal file
@ -0,0 +1,215 @@
|
||||
# AI Shell 升级和更新指南
|
||||
|
||||
## 🚀 快速升级方法
|
||||
|
||||
### 方法一:直接重新安装(推荐)
|
||||
```bash
|
||||
# 在项目目录中
|
||||
cd /path/to/ai-shell
|
||||
|
||||
# 重新构建并安装
|
||||
uv build
|
||||
uv tool install . --force
|
||||
|
||||
# 验证安装
|
||||
ai --version
|
||||
```
|
||||
|
||||
### 方法二:使用 uv tool upgrade
|
||||
```bash
|
||||
# 如果项目已发布到 PyPI
|
||||
uv tool upgrade ai-shell
|
||||
|
||||
# 或者从本地项目升级
|
||||
cd /path/to/ai-shell
|
||||
uv tool upgrade ai-shell --from .
|
||||
```
|
||||
|
||||
## 🔧 开发和版本管理
|
||||
|
||||
### 1. 修改代码后的升级流程
|
||||
|
||||
```bash
|
||||
# 1. 修改代码(如 ai_shell/main.py, ai_shell/config.py 等)
|
||||
|
||||
# 2. 更新版本号
|
||||
python scripts/bump_version.py patch # 0.1.0 -> 0.1.1
|
||||
# 或
|
||||
python scripts/bump_version.py minor # 0.1.0 -> 0.2.0
|
||||
# 或
|
||||
python scripts/bump_version.py major # 0.1.0 -> 1.0.0
|
||||
|
||||
# 3. 重新构建和安装
|
||||
uv build
|
||||
uv tool install . --force
|
||||
|
||||
# 4. 测试新版本
|
||||
ai --version
|
||||
ai --config
|
||||
ai "test command"
|
||||
```
|
||||
|
||||
### 2. 使用 Makefile 简化操作
|
||||
|
||||
```bash
|
||||
# 查看所有可用命令
|
||||
make help
|
||||
|
||||
# 升级补丁版本并重新安装
|
||||
make bump-patch
|
||||
make install
|
||||
|
||||
# 升级次版本并重新安装
|
||||
make bump-minor
|
||||
make install
|
||||
|
||||
# 清理构建文件
|
||||
make clean
|
||||
|
||||
# 测试安装
|
||||
make test
|
||||
```
|
||||
|
||||
## 📝 常见升级场景
|
||||
|
||||
### 场景 1:修改 API 配置
|
||||
```bash
|
||||
# 编辑配置文件
|
||||
vim ai_shell/config.py
|
||||
|
||||
# 升级并重新安装
|
||||
python scripts/bump_version.py patch
|
||||
uv build
|
||||
uv tool install . --force
|
||||
```
|
||||
|
||||
### 场景 2:添加新功能
|
||||
```bash
|
||||
# 编辑主程序
|
||||
vim ai_shell/main.py
|
||||
|
||||
# 升级次版本
|
||||
python scripts/bump_version.py minor
|
||||
uv build
|
||||
uv tool install . --force
|
||||
```
|
||||
|
||||
### 场景 3:修改依赖
|
||||
```bash
|
||||
# 编辑依赖
|
||||
vim pyproject.toml
|
||||
|
||||
# 同步依赖
|
||||
uv sync
|
||||
|
||||
# 重新安装
|
||||
uv build
|
||||
uv tool install . --force
|
||||
```
|
||||
|
||||
## 🔍 验证升级
|
||||
|
||||
### 检查安装状态
|
||||
```bash
|
||||
# 查看已安装的工具
|
||||
uv tool list
|
||||
|
||||
# 查看版本信息
|
||||
ai --version
|
||||
|
||||
# 查看配置
|
||||
ai --config
|
||||
|
||||
# 测试功能
|
||||
ai "echo hello"
|
||||
```
|
||||
|
||||
### 故障排除
|
||||
```bash
|
||||
# 如果命令不存在,检查 PATH
|
||||
echo $PATH | grep -o ~/.local/bin
|
||||
|
||||
# 如果 PATH 中没有 ~/.local/bin,添加到 shell 配置
|
||||
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc
|
||||
source ~/.zshrc
|
||||
|
||||
# 完全重新安装
|
||||
uv tool uninstall ai-shell
|
||||
uv tool install .
|
||||
```
|
||||
|
||||
## 📦 版本管理最佳实践
|
||||
|
||||
### 1. 语义化版本控制
|
||||
- **补丁版本** (0.1.0 -> 0.1.1): 修复 bug,小改动
|
||||
- **次版本** (0.1.0 -> 0.2.0): 新功能,向后兼容
|
||||
- **主版本** (0.1.0 -> 1.0.0): 重大变更,可能不兼容
|
||||
|
||||
### 2. 升级前的检查清单
|
||||
- [ ] 代码修改完成
|
||||
- [ ] 测试功能正常
|
||||
- [ ] 更新版本号
|
||||
- [ ] 重新构建包
|
||||
- [ ] 重新安装工具
|
||||
- [ ] 验证新版本
|
||||
|
||||
### 3. 配置文件管理
|
||||
```bash
|
||||
# 查看当前配置
|
||||
ai --config
|
||||
|
||||
# 如果需要修改 API 配置,编辑:
|
||||
vim ai_shell/config.py
|
||||
|
||||
# 或者使用环境变量覆盖:
|
||||
export AI_SHELL_API_KEY="new_api_key"
|
||||
export AI_SHELL_BASE_URL="new_base_url"
|
||||
export AI_SHELL_MODEL="new_model"
|
||||
```
|
||||
|
||||
## 🎯 自动化升级脚本
|
||||
|
||||
创建一个一键升级脚本:
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# 保存为 quick_upgrade.sh
|
||||
|
||||
echo "🔄 AI Shell 快速升级..."
|
||||
|
||||
# 检查是否在项目目录
|
||||
if [ ! -f "pyproject.toml" ]; then
|
||||
echo "❌ 请在 ai-shell 项目目录中运行此脚本"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 升级补丁版本
|
||||
echo "📈 升级版本..."
|
||||
python scripts/bump_version.py patch
|
||||
|
||||
# 重新构建
|
||||
echo "📦 重新构建..."
|
||||
uv build
|
||||
|
||||
# 重新安装
|
||||
echo "🔧 重新安装..."
|
||||
uv tool install . --force
|
||||
|
||||
# 验证
|
||||
echo "✅ 升级完成!"
|
||||
ai --version
|
||||
|
||||
echo "🧪 测试命令:"
|
||||
echo "ai --config"
|
||||
echo "ai \"echo test\""
|
||||
```
|
||||
|
||||
使用方法:
|
||||
```bash
|
||||
chmod +x quick_upgrade.sh
|
||||
./quick_upgrade.sh
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
💡 **总结**:最简单的升级方法就是在项目目录中运行 `uv build && uv tool install . --force`
|
157
配置修复总结.md
Normal file
157
配置修复总结.md
Normal file
@ -0,0 +1,157 @@
|
||||
# 配置修复总结
|
||||
|
||||
## 🐛 问题描述
|
||||
|
||||
每次运行 `uv sync` 时,都会在项目目录中创建一个名为 `~` 的文件夹。
|
||||
|
||||
## 🔍 问题原因
|
||||
|
||||
在 `uv.toml` 配置文件中,`cache-dir = "~/.cache/uv"` 的 `~` 符号没有被正确展开,uv 将其当作字面量处理,导致在当前目录创建了名为 `~` 的文件夹。
|
||||
|
||||
## ✅ 解决方案
|
||||
|
||||
### 1. 修复项目配置文件
|
||||
|
||||
**修改前** (`uv.toml`):
|
||||
```toml
|
||||
# 缓存目录
|
||||
cache-dir = "~/.cache/uv"
|
||||
```
|
||||
|
||||
**修改后** (`uv.toml`):
|
||||
```toml
|
||||
# 缓存目录(移除此配置,使用 uv 默认缓存位置)
|
||||
# cache-dir = "~/.cache/uv"
|
||||
```
|
||||
|
||||
### 2. 清理重复配置
|
||||
|
||||
**问题**:`pyproject.toml` 和 `uv.toml` 中有重复的 uv 配置,导致警告信息。
|
||||
|
||||
**解决**:删除 `pyproject.toml` 中的 `[tool.uv]` 配置段,只保留 `uv.toml` 中的配置。
|
||||
|
||||
**修改前** (`pyproject.toml`):
|
||||
```toml
|
||||
[tool.uv]
|
||||
# 使用国内镜像源加速下载
|
||||
index-url = "https://pypi.tuna.tsinghua.edu.cn/simple"
|
||||
extra-index-url = [
|
||||
"https://mirrors.aliyun.com/pypi/simple/",
|
||||
"https://mirrors.cloud.tencent.com/pypi/simple/",
|
||||
]
|
||||
index-strategy = "unsafe-best-match"
|
||||
concurrent-downloads = 10
|
||||
cache-dir = "~/.cache/uv"
|
||||
```
|
||||
|
||||
**修改后** (`pyproject.toml`):
|
||||
```toml
|
||||
# UV 配置已移至 uv.toml 文件
|
||||
```
|
||||
|
||||
### 3. 完善全局配置
|
||||
|
||||
创建正确的全局 uv 配置文件 `~/.config/uv/uv.toml`:
|
||||
|
||||
```toml
|
||||
# UV 全局配置文件
|
||||
# 配置国内镜像源加速下载
|
||||
|
||||
# PyPI 镜像源配置
|
||||
index-url = "https://pypi.tuna.tsinghua.edu.cn/simple"
|
||||
extra-index-url = [
|
||||
"https://mirrors.aliyun.com/pypi/simple/",
|
||||
"https://mirrors.cloud.tencent.com/pypi/simple/",
|
||||
]
|
||||
|
||||
# 性能优化配置
|
||||
index-strategy = "unsafe-best-match"
|
||||
concurrent-downloads = 10
|
||||
|
||||
# 注意:不要设置 cache-dir,让 uv 使用默认位置
|
||||
```
|
||||
|
||||
## 🧹 清理操作
|
||||
|
||||
1. **删除错误创建的目录**:
|
||||
```bash
|
||||
rm -rf ./~
|
||||
```
|
||||
|
||||
2. **验证修复效果**:
|
||||
```bash
|
||||
uv sync
|
||||
ls -la | grep "~" # 应该没有输出
|
||||
```
|
||||
|
||||
## 📋 最佳实践
|
||||
|
||||
### 1. uv 缓存配置
|
||||
- ✅ **推荐**:不设置 `cache-dir`,让 uv 使用默认位置
|
||||
- ❌ **避免**:使用 `~` 符号,因为可能不被正确展开
|
||||
- ✅ **替代**:如果必须自定义,使用绝对路径
|
||||
|
||||
### 2. 配置文件优先级
|
||||
- `uv.toml` > `pyproject.toml` 中的 `[tool.uv]`
|
||||
- 避免在两个文件中重复配置相同选项
|
||||
|
||||
### 3. 全局 vs 项目配置
|
||||
- **全局配置** (`~/.config/uv/uv.toml`):适用于所有项目的通用设置
|
||||
- **项目配置** (`项目目录/uv.toml`):特定项目的配置,会覆盖全局配置
|
||||
|
||||
## 🔧 当前配置状态
|
||||
|
||||
### 项目配置 (`uv.toml`):
|
||||
```toml
|
||||
# uv 项目配置文件
|
||||
# 配置国内镜像源加速下载
|
||||
|
||||
# 主要的 PyPI 镜像源
|
||||
index-url = "https://pypi.tuna.tsinghua.edu.cn/simple"
|
||||
|
||||
# 额外的镜像源
|
||||
extra-index-url = [
|
||||
"https://mirrors.aliyun.com/pypi/simple/",
|
||||
"https://mirrors.cloud.tencent.com/pypi/simple/",
|
||||
]
|
||||
|
||||
# 索引策略 - 允许从所有索引中选择最佳版本
|
||||
index-strategy = "unsafe-best-match"
|
||||
|
||||
# 缓存目录(移除此配置,使用 uv 默认缓存位置)
|
||||
# cache-dir = "~/.cache/uv"
|
||||
|
||||
# 并发下载数
|
||||
concurrent-downloads = 10
|
||||
```
|
||||
|
||||
### 全局配置 (`~/.config/uv/uv.toml`):
|
||||
```toml
|
||||
# UV 全局配置文件
|
||||
# 配置国内镜像源加速下载
|
||||
|
||||
# PyPI 镜像源配置
|
||||
index-url = "https://pypi.tuna.tsinghua.edu.cn/simple"
|
||||
extra-index-url = [
|
||||
"https://mirrors.aliyun.com/pypi/simple/",
|
||||
"https://mirrors.cloud.tencent.com/pypi/simple/",
|
||||
]
|
||||
|
||||
# 性能优化配置
|
||||
index-strategy = "unsafe-best-match"
|
||||
concurrent-downloads = 10
|
||||
|
||||
# 注意:不要设置 cache-dir,让 uv 使用默认位置
|
||||
```
|
||||
|
||||
## ✅ 验证结果
|
||||
|
||||
修复后运行 `uv sync`:
|
||||
- ✅ 不再创建 `~` 目录
|
||||
- ✅ 没有重复配置警告
|
||||
- ✅ 国内镜像源正常工作
|
||||
- ✅ 依赖同步正常
|
||||
|
||||
---
|
||||
|
||||
💡 **总结**:问题已完全解决,uv 配置现在更加清晰和规范。
|
117
配置总结.md
Normal file
117
配置总结.md
Normal file
@ -0,0 +1,117 @@
|
||||
# UV 国内源加速配置总结
|
||||
|
||||
## ✅ 配置完成状态
|
||||
|
||||
### 核心配置文件
|
||||
|
||||
- **uv.toml** - 主要配置文件 ⭐
|
||||
- 清华大学镜像(主源)+ 阿里云、腾讯云(备源)
|
||||
- 10个并发下载,智能版本选择策略
|
||||
- 已优化缓存配置
|
||||
|
||||
- **pyproject.toml** - 项目配置文件
|
||||
- Python 版本:>=3.12(当前使用 3.12.11)
|
||||
- 核心依赖:pydantic-ai, google-genai, requests
|
||||
|
||||
### 2. 配置的镜像源
|
||||
|
||||
| 镜像源 | URL | 状态 |
|
||||
|--------|-----|------|
|
||||
| 清华大学 | https://pypi.tuna.tsinghua.edu.cn/simple | 主源 ✅ |
|
||||
| 阿里云 | https://mirrors.aliyun.com/pypi/simple/ | 备用 ✅ |
|
||||
| 腾讯云 | https://mirrors.cloud.tencent.com/pypi/simple/ | 备用 ✅ |
|
||||
|
||||
### 3. 性能测试结果
|
||||
|
||||
- ✅ PyPI 包解析速度:0.02秒(极快)
|
||||
- ✅ 包安装速度:显著提升(使用国内镜像源)
|
||||
- ✅ 配置文件检测:全部通过
|
||||
- ✅ Python 版本:3.12.11(已正确配置)
|
||||
- ⚠️ Python 解释器下载:仍需要优化(建议使用系统包管理器)
|
||||
|
||||
## 🚀 使用方法
|
||||
|
||||
### 基本命令
|
||||
|
||||
```bash
|
||||
# 安装依赖
|
||||
uv sync
|
||||
|
||||
# 添加新包
|
||||
uv add package-name
|
||||
|
||||
# 运行脚本
|
||||
uv run python script.py
|
||||
|
||||
# 激活虚拟环境
|
||||
uv shell
|
||||
```
|
||||
|
||||
### 验证配置
|
||||
|
||||
```bash
|
||||
# 运行测试脚本
|
||||
uv run python test_uv_config.py
|
||||
```
|
||||
|
||||
## 📁 当前项目结构
|
||||
|
||||
```
|
||||
ai-shell/
|
||||
├── ai.py # 主程序(AI shell 命令生成器)
|
||||
├── pyproject.toml # 项目配置文件
|
||||
├── uv.toml # UV 配置文件(核心)
|
||||
├── uv.lock # 依赖锁定文件(自动生成)
|
||||
├── .python-version # Python 版本文件(自动生成)
|
||||
├── .venv/ # 虚拟环境(自动生成)
|
||||
├── README.md # 项目说明
|
||||
├── 配置总结.md # 本文件
|
||||
└── 项目配置说明.md # 详细配置说明
|
||||
```
|
||||
|
||||
## 🎯 配置优势
|
||||
|
||||
1. **PyPI 包速度提升**:使用国内镜像源,包下载速度显著提升
|
||||
2. **稳定性**:多个备用镜像源,确保可用性
|
||||
3. **兼容性**:支持所有 uv 功能
|
||||
4. **易维护**:配置文件清晰,易于修改
|
||||
5. **版本管理**:正确配置 Python 版本要求,避免兼容性问题
|
||||
|
||||
## 🔧 故障排除
|
||||
|
||||
如果遇到问题:
|
||||
|
||||
1. **网络问题**:检查网络连接,尝试切换镜像源
|
||||
2. **缓存问题**:运行 `uv cache clean` 清除缓存
|
||||
3. **配置冲突**:确保 uv.toml 配置正确
|
||||
|
||||
## 📝 注意事项
|
||||
|
||||
- uv.toml 文件优先级高于 pyproject.toml 中的 [tool.uv] 配置
|
||||
- 使用 unsafe-best-match 策略可能有安全风险,但提供更好的包版本选择
|
||||
- 定期更新镜像源地址以确保最佳性能
|
||||
|
||||
## 🐍 关于 Python 解释器下载
|
||||
|
||||
**重要说明**:
|
||||
- ✅ **PyPI 包下载**:已成功配置国内镜像源,速度很快
|
||||
- ⚠️ **Python 解释器下载**:镜像源配置复杂,建议使用以下替代方案:
|
||||
|
||||
### 推荐的 Python 版本管理方案:
|
||||
1. **使用系统包管理器**:`brew install python@3.12` (macOS)
|
||||
2. **使用 pyenv**:`pyenv install 3.12.0`
|
||||
3. **使用 conda**:`conda install python=3.12`
|
||||
4. **使用现有版本**:您已有 Python 3.12.11,完全可用
|
||||
|
||||
### 如果必须用 uv 下载 Python:
|
||||
- 考虑使用代理:`export HTTPS_PROXY=your_proxy`
|
||||
- 或者耐心等待:Python 解释器文件较大,首次下载需要时间
|
||||
|
||||
---
|
||||
|
||||
🎉 **配置完成!现在您可以享受快速的 Python 包管理体验了!**
|
||||
|
||||
📋 **当前状态**:
|
||||
- ✅ PyPI 包下载:极快(国内镜像源)
|
||||
- ✅ Python 版本:3.12.11(已配置)
|
||||
- ✅ 项目依赖:已同步完成
|
199
配置管理说明.md
Normal file
199
配置管理说明.md
Normal file
@ -0,0 +1,199 @@
|
||||
# AI Shell 配置管理说明
|
||||
|
||||
## 🔐 敏感配置管理
|
||||
|
||||
### 1. 使用 .env 文件
|
||||
|
||||
项目现在使用 `.env` 文件来管理敏感配置,确保 API 密钥等信息不会被意外提交到代码库。
|
||||
|
||||
#### 配置文件结构:
|
||||
```
|
||||
ai-shell/
|
||||
├── .env # 实际配置文件(已在 .gitignore 中排除)
|
||||
├── .env.example # 配置模板文件(会被提交到代码库)
|
||||
└── ai_shell/config.py # 配置加载逻辑
|
||||
```
|
||||
|
||||
### 2. 配置文件内容
|
||||
|
||||
#### `.env` 文件(实际配置):
|
||||
```bash
|
||||
# AI Shell 配置文件
|
||||
AI_SHELL_API_KEY=f8370a60-fe0a-455f-9167-411d476123d2
|
||||
AI_SHELL_BASE_URL=https://ark.cn-beijing.volces.com/api/v3/
|
||||
AI_SHELL_MODEL=deepseek-v3-250324
|
||||
|
||||
# 可选配置
|
||||
AI_SHELL_TIMEOUT=30
|
||||
AI_SHELL_MAX_RETRIES=3
|
||||
```
|
||||
|
||||
#### `.env.example` 文件(模板):
|
||||
```bash
|
||||
# AI Shell 配置文件模板
|
||||
AI_SHELL_API_KEY=your_api_key_here
|
||||
AI_SHELL_BASE_URL=https://your-api-endpoint.com/v3/
|
||||
AI_SHELL_MODEL=your_model_name
|
||||
|
||||
# 可选配置
|
||||
AI_SHELL_TIMEOUT=30
|
||||
AI_SHELL_MAX_RETRIES=3
|
||||
```
|
||||
|
||||
## 🔧 配置加载优先级
|
||||
|
||||
配置系统按以下优先级加载配置:
|
||||
|
||||
1. **环境变量**(最高优先级)
|
||||
2. **当前目录的 .env 文件**
|
||||
3. **包目录的 .env 文件**
|
||||
4. **~/.ai-shell/.env 文件**
|
||||
5. **默认值**(最低优先级)
|
||||
|
||||
## 📋 配置项说明
|
||||
|
||||
| 配置项 | 环境变量 | 说明 | 默认值 |
|
||||
|--------|----------|------|--------|
|
||||
| API Key | `AI_SHELL_API_KEY` | API 密钥(必填) | 无 |
|
||||
| Base URL | `AI_SHELL_BASE_URL` | API 基础 URL | `https://api.openai.com/v1/` |
|
||||
| Model | `AI_SHELL_MODEL` | 模型名称 | `gpt-3.5-turbo` |
|
||||
| Timeout | `AI_SHELL_TIMEOUT` | 请求超时时间(秒) | `30` |
|
||||
| Max Retries | `AI_SHELL_MAX_RETRIES` | 最大重试次数 | `3` |
|
||||
|
||||
## 🚀 使用方法
|
||||
|
||||
### 1. 查看当前配置
|
||||
```bash
|
||||
ai --config
|
||||
```
|
||||
|
||||
输出示例:
|
||||
```
|
||||
AI Shell Configuration:
|
||||
Model: deepseek-v3-250324
|
||||
Base URL: https://ark.cn-beijing.volces.com/api/v3/
|
||||
API Key: f8370a60...123d2
|
||||
Timeout: 30s
|
||||
Max Retries: 3
|
||||
|
||||
Configuration Status: ✅ Valid
|
||||
|
||||
Configuration Sources (in priority order):
|
||||
1. Environment variables
|
||||
2. .env file in current directory
|
||||
3. .env file in package directory
|
||||
4. ~/.ai-shell/.env file
|
||||
5. Default values
|
||||
```
|
||||
|
||||
### 2. 修改配置
|
||||
|
||||
#### 方法 1:编辑 .env 文件
|
||||
```bash
|
||||
# 编辑项目目录中的 .env 文件
|
||||
vim .env
|
||||
|
||||
# 或创建全局配置
|
||||
mkdir -p ~/.ai-shell
|
||||
cp .env ~/.ai-shell/.env
|
||||
vim ~/.ai-shell/.env
|
||||
```
|
||||
|
||||
#### 方法 2:使用环境变量
|
||||
```bash
|
||||
# 临时设置
|
||||
export AI_SHELL_API_KEY="new_api_key"
|
||||
export AI_SHELL_MODEL="gpt-4"
|
||||
|
||||
# 永久设置(添加到 shell 配置文件)
|
||||
echo 'export AI_SHELL_API_KEY="new_api_key"' >> ~/.zshrc
|
||||
```
|
||||
|
||||
### 3. 配置验证
|
||||
|
||||
程序启动时会自动验证配置:
|
||||
|
||||
```bash
|
||||
ai "test command"
|
||||
```
|
||||
|
||||
如果配置无效,会显示错误信息:
|
||||
```
|
||||
❌ Configuration error: API key not configured.
|
||||
Please set AI_SHELL_API_KEY in .env file or environment variable.
|
||||
Run 'ai --config' to see current configuration.
|
||||
```
|
||||
|
||||
## 🔄 升级后的配置管理
|
||||
|
||||
### 升级流程:
|
||||
1. **修改代码**
|
||||
2. **更新版本**: `python scripts/bump_version.py patch`
|
||||
3. **重新安装**: `uv build && uv tool install . --force`
|
||||
4. **配置自动保留**:`.env` 文件不会被覆盖
|
||||
|
||||
### 配置迁移:
|
||||
如果需要迁移配置到新环境:
|
||||
```bash
|
||||
# 复制配置文件
|
||||
cp .env /path/to/new/environment/
|
||||
|
||||
# 或设置环境变量
|
||||
export AI_SHELL_API_KEY="your_key"
|
||||
export AI_SHELL_BASE_URL="your_url"
|
||||
export AI_SHELL_MODEL="your_model"
|
||||
```
|
||||
|
||||
## 🛡️ 安全最佳实践
|
||||
|
||||
### 1. 保护 .env 文件
|
||||
- ✅ `.env` 文件已在 `.gitignore` 中排除
|
||||
- ✅ 不要将 `.env` 文件提交到代码库
|
||||
- ✅ 使用 `.env.example` 作为模板
|
||||
|
||||
### 2. API 密钥管理
|
||||
- 🔐 定期轮换 API 密钥
|
||||
- 🔐 不要在代码中硬编码密钥
|
||||
- 🔐 使用环境变量或配置文件
|
||||
|
||||
### 3. 权限控制
|
||||
```bash
|
||||
# 设置 .env 文件权限(仅所有者可读写)
|
||||
chmod 600 .env
|
||||
|
||||
# 检查权限
|
||||
ls -la .env
|
||||
```
|
||||
|
||||
## 🔍 故障排除
|
||||
|
||||
### 常见问题:
|
||||
|
||||
1. **API 密钥未配置**
|
||||
```bash
|
||||
# 检查配置
|
||||
ai --config
|
||||
|
||||
# 设置密钥
|
||||
echo 'AI_SHELL_API_KEY=your_key' >> .env
|
||||
```
|
||||
|
||||
2. **配置文件未找到**
|
||||
```bash
|
||||
# 创建配置文件
|
||||
cp .env.example .env
|
||||
vim .env
|
||||
```
|
||||
|
||||
3. **权限问题**
|
||||
```bash
|
||||
# 检查文件权限
|
||||
ls -la .env
|
||||
|
||||
# 修复权限
|
||||
chmod 600 .env
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
💡 **总结**:现在 AI Shell 使用 `.env` 文件管理敏感配置,确保了安全性和可维护性。配置会在升级时自动保留,无需重新设置。
|
165
项目配置说明.md
Normal file
165
项目配置说明.md
Normal file
@ -0,0 +1,165 @@
|
||||
# AI Shell 项目配置说明
|
||||
|
||||
## 📁 项目结构
|
||||
|
||||
```
|
||||
ai-shell/
|
||||
├── ai.py # 主程序文件
|
||||
├── pyproject.toml # 项目配置文件
|
||||
├── uv.toml # UV 包管理器配置文件
|
||||
├── uv.lock # 依赖锁定文件(自动生成)
|
||||
├── .python-version # Python 版本固定文件(自动生成)
|
||||
├── .venv/ # 虚拟环境目录(自动生成)
|
||||
├── README.md # 项目说明文档
|
||||
├── 配置总结.md # 配置总结文档
|
||||
└── 项目配置说明.md # 本文件
|
||||
```
|
||||
|
||||
## 🔧 核心配置文件详解
|
||||
|
||||
### 1. `ai.py` - 主程序文件
|
||||
**作用**:AI 驱动的 shell 命令生成器
|
||||
**功能**:
|
||||
- 使用 Gemini AI 模型生成 shell 命令
|
||||
- 支持多语言提示和响应
|
||||
- 交互式执行确认
|
||||
|
||||
**关键配置**:
|
||||
```python
|
||||
# OpenAI 兼容接口配置
|
||||
API_KEY = "f8370a60-fe0a-455f-9167-411d476123d2"
|
||||
BASE_URL = "https://ark.cn-beijing.volces.com/api/v3/"
|
||||
|
||||
# 使用 DeepSeek V3 模型
|
||||
model = OpenAIModel("deepseek-v3-250324")
|
||||
```
|
||||
|
||||
### 2. `pyproject.toml` - 项目配置文件
|
||||
**作用**:定义项目元数据和依赖关系
|
||||
**内容解析**:
|
||||
```toml
|
||||
[project]
|
||||
name = "ai-shell" # 项目名称
|
||||
version = "0.1.0" # 版本号
|
||||
description = "AI-powered shell command generator" # 项目描述
|
||||
requires-python = ">=3.12" # Python 版本要求
|
||||
dependencies = [ # 项目依赖
|
||||
"pydantic-ai", # AI 框架
|
||||
"openai", # OpenAI 兼容 API 客户端
|
||||
"requests>=2.32.4", # HTTP 请求库
|
||||
]
|
||||
```
|
||||
|
||||
### 3. `uv.toml` - UV 包管理器配置文件 ⭐
|
||||
**作用**:配置 UV 包管理器的行为和镜像源
|
||||
**重要性**:这是加速包下载的核心配置文件
|
||||
|
||||
**详细配置解析**:
|
||||
```toml
|
||||
# PyPI 镜像源配置
|
||||
index-url = "https://pypi.tuna.tsinghua.edu.cn/simple" # 主镜像源(清华大学)
|
||||
extra-index-url = [ # 备用镜像源
|
||||
"https://mirrors.aliyun.com/pypi/simple/", # 阿里云镜像
|
||||
"https://mirrors.cloud.tencent.com/pypi/simple/", # 腾讯云镜像
|
||||
]
|
||||
|
||||
# 性能优化配置
|
||||
index-strategy = "unsafe-best-match" # 允许从所有镜像源选择最佳版本
|
||||
concurrent-downloads = 10 # 并发下载数量
|
||||
cache-dir = "~/.cache/uv" # 缓存目录
|
||||
|
||||
# Python 解释器镜像源(已注释,使用默认源)
|
||||
# python-install-mirror = "镜像源URL"
|
||||
```
|
||||
|
||||
### 4. `uv.lock` - 依赖锁定文件(自动生成)
|
||||
**作用**:锁定所有依赖的精确版本
|
||||
**特点**:
|
||||
- 自动生成,不需要手动编辑
|
||||
- 确保在不同环境中安装相同版本的依赖
|
||||
- 包含所有传递依赖的版本信息
|
||||
|
||||
### 5. `.python-version` - Python 版本固定文件(自动生成)
|
||||
**作用**:指定项目使用的 Python 版本
|
||||
**内容**:`3.12`
|
||||
**用途**:确保项目在正确的 Python 版本下运行
|
||||
|
||||
### 6. `.venv/` - 虚拟环境目录(自动生成)
|
||||
**作用**:隔离的 Python 环境
|
||||
**包含**:
|
||||
- 项目特定的 Python 解释器
|
||||
- 安装的所有依赖包
|
||||
- 环境配置文件
|
||||
|
||||
## 🚀 配置优势
|
||||
|
||||
### 1. 国内镜像源加速
|
||||
- **主源**:清华大学镜像(教育网友好)
|
||||
- **备源**:阿里云、腾讯云(商业网络友好)
|
||||
- **效果**:包下载速度从几十秒降到秒级
|
||||
|
||||
### 2. 智能版本选择
|
||||
- `index-strategy = "unsafe-best-match"`
|
||||
- 从所有镜像源中选择最佳版本
|
||||
- 避免版本冲突和依赖问题
|
||||
|
||||
### 3. 性能优化
|
||||
- 10 个并发下载
|
||||
- 本地缓存机制
|
||||
- 快速依赖解析
|
||||
|
||||
## 📋 使用指南
|
||||
|
||||
### 基本命令
|
||||
```bash
|
||||
# 安装/更新依赖
|
||||
uv sync
|
||||
|
||||
# 添加新依赖
|
||||
uv add package-name
|
||||
|
||||
# 运行程序
|
||||
uv run python ai.py "your command description"
|
||||
|
||||
# 激活虚拟环境
|
||||
uv shell
|
||||
```
|
||||
|
||||
### 环境管理
|
||||
```bash
|
||||
# 查看 Python 版本
|
||||
uv python pin
|
||||
|
||||
# 查看已安装包
|
||||
uv pip list
|
||||
|
||||
# 清理缓存
|
||||
uv cache clean
|
||||
```
|
||||
|
||||
## ⚠️ 注意事项
|
||||
|
||||
1. **配置优先级**:`uv.toml` > `pyproject.toml` 中的 `[tool.uv]` 配置
|
||||
2. **镜像源策略**:使用 `unsafe-best-match` 可能有安全风险,但提供更好的包选择
|
||||
3. **Python 解释器**:下载新 Python 版本仍然较慢,建议使用系统包管理器
|
||||
4. **API 配置**:已内置 Volces (ByteDance) API 配置,使用 DeepSeek V3 模型
|
||||
|
||||
## 🔍 故障排除
|
||||
|
||||
### 常见问题
|
||||
1. **包下载慢**:检查网络连接,尝试切换镜像源
|
||||
2. **版本冲突**:运行 `uv sync` 重新解析依赖
|
||||
3. **缓存问题**:运行 `uv cache clean` 清理缓存
|
||||
|
||||
### 验证配置
|
||||
```bash
|
||||
# 测试依赖解析速度
|
||||
time uv sync --dry-run
|
||||
|
||||
# 检查镜像源连通性
|
||||
curl -I https://pypi.tuna.tsinghua.edu.cn/simple/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
🎯 **总结**:这个配置实现了 Python 包的快速下载和管理,同时保持了项目的可移植性和稳定性。
|
Reference in New Issue
Block a user