编程 GoLang语言,结合Google的GeminiPro模型和Redis缓存,构建一个功能完善的AI聊天应用

2024-11-19 01:37:16 +0800 CST views 831

使用 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 将用户输入和回复存储为历史记录。我们限制了历史记录的最大长度为 10 条,并设置了 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 函数用于从 Redis 检索用户的历史对话记录,并将其返回给用户。

API 接口设计

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

我们定义了三个 API 接口:

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

总结

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

推荐文章

LLM驱动的强大网络爬虫工具
2024-11-19 07:37:07 +0800 CST
支付轮询打赏系统介绍
2024-11-18 16:40:31 +0800 CST
ElasticSearch简介与安装指南
2024-11-19 02:17:38 +0800 CST
html文本加载动画
2024-11-19 06:24:21 +0800 CST
Vue3中如何实现状态管理?
2024-11-19 09:40:30 +0800 CST
PHP 允许跨域的终极解决办法
2024-11-19 08:12:52 +0800 CST
Go 接口:从入门到精通
2024-11-18 07:10:00 +0800 CST
Node.js中接入微信支付
2024-11-19 06:28:31 +0800 CST
html一个全屏背景视频
2024-11-18 00:48:20 +0800 CST
程序员茄子在线接单