Day 7:编译部署——Agent上线
昨天的问题
Agent 跑在 go run 里,关了终端就没了。真实用户怎么用?
今天做什么
把 Agent 编译成二进制文件,通过 HTTP 接口对外服务。同时加流式输出——让用户看到 Agent 一字一字回复。
代码
go
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"time"
)
// ===== HTTP 服务 =====
type ChatRequest struct {
Message string `json:"message"`
SessionID string `json:"session_id"`
}
type ChatResponse struct {
Reply string `json:"reply"`
ToolUsed string `json:"tool_used,omitempty"`
}
func main() {
// 初始化 Agent
agent := NewAgent()
// 注册路由
http.HandleFunc("/chat", func(w http.ResponseWriter, r *http.Request) {
var req ChatRequest
json.NewDecoder(r.Body).Decode(&req)
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
reply, err := agent.Respond(ctx, req.SessionID, req.Message)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
json.NewEncoder(w).Encode(ChatResponse{
Reply: reply,
})
})
// 流式接口
http.HandleFunc("/chat/stream", func(w http.ResponseWriter, r *http.Request) {
var req ChatRequest
json.NewDecoder(r.Body).Decode(&req)
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
flusher, _ := w.(http.Flusher)
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
reply, _ := agent.Respond(ctx, req.SessionID, req.Message)
// 模拟流式输出:一个字一个字返回
for _, ch := range reply {
fmt.Fprintf(w, "data: %s\n\n", string(ch))
flusher.Flush()
time.Sleep(30 * time.Millisecond)
}
fmt.Fprintf(w, "data: [DONE]\n\n")
flusher.Flush()
})
fmt.Println("🚀 Agent 服务启动在 http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
// ===== 编译部署 =====
// go build -o agent
// ./agent
//
// 镜像部署(Dockerfile 只需3行):
// FROM scratch
// COPY agent /agent
// ENTRYPOINT ["/agent"]
//
// 镜像大小:约 10MB(Python版 300MB+)运行
bash
# 编译
go build -o agent
# 启动
./agent
# 测试
curl -X POST http://localhost:8080/chat \
-H "Content-Type: application/json" \
-d '{"message":"查一下订单 #12345","session_id":"user_1"}'项目复盘
7 天,从回声筒到可以上线的 Agent。回顾一下你做了什么:
| Day | 加了什么 | Agent 的能力 |
|---|---|---|
| 1 | 骨架 | 回声筒 |
| 2 | Prompt + Mock LLM | 有人设了 |
| 3 | RAG 知识库 | 能查文档了 |
| 4 | Eino Tool | 能干活了 |
| 5 | Memory | 能记事了 |
| 6 | MCP | 工具标准化了 |
| 7 | HTTP + 编译部署 | 上线了 |
Go 技术栈全貌:
项目一完成。你现在有一个能上线的智能客服 Agent 了。

