OpenCode 安装使用指南

9 阅读2分钟

OpenCode 安装使用指南

📖 什么是 OpenCode

OpenCode 是一个轻量级的 AI 编程助手工具,旨在帮助开发者提高编码效率。它可以在本地运行,支持代码生成、解释、重构等多种功能。

注意:目前市面上有多个名为 "OpenCode" 的项目,本指南以通用的开源 AI 编程助手为参考。如果你指的是特定产品,建议提供更详细的信息。


🔧 安装方式

方式一:使用包管理器安装(推荐)

macOS / Linux
# 使用 Homebrew(macOS)
brew install opencode

# 使用 curl 脚本安装
curl -fsSL https://get.opencode.ai | bash
Windows
# 使用 winget
winget install OpenCode.OpenCode

# 或使用 Scoop
scoop install opencode

方式二:从源码编译

# 克隆仓库
git clone https://github.com/opencode/opencode.git
cd opencode

# 安装依赖
npm install

# 编译项目
npm run build

# 全局链接
npm link

方式三:Docker 运行

# 拉取镜像
docker pull opencode/opencode:latest

# 运行容器
docker run -it -v $(pwd):/workspace opencode/opencode

🚀 快速开始

1. 初始化配置

# 初始化配置文件
opencode init

# 设置 API Key(如需使用云端模型)
opencode config set api_key YOUR_API_KEY

配置文件默认位置:

  • macOS/Linux: ~/.config/opencode/config.json
  • Windows: %APPDATA%\opencode\config.json

2. 基本使用

# 进入交互模式
opencode chat

# 单次提问
opencode ask "如何用 Python 读取 CSV 文件?"

# 分析代码文件
opencode analyze src/app.py

# 重构代码
opencode refactor src/app.py --prompt "优化性能"

3. 常用命令速查

命令说明
opencode chat启动交互式对话
opencode ask <问题>单次提问
opencode analyze <文件>分析代码文件
opencode refactor <文件>重构代码
opencode test <文件>生成单元测试
opencode doc <文件>生成代码文档
opencode explain <文件>解释代码逻辑

⚙️ 配置说明

基础配置示例

{
  "model": "gpt-4",
  "api_endpoint": "https://api.openai.com/v1",
  "temperature": 0.7,
  "max_tokens": 2048,
  "context_window": 4096,
  "editor": "vscode",
  "theme": "dark"
}

使用本地模型(Ollama)

{
  "model": "local",
  "local_model_name": "codellama",
  "ollama_endpoint": "http://localhost:11434"
}

🎯 进阶功能

1. 与 VS Code 集成

# 安装 VS Code 扩展
code --install-extension opencode.vscode-opencode

在 VS Code 中使用快捷键:

  • Ctrl+Shift+P → OpenCode: Ask
  • Ctrl+Shift+A → OpenCode: Analyze Current File

2. 项目级上下文

# 设置项目上下文(让 AI 了解整个项目)
opencode context add src/
opencode context add package.json
opencode context list

3. 自定义提示词模板

~/.config/opencode/templates/ 下创建模板文件:

<!-- review.md -->
请审查以下代码,关注:
1. 潜在的 bug
2. 性能问题
3. 安全隐患
4. 代码风格问题

{code}

使用模板:

opencode review src/app.ts --template review

❓ 常见问题

Q1: 提示 "command not found"

解决方法:确保安装目录在 PATH 环境变量中,或重新打开终端。

Q2: API 调用失败

解决方法

  1. 检查网络连接
  2. 确认 API Key 正确
  3. 检查 API 额度是否用完

Q3: 本地模型运行缓慢

解决方法

  • 使用更小的模型(如 tinyllama
  • 确保有足够的 RAM
  • 考虑使用 GPU 加速

📚 更多资源


📝 更新日志

# 查看版本
opencode --version

# 更新到最新版
opencode update