接續上一篇,用 Go 打造本地 LLM 聊天機器人:整合 llm-go 與 go-llama.cpp,此篇開始建構前端與 API 接口
執行環境需求
? ? Go 1.20+
? ? C++ toolchain(macOS: Xcode Command Line Tools / Linux: g++)
? ? GGUF 格式模型(如:Gemma-2B.gguf, Llama2-7B.gguf)
? ? 可選:make 工具簡化編譯
一、專案整合架構更新
llama-chatbot-go/
├── cmd/
│ ├── main.go # CLI 主程式
│ └── main_web.go # 啟動 HTTP Server
├── llm/
│ ├── model.go # 封裝模型邏輯
│ └── chat.go # 管理 prompt 歷史
├── web/
│ ├── handler/
│ │ └── chat.go # 處理 POST /api/chat
│ ├── routes/
│ │ └── router.go # gin 路由
│ └── ui/
│ └── index.html # Web 前端頁面
├── config/
│ └── persona.yaml # 角色設定
├── go.mod
└── docs/ # Swagger 文檔生成目錄
二、Swagger 接口文檔
go install github.com/swaggo/swag/cmd/swag@latest
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/files
新增註解至 web/routes/router.go:
// @title LLaMA ChatBot API
// @version 1.0
// @description 基于 go-llama.cpp 與 llm-go 的本地語言模型聊天機器人 API
// @host localhost:8080
// @BasePath /// @contact.name 開發者支援
// @contact.email dev@example.com
在 main_web.go 中加入 Swagger 路由:
import ("github.com/swaggo/gin-swagger""github.com/swaggo/files"_ "your_project/docs" // docs 是 swag init 成的目錄
)r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
在專案根目錄執行
swag init
瀏覽 http://localhost:8080/swagger/index.html 即可查看中文接口文檔。
三、Web 前端介面(純 HTML)
在 web/ui/index.html 建立:
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>LLaMA Chat</title>
</head>
<body><h2>LLaMA 聊天介面</h2><div><textarea id="input" rows="3" cols="60" placeholder="輸入你的問題..."></textarea><br><button onclick="send()">發送</button></div><pre id="response"></pre><script>async function send() {const input = document.getElementById('input').value;const res = await fetch('/api/chat', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ message: input })});const data = await res.json();document.getElementById('response').innerText = data.response || JSON.stringify(data);}</script>
</body>
</html>
并在你的 main_web.go 中加入靜態檔案伺服:
r.Static("/ui", "./web/ui")
四、Swagger 集成步驟
改寫 main.go
以下是具 Swagger 支援的 main.go,加入 /chat 路由文檔與 /swagger/index.html 的瀏覽功能:
package mainimport ("net/http""github.com/gin-gonic/gin""github.com/go-skynet/go-llama.cpp"_ "llama-chat/docs" // swagger 文件註冊swaggerFiles "github.com/swaggo/files"ginSwagger "github.com/swaggo/gin-swagger"
)// ChatRequest 用戶輸入
type ChatRequest struct {Message string `json:"message" example:"你好,請介紹你自己"`
}// ChatResponse 模型回應
type ChatResponse struct {Reply string `json:"reply" example:"你好,我是部署在本地的語言模型。"`
}// @title Gemma LLM Chatbot API
// @version 1.0
// @description 使用 Llama.cpp 驅動的本地 LLM 聊天接口
// @host localhost:8080
// @BasePath /
func main() {r := gin.Default()model := llama.LoadModel("path/to/gemma-2b.gguf", llama.Params{Threads: 4})defer model.Close()// swagger 文檔路由r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))// 聊天接口// @Summary 啟動聊天// @Description 提交一段文字并取得回應// @Accept json// @Produce json// @Param message body ChatRequest true "用戶輸入"// @Success 200 {object} ChatResponse// @Router /chat [post]r.POST("/chat", func(c *gin.Context) {var req ChatRequestif err := c.ShouldBindJSON(&req); err != nil {c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})return}resp := model.Predict(llama.PredictOptions{Prompt: req.Message,MaxTokens: 128,Stream: false,})c.JSON(http.StatusOK, ChatResponse{Reply: resp.Content})})r.Run(":8080")
}
瀏覽與測試
打開你的瀏覽器進入:
http://localhost:8080/swagger/index.html
補充說明
? 所有 @XXX 是 Swagger 的注解標簽。
? 如果你日后有多模型、多任務接口,可以用 @Tag 區分模組。
? 所有 example: 設定會在 Swagger UI 預填樣例值,便于測試。
下一步將會
? Swagger + Swagger UI(開發者介面)
使用技術:Swagger YAML + Swagger UI
特征:
? 適合 API 測試、技術人員驗證用
? 具備 POST /chat、GET /healthz 等接口說明
? 支援 request/response 模擬
? 美化版 Chat Web App(推薦給公開展示用)
使用技術::Vue.js / React + Tailwind + WebSocket Streaming
特征:
? 支援上下文顯示
? 支援多輪對話
? 支援多角色選擇與人格切換
? UI 類似 ChatGPT 界面
?
參考鏈接:
?
本項目 README
🧾 GitCode 開源項目地址:
👉 GitCode - 全球開發者的開源社區,開源代碼托管平臺
我是一位獨立開發者,加入使用者社群,一起討論私有化 LLM 與 RAG 架構實踐,歡迎 Star、Fork、Issue 交流。
?