以下是一个基于Python的自动化脚本示例,结合DeepSeek API和GitHub操作实现一键生成并提交代码:
```python
import os
import requests
import subprocess
from getpass import getpass
# 配置信息
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/code/generate"
GITHUB_REPO_URL = input("请输入GitHub仓库地址(SSH或HTTPS): ")
LOCAL_REPO_DIR = "./deepseek_generated_code"
FILE_NAME = "generated_code.py"
def get_deepseek_code(prompt, api_key):
headers = {"Authorization": f"Bearer {api_key}"}
data = {
"prompt": prompt,
"language": "python",
"temperature": 0.7,
"max_tokens": 1000
}
try:
response = requests.post(DEEPSEEK_API_URL, json=data, headers=headers)
response.raise_for_status()
return response.json()["choices"][0]["text"]
except Exception as e:
print(f"DeepSeek API调用失败: {str(e)}")
exit(1)
def git_operations(code_content):
# 初始化本地仓库
if not os.path.exists(LOCAL_REPO_DIR):
os.makedirs(LOCAL_REPO_DIR)
# 写入生成的文件
file_path = os.path.join(LOCAL_REPO_DIR, FILE_NAME)
with open(file_path, "w") as f:
f.write(code_content)
# 执行Git操作
try:
subprocess.run(["git", "clone", GITHUB_REPO_URL, LOCAL_REPO_DIR], check=True)
subprocess.run(["git", "-C", LOCAL_REPO_DIR, "add", "."], check=True)
subprocess.run(["git", "-C", LOCAL_REPO_DIR, "commit", "-m", "Auto-commit generated code"], check=True)
subprocess.run(["git", "-C", LOCAL_REPO_DIR, "push"], check=True)
print("代码已成功提交到GitHub仓库!")
except subprocess.CalledProcessError as e:
print(f"Git操作失败: {str(e)}")
exit(1)
if __name__ == "__main__":
# 获取用户输入
prompt = input("请输入代码生成提示词: ")
api_key = getpass("请输入DeepSeek API密钥: ")
# 生成代码
generated_code = get_deepseek_code(prompt, api_key)
print("\n生成的代码:\n")
print(generated_code)
# 提交到GitHub
git_operations(generated_code)
```
---
**使用说明:**
1. **准备工作:**
- 获取DeepSeek API密钥(登录DeepSeek平台创建)
- 准备GitHub仓库(建议先创建空仓库)
- 本地安装:
- Python 3.6+
- Git
- 所需Python包:`pip install requests`
2. **配置步骤:**
- 将脚本中的`DEEPSEEK_API_URL`替换为实际的API地址(根据文档)
- 根据需要修改`LOCAL_REPO_DIR`和`FILE_NAME`
3. **运行脚本:**
```bash
python auto_codegen.py
```
按提示输入:
- GitHub仓库地址(HTTPS/SSH格式)
- 代码生成提示词(英文效果更佳)
- DeepSeek API密钥
4. **验证结果:**
- 查看GitHub仓库是否成功提交
- 检查生成代码是否符合预期
---
**注意事项:**
1. 安全建议:
- 不要将API密钥提交到版本控制
- 建议将密钥存储在环境变量中
```bash
export DEEPSEEK_API_KEY='your_key'
```
2. 扩展建议:
- 添加代码质量检查
- 增加生成后的人工确认步骤
- 支持多文件生成
- 添加commit message自定义功能
3. 错误排查:
- 确保Git已配置全局用户信息
```bash
git config --global user.name "Your Name"
git config --global user.email "your@email.com"
```
- 确保有仓库的写入权限
- 检查网络连接和API限额
如果需要更详细的配置说明或定制功能,可以告诉我具体需求!