likes
comments
collection
share

龘龘龘-代码上的年味-通过AI生成春联🐲

作者站长头像
站长
· 阅读数 5

目录

龘龘龘-代码上的年味-通过AI生成春联🐲

前言

现在是2024年1月24日农历癸卯年腊月十四,距离甲辰龙年春节还有17天,年关愈近、年味愈浓,今年让我们使用AI+GoLang+Vue来实现春联的生成。

无论2023年经历了什么、发生了什么,往事成风,向前看,别回头。

技术栈

  • Go:接口的编写以Go作为后端开发语言,GoLang相对于Java来说,它提供了高效的并发模型和简洁的语法,适合作为Java开发者的第二语言。
  • Vue.js: 一个流行的JavaScript框架,用于构建用户所看到的界面。
  • HTTP:使用Go的内置net/http包来处理HTTP请求和构建HTTP服务器,简化了与前端的通信。
  • JSON: 通过Go内置的encoding/json包实现JSON数据的序列化和反序列化,便于与前端进行数据交互。
  • 编码工具: Visual Studio Code

实现思路

近年来,随着自然语言处理(NLP)领域的迅速发展,越来越多基于NLP的产品应运而生。这些产品为用户和开发者提供了低成本、高效快速的体验,展示了人工智能的卓越魅力,为生活带来了极大的便利。本文以调用百度智能云的语言大模型生成春联为例,通过将生成的春联以JSON的形式返回给前端,使前端能够灵活展示横批、上联和下联的内容。这个过程为读者提供了一个深入了解如何利用NLP技术为应用开发增加趣味和智能化的窗口,更重要的是给伏案编码的大家带来一些年味,感受中国传统节日的魅力。

百度智能云申请

百度智能云-千帆大模型申请

龘龘龘-代码上的年味-通过AI生成春联🐲

本案例使用的大模型为: 龘龘龘-代码上的年味-通过AI生成春联🐲

0.0012元/千tokes,亲测,每个回答约使用50tokens。

接口文档:

千帆大模型-API鉴权及调用

在线调用:

在线调用地址

龘龘龘-代码上的年味-通过AI生成春联🐲

ERNIE-Bot模型使用:

龘龘龘-代码上的年味-通过AI生成春联🐲

后端实现

以下是基于Go语言调用千帆大模型的代码案例:

package main

import (
    "encoding/json"
    "fmt"
    "io"
    "io/ioutil"
    "net/http"
    "strings"
    "time"
)

// BaiduAIChatClient 实现了 AIChatClient 接口,与百度 AI 对话服务交互
type BaiduAIChatClient struct {
    AccessToken string
}

// ChatCompletionResponse 定义 Chat Completion 的返回体结构
type ChatCompletionResponse struct {
    ID               string `json:"id"`
    Object           string `json:"object"`
    Created          int64  `json:"created"`
    Result           string `json:"result"`
    IsTruncated      bool   `json:"is_truncated"`
    NeedClearHistory bool   `json:"need_clear_history"`
    FinishReason     string `json:"finish_reason"`
    Usage            struct {
        PromptTokens     int `json:"prompt_tokens"`
        CompletionTokens int `json:"completion_tokens"`
        TotalTokens      int `json:"total_tokens"`
    } `json:"usage"`
}

// NewBaiduAIChatClient 创建一个 BaiduAIChatClient 实例
func NewBaiduAIChatClient(accessToken string) *BaiduAIChatClient {
    return &BaiduAIChatClient{
        AccessToken: accessToken,
    }
}

// GetChatCompletion 实现了 AIChatClient 接口的方法,获取 AI 对话完成结果
func (c *BaiduAIChatClient) GetChatCompletion(prompt string) (string, error) {
    url := fmt.Sprintf("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=%s", c.AccessToken)
    payload := strings.NewReader(fmt.Sprintf(`{"messages":[{"role":"user","content":"%s"}],"disable_search":false,"enable_citation":false}`, prompt))
    client := &http.Client{}
    req, err := http.NewRequest("POST", url, payload)

    if err != nil {
        return "", err
    }
    req.Header.Add("Content-Type", "application/json")

    res, err := client.Do(req)
    if err != nil {
        return "", err
    }
    defer func(Body io.ReadCloser) {
        err := Body.Close()
        if err != nil {

        }
    }(res.Body)

    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        return "", err
    }

    // 解析 JSON 数据到 ChatCompletionResponse 结构体
    var response ChatCompletionResponse
    if err := json.Unmarshal(body, &response); err != nil {
        return "", err
    }

    // 返回解析后的结果
    return response.Result, nil
}

// handleRequest 处理前端请求的处理器函数
func handleRequest(w http.ResponseWriter, _ *http.Request) {

    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
    w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
    // 创建 BaiduAIChatClient 实例
    baiduClient := NewBaiduAIChatClient("your_token")

    // 调用 GetChatCompletion 方法获取对话完成结果
    prompt := "生成新年对联"
    result, err := baiduClient.GetChatCompletion(prompt)
    if err != nil {
        http.Error(w, "Error fetching result", http.StatusInternalServerError)
        return
    }

    // 创建一个 JSON 结构体
    response := struct {
        Message     string    `json:"message"`
        Result      string    `json:"result"`
        RequestTime time.Time `json:"requestTime"`
        Status      int       `json:"status"`
    }{
        Message:     "Hello from the server!",
        Result:      result,
        RequestTime: time.Now(),
        Status:      http.StatusOK,
    }

    // 将数据编码为 JSON 格式
    responseJSON, err := json.Marshal(response)
    if err != nil {
        http.Error(w, "Error encoding JSON", http.StatusInternalServerError)
        return
    }

    // 设置响应头
    w.Header().Set("Content-Type", "application/json")

    // 发送JSON响应给前端
    w.Write(responseJSON)
}

func main() {
    // 注册处理器函数
    http.HandleFunc("/api", handleRequest)

    // 启动HTTP服务器,监听端口8081
    err := http.ListenAndServe(":8081", nil)
    if err != nil {
        fmt.Println("Error starting the server:", err)
    }
}

前端实现

前端使用Vue渲染页面。

本人一直从事Java后端接口开发工作,对前端并不了解,因此使用网络案例实现对联展示。

前端素材案例:

HTML春联(部分Vue)有源码_有素材_包满意

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新年祝福</title>
    <style>
        * {
            margin: 0px auto;
            padding: 0px;
            font-family: '隶书';
            font-size: 2rem;
            border-radius: 12px;
        }

        .info {
            width: 100%;
        }

        .top {
            width: 20%;
            background-color: red;
            text-align: center;
            background-size: 95px 100%;
            background-repeat: repeat-x;
        }

        span {
            margin-left: 15px;
            margin-right: 15px;
        }

        .content {
            width: 35%;
        }

        .left {
            text-align: center;
            float: left;
        }

        .right {
            text-align: center;
            float: right;
        }

        .left,
        .right {
            width: 15%;
            height: 70%;
            background-color: red;
            background-size: 100%;
            background-repeat: repeat-y;
            line-height: 100px;
        }

        .inText {
            text-align: center;
            width: 100%;
        }

        input {
            width: 32%;
        }
    </style>
</head>

<body>
    <div id="app">
        <div class="info">
            <div class="top">
                <span>{{topText}}</span>
            </div>
            <div class="content">
                <!-- 右侧是上联 -->
                <div class="right">{{rightText}}</div>
                <!-- 左侧是下联 -->
                <div class="left">{{leftText}}</div>
            </div>
        </div>
        <div style="clear: both;"></div>
        <hr />
        <div class="inText">
            <button @click="generateCouplet" style="background-color: red;">生成新春联</button>
        </div>
    </div>

    <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    <script>
        new Vue({
            el: "#app",
            data: {
                leftText: "",
                rightText: "",
                topText: "恭 喜 发 财"
            },
            methods: {
                // 生成新的春联
                generateCouplet() {
                    // 请将下面的URL替换为实际的后端接口URL
                    const apiUrl = "http://localhost:8081/api"; // 请根据实际情况修改接口地址

                    fetch(apiUrl)
                        .then(response => response.json())
                        .then(data => {
                            // 解析后端返回的数据
                            const result = data.result;
                            const lines = result.split('\n');

                            // 更新数据
                            this.topText = lines[2].split(':')[1].trim(); // 获取横批信息
                            this.leftText = lines[1].split(':')[1].trim(); // 获取下联信息
                            this.rightText = lines[0].split(':')[1].trim(); // 获取上联信息
                        })
                        .catch(error => console.error("Error fetching data:", error));
                }
            },
            mounted() {
                // 页面加载时默认获取一次春联数据
                this.generateCouplet();
            }
        });

    </script>

</body>

</html>

如何运行

后端接口

编写好go语言文件代码后,在控制台执行命令:

go run xxxx.go

如:

龘龘龘-代码上的年味-通过AI生成春联🐲

此时后端接口已启动,使用API测试:

龘龘龘-代码上的年味-通过AI生成春联🐲

前端页面

使用chrome浏览器打开即可。

展示

龘龘龘-代码上的年味-通过AI生成春联🐲

龘龘龘-代码上的年味-通过AI生成春联🐲