使用 Go 语言打造专属的 Gemini AI 聊天应用

源自开发者
源自开发者
发布于 2024-08-17 / 70 阅读
3
1

使用 Go 语言打造专属的 Gemini AI 聊天应用

在人工智能领域,大型语言模型(LLM)正掀起一场技术革命。其中,Google 最新推出的 Gemini 模型以其强大的性能和多模态处理能力备受瞩目。本文将引领你使用 GoLang 语言,结合 Redis 缓存,构建一个基于 Gemini Pro 的 AI 聊天应用。

项目概览

本项目旨在创建一个能够与用户进行自然语言交互的聊天应用。它利用 Gemini Pro 模型理解用户输入,并生成相应的回复。为了提升用户体验,我们还将引入 Redis 缓存,用于存储用户的历史对话,打造更加个性化的聊天体验。

技术栈

  • GoLang: 以其简洁、高效和并发性著称,是构建高性能应用的理想选择。
  • Gin: 轻量级 Web 框架,提供路由、中间件等功能,简化 Web 应用开发流程。
  • Gemini Pro: Google 最新推出的 LLM,具备强大的自然语言理解和生成能力。
  • Redis: 高性能内存数据库,用作缓存以存储用户历史对话。

项目结构

app  
|-- .gitignore  
|-- Dockerfile  
|-- config.yml  
|-- docker-compose.yml  
|-- go.mod  
|-- go.sum  
|-- main.go
|-- handlers  
|   |-- index.go  
|   |-- run.go
|-- models  
|   |-- models.go
|-- routers  
|   |-- router.go
|-- service  
|   |-- redis.go
|-- static  
|   |-- app.js  
|   |-- autosize.min.js  
|   |-- index.html  
|   |-- logo-black.svg  
|   |-- share.png  
|   |-- styles.css
|-- utils  
|   |-- env.go

核心功能实现

1. 接收用户输入并调用 Gemini Pro 生成回复

func Run(c *gin.Context) {
    // ... (绑定请求数据) ...

    ctx := context.Background()
    client, err := genai.NewClient(ctx, option.WithAPIKey(prompt.APIKey))
    // ... (错误处理) ...
    defer client.Close()

    model := client.GenerativeModel("gemini-pro")
    resp, err := model.GenerateContent(ctx, genai.Text(prompt.Input))
    // ... (错误处理) ...

    formattedContent := formatResponse(resp)

    // ... (存储历史记录) ...

    c.JSON(http.StatusOK, gin.H{
        "input":    prompt.Input,
        "response": formattedContent,
        "history":  history,
    })
}

这段代码展示了如何接收用户输入,并调用 Gemini Pro API 生成回复。首先,我们使用 genai.NewClient 创建一个 Gemini 客户端,然后指定要使用的模型为 gemini-pro。接着,调用 model.GenerateContent 方法,传入用户输入,即可获得模型生成的回复。

2. 使用 Redis 缓存存储用户历史对话

func StoreHistory(userID, input, response string) {
    // ... (计算哈希值) ...

    historyKey := fmt.Sprintf("history:%s", hashedUserID)
    // ... (日志记录) ...

    maxHistoryLength := 10
    entry := fmt.Sprintf(`{"input": "%s", "response": "%s"}`, input, response)

    rdb.LPush(context.Background(), historyKey, entry)
    rdb.LTrim(context.Background(), historyKey, 0, int64(maxHistoryLength-1))
    expiration := time.Hour * 24
    rdb.Expire(context.Background(), historyKey, expiration)
}

为了实现个性化聊天体验,我们使用 Redis 存储用户的历史对话。StoreHistory 函数首先计算用户 ID 的哈希值,然后将用户的输入和模型的回复拼接成 JSON 字符串,存储到 Redis 列表中。同时,我们限制了历史记录的最大长度,并设置了 24 小时的过期时间。

3. 检索历史对话并返回给用户

func GetHistory(userID string) []string {
    // ... (计算哈希值) ...

    historyKey := fmt.Sprintf("history:%s", hashedUserID)
    result, err := rdb.LRange(context.Background(), historyKey, 0, -1).Result()
    // ... (错误处理) ...

    return result
}

GetHistory 函数用于检索用户的历史对话。它首先计算用户 ID 的哈希值,然后从 Redis 列表中获取所有历史记录,并将其返回给用户。

API 接口设计

router.GET("/", handlers.Index)  
router.POST("/run", handlers.Run)  
router.POST("/fetchHistory", handlers.HandleFetchHistory)

我们定义了三个 API 接口:

  • /: 根路径,用于展示应用首页。
  • /run: 接收用户输入并返回模型生成的回复。
  • /fetchHistory: 获取用户的历史对话记录。

总结

本文介绍了如何使用 GoLang 语言,结合 Gemini Pro 和 Redis 缓存,构建一个功能完善的 AI 聊天应用。通过合理的技术选型和架构设计,我们实现了高效的对话生成和个性化的用户体验。相信随着 LLM 技术的不断发展,未来将涌现出更多基于此类技术的创新应用。


评论