Go 语言实现的 AI 编程助手

一、项目背景

基于对 AI 编程助手架构的学习和研究,使用 Go 语言实现一个类似的 CLI 工具。项目名称 Gallifrey Code,灵感来源于《神秘博士》中时间领主的母星。

设计目标

  • 单二进制部署 - 纯 Go 实现,无需运行时环境
  • 双模式输出 - TUI 交互 + —print 无头模式
  • 多 API 支持 - Anthropic API + OpenAI 兼容 API
  • 可扩展工具系统 - 模块化的工具接口设计

二、架构设计

2.1 分层架构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
┌─────────────────────────────────────────────────────────────┐
│ CLI Layer │
│ (cobra CLI, TUI with bubbletea, --print mode) │
├─────────────────────────────────────────────────────────────┤
│ Coordinator Layer │
│ (Single Agent / Multi-Agent orchestration) │
├─────────────────────────────────────────────────────────────┤
│ Tool Layer │
│ (Bash, Read, Edit, Write, Glob, Grep, MCP, Agent, Memory) │
├─────────────────────────────────────────────────────────────┤
│ Service Layer │
│ (API Client, Auth, Memory, Permission) │
├─────────────────────────────────────────────────────────────┤
│ Infrastructure Layer │
│ (Config, Logger, Context, State Manager) │
└─────────────────────────────────────────────────────────────┘

2.2 核心设计理念

优先考虑单二进制部署

Go 语言天然适合构建 CLI 工具:

  • 静态编译,无运行时依赖
  • 交叉编译简单
  • 启动速度快

工具接口设计

1
2
3
4
5
6
7
type Tool interface {
Name() string
Description() string
InputSchema() json.RawMessage
Execute(ctx context.Context, input json.RawMessage) (*Result, error)
RequiresConfirmation() bool
}

这个接口设计允许:

  • 工具的动态注册和发现
  • 统一的权限控制
  • 方便扩展新工具

System Prompt 优先级系统

1
2
3
4
5
6
7
type PromptManager struct {
override string // Priority 0: 强制覆盖
coordinator string // Priority 1: 协调模式
agent string // Priority 2: 子 Agent
custom string // Priority 3: 用户自定义
defaultP string // Priority 4: 默认
}

三、核心模块实现

3.1 API 客户端

支持双提供商架构,流式响应处理使用 channel 传递 StreamEvent。

3.2 Agent 核心循环

1
API Call → Process Stream → Tools? → Execute Tool → Add Results → Loop

3.3 工具系统

工具 说明 权限
Bash 执行 shell 命令 需确认
Read 读取文件 无需确认
Write 写入文件 需确认
Edit 编辑文件 需确认
Glob 文件搜索 无需确认
Grep 内容搜索 无需确认
Memory 记忆管理 无需确认

3.4 多 Agent 协调

支持并行创建多个子 Agent,独立的 System Prompt,结果聚合。

3.5 TUI 界面

使用 bubbletea 框架实现,输入框使用 bubbles/textinput,样式使用 lipgloss。

四、技术选型

模块 选择理由
CLI cobra 成熟稳定,自动补全
TUI bubbletea 同类最佳,声明式
配置 viper 多格式支持,环境变量

五、使用方式

配置

1
2
3
4
# 环境变量
export ANTHROPIC_API_KEY=your-key

# 或配置文件 ~/.config/gallifrey-code/config.yaml

命令

1
2
3
4
5
6
7
8
# TUI 模式
gallifrey-code

# 无头模式
gallifrey-code -p "帮我写一个 hello world"

# 指定模型
gallifrey-code -p "你好" --model claude-opus-4-6

六、实现统计

  • Go 文件: 19 个
  • 代码行数: ~3,600 行
  • 提交次数: 12 次

七、免责声明

本项目为个人学习项目,仅供教育和研究目的使用。所有代码均为原创实现,不包含任何第三方知识产权内容。请勿将本项目用于商业用途。

相关链接