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

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

使用 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 技术的不断发展,未来将涌现出更多基于此类技术的创新应用。

推荐文章

免费常用API接口分享
2024-11-19 09:25:07 +0800 CST
Go配置镜像源代理
2024-11-19 09:10:35 +0800 CST
利用图片实现网站的加载速度
2024-11-18 12:29:31 +0800 CST
H5抖音商城小黄车购物系统
2024-11-19 08:04:29 +0800 CST
liunx宝塔php7.3安装mongodb扩展
2024-11-17 11:56:14 +0800 CST
markdowns滚动事件
2024-11-19 10:07:32 +0800 CST
Rust async/await 异步运行时
2024-11-18 19:04:17 +0800 CST
使用Python实现邮件自动化
2024-11-18 20:18:14 +0800 CST
Golang 几种使用 Channel 的错误姿势
2024-11-19 01:42:18 +0800 CST
百度开源压测工具 dperf
2024-11-18 16:50:58 +0800 CST
支付页面html收银台
2025-03-06 14:59:20 +0800 CST
js迭代器
2024-11-19 07:49:47 +0800 CST
vue打包后如何进行调试错误
2024-11-17 18:20:37 +0800 CST
Nginx 性能优化有这篇就够了!
2024-11-19 01:57:41 +0800 CST
filecmp,一个Python中非常有用的库
2024-11-19 03:23:11 +0800 CST
js函数常见的写法以及调用方法
2024-11-19 08:55:17 +0800 CST
程序员茄子在线接单