GoClaw - Go SDK
约 1275 字大约 4 分钟
2026-03-07
供 Go 开发者二次开发的 SDK,快速构建自定义 Agent。
核心特性
Go 原生
- 纯 Go 实现
- 无外部依赖
- Goroutine 并发
- 静态编译
易于扩展
- 模块化设计
- 插件系统
- 接口清晰
- 文档完善
高性能
- 低延迟
- 高吞吐
- 内存友好
- 资源可控
完整功能
- LLM 调用
- 工具系统
- 记忆管理
- 会话管理
快速开始
安装
# 使用 Go Modules
go get github.com/smallnest/goclaw
# 或克隆源码
git clone https://github.com/smallnest/goclaw.git基础使用
package main
import (
"fmt"
"github.com/smallnest/goclaw"
)
func main() {
// 创建 Agent
agent := goclaw.NewAgent(
goclaw.WithProvider("openai"),
goclaw.WithModel("gpt-4"),
goclay.apiKey("your-api-key"),
)
// 对话
resp, err := agent.Chat("你好,请介绍一下自己")
if err != nil {
panic(err)
}
fmt.Println(resp.Content)
}完整配置
agent := goclaw.NewAgent(
goclaw.WithProvider("openai"),
goclaw.WithModel("gpt-4"),
goclaw.WithAPIKey("your-api-key"),
goclaw.WithBaseURL("https://api.openai.com/v1"),
goclaw.WithTemperature(0.7),
goclaw.WithMaxTokens(2000),
// 工具配置
goclaw.WithTools(
goclaw.SearchTool{},
goclaw.CalculatorTool{},
),
// 记忆配置
goclaw.WithMemory(
goclaw.NewBufferMemory(10),
),
)技术架构
核心组件
// Agent 核心
type Agent struct {
provider LLMProvider
memory Memory
tools ToolRegistry
config Config
}
// 对话流程
func (a *Agent) Chat(input string) (*Response, error) {
// 1. 构建上下文
ctx := a.buildContext(input)
// 2. LLM 调用
resp, err := a.provider.Complete(ctx)
if err != nil {
return nil, err
}
// 3. 处理工具调用
for resp.NeedToolCall() {
result := a.tools.Execute(resp.ToolCalls())
ctx.AddMessage(result)
resp, err = a.provider.Complete(ctx)
if err != nil {
return nil, err
}
}
// 4. 保存记忆
a.memory.Save(input, resp.Content)
return resp, nil
}工具系统
// 工具接口
type Tool interface {
Name() string
Description() string
Parameters() map[string]Parameter
Execute(params map[string]interface{}) (string, error)
}
// 内置搜索工具
type SearchTool struct{}
func (t *SearchTool) Name() string {
return "web_search"
}
func (t *SearchTool) Description() string {
return "搜索网络信息"
}
func (t *SearchTool) Execute(params map[string]interface{}) (string, error) {
query := params["query"].(string)
return searchWeb(query)
}
// 自定义工具
type MyTool struct{}
func (t *MyTool) Name() string {
return "my_tool"
}
func (t *MyTool) Execute(params map[string]interface{}) (string, error) {
// 你的逻辑
return "result", nil
}记忆系统
// 记忆接口
type Memory interface {
Save(input, output string)
GetContext(maxTokens int) string
Clear()
}
// 缓冲区记忆
type BufferMemory struct {
messages []Message
maxCount int
}
func (m *BufferMemory) Save(input, output string) {
m.messages = append(m.messages,
Message{Role: "user", Content: input},
Message{Role: "assistant", Content: output},
)
// 保持最大数量
if len(m.messages) > m.maxCount {
m.messages = m.messages[len(m.messages)-m.maxCount:]
}
}
// 向量记忆(需要向量数据库)
type VectorMemory struct {
client vectordb.Client
embedder embedder.Embedder
}
func (m *VectorMemory) GetContext(query string, topK int) string {
// 1. 向量化查询
vec := m.embedder.Embed(query)
// 2. 相似度搜索
results := m.client.Search(vec, topK)
// 3. 构建上下文
return concatenate(results...)
}插件系统
创建插件
// 插件接口
type Plugin interface {
Name() string
Init(agent *Agent) error
OnMessage(msg *Message) (*Message, error)
OnResponse(resp *Response) (*Response, error)
}
// 日志插件
type LoggerPlugin struct{}
func (p *LoggerPlugin) Name() string {
return "logger"
}
func (p *LoggerPlugin) Init(agent *Agent) error {
log.Info("Logger plugin initialized")
return nil
}
func (p *LoggerPlugin) OnMessage(msg *Message) (*Message, error) {
log.Infof("Received: %s", msg.Content)
return msg, nil
}
func (p *LoggerPlugin) OnResponse(resp *Response) (*Response, error) {
log.Infof("Response: %s", resp.Content)
return resp, nil
}
// 使用插件
agent := goclaw.NewAgent()
agent.Use(LoggerPlugin{})插件示例
// 限流插件
type RateLimitPlugin struct {
requestsPerMinute int
}
func (p *RateLimitPlugin) OnMessage(msg *Message) (*Message, error) {
if !p.allow() {
return &Message{
Content: "请求过于频繁,请稍后再试",
}, nil
}
return msg, nil
}
// 敏感词过滤插件
type FilterPlugin struct {
keywords []string
}
func (p *FilterPlugin) OnMessage(msg *Message) (*Message, error) {
for _, kw := range p.keywords {
msg.Content = strings.ReplaceAll(msg.Content, kw, "***")
}
return msg, nil
}高级功能
流式输出
stream, err := agent.StreamChat("给我讲个故事")
if err != nil {
panic(err)
}
for chunk := range stream {
fmt.Print(chunk.Content)
}并发处理
// 并发对话
results := make(chan string, 10)
questions := []string{
"问题1",
"问题2",
"问题3",
}
var wg sync.WaitGroup
for _, q := range questions {
wg.Add(1)
go func(q string) {
defer wg.Done()
resp, _ := agent.Chat(q)
results <- resp.Content
}(q)
}
go func() {
wg.Wait()
close(results)
}()
for result := range results {
println(result)
}中间件
// 请求前处理
agent.Use(func(next Handler) Handler {
return func(req *Request) (*Response, error) {
// 添加前缀
req.Messages = append([]Message{
{Role: "system", Content: "你是一个有帮助的助手"},
}, req.Messages...)
return next(req)
}
})
// 响应后处理
agent.UseResponse(func(next Handler) Handler {
return func(req *Request) (*Response, error) {
resp, err := next(req)
if err != nil {
return nil, err
}
// 添加后缀
resp.Content += "\n\n如有其他问题,欢迎继续提问!"
return resp, nil
}
})示例项目
简单聊天机器人
package main
import (
"fmt"
"github.com/smallnest/goclaw"
)
func main() {
agent := goclaw.NewAgent(
goclaw.WithProvider("openai"),
goclaw.WithAPIKey("your-key"),
)
fmt.Println("[GoClaw] 聊天机器人")
fmt.Println("输入 'quit' 退出\n")
for {
fmt.Print("> ")
var input string
fmt.Scanln(&input)
if input == "quit" {
break
}
resp, err := agent.Chat(input)
if err != nil {
fmt.Printf("错误: %v\n", err)
continue
}
fmt.Printf("[Bot]: %s\n\n", resp.Content)
}
}Slack 机器人
package main
import (
"github.com/smallnest/goclaw"
"github.com/slack-go/slack"
)
func main() {
agent := goclaw.NewAgent(
goclaw.WithProvider("openai"),
goclaw.WithAPIKey("your-key"),
)
api := slack.New("xoxb-your-token")
rtm := api.NewRTM()
go rtm.ManageConnection()
for msg := range rtm.IncomingEvents {
if ev, ok := msg.Data.(*slack.MessageEvent); ok {
if ev.Channel == "your-channel" {
resp, _ := agent.Chat(ev.Text)
api.PostMessage(ev.Channel, slack.MsgText(resp.Content))
}
}
}
}适用场景
推荐使用
- Go 项目集成: 已有 Go 项目需要 AI 能力
- 二次开发: 需要深度定制 Agent 行为
- 高性能需求: 需要低延迟、高吞吐
- 微服务: 作为微服务的 AI 组件
与其他版本对比
| 特性 | GoClaw SDK | GoClaw 网关 | 官方版 |
|---|---|---|---|
| 用途 | 开发框架 | API 网关 | 全功能 |
| 集成方式 | 代码嵌入 | HTTP 调用 | npm 包 |
| 复杂度 | 中等 | 低 | 高 |
相关链接
- GitHub: smallnest/goclaw
- 文档: 使用文档
- Go Doc: pkg.go.dev
- 问题反馈: Issues
许可证
MIT License - 详见 LICENSE