MENU

golang基于chatgpt实现多语言翻译

April 6, 2023 • 默认分类

准备

  1. openai api key
  2. 程序根目录新建 .env 配置文件,填写 CHATGPT_API_KEY=[openai-api-key]
package main

import (
    "bytes"
    "encoding/json"
    "flag"
    "fmt"
    "io/ioutil"
    "net/http"
    "os"

    simplejson "github.com/bitly/go-simplejson"
    _ "github.com/joho/godotenv/autoload"
)

type Message struct {
    Role    string `json:"role"`
    Content string `json:"content"`
}

type ChatRequest struct {
    MaxTokens   int       `json:"max_tokens"`
    Temperature float64   `json:"temperature"`
    Model       string    `json:"model"`
    Messages    []Message `json:"messages"`
}

func chatgpt(chat ChatRequest) (reply string) {
    // 构造请求的 JSON Body 数据
    jsonData, err := json.Marshal(chat)
    if err != nil {
        fmt.Println(err)
        return
    }

    // 设置 HTTP 请求
    req, err := http.NewRequest("POST", "https://api.openai.com/v1/chat/completions", bytes.NewBuffer(jsonData))
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", "Bearer "+os.Getenv("CHATGPT_API_KEY"))

    // 发送 HTTP 请求
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer resp.Body.Close()

    // 读取 HTTP 响应
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println(err)
        return
    }
    reply = string(body)
    return
}

func translate(msg string) *Message {
    txt := fmt.Sprintf("[%s],翻译成英文", msg)
    fmt.Printf("[原文]: \n%s\n", txt)
    chat := ChatRequest{
        MaxTokens:   100,
        Temperature: 0.7,
        Model:       "gpt-3.5-turbo",
        Messages: []Message{
            {
                Role:    "user",
                Content: txt,
            },
        },
    }
    reply := chatgpt(chat)
    fmt.Println(reply)
    return parseReply(reply)
}

/*
    {
        "id": "chatcmpl-72DpngkWShDySo58uVy9cvIxujivN",
        "object": "chat.completion",
        "created": 1680764191,
        "model": "gpt-3.5-turbo-0301",
        "usage": {
            "prompt_tokens": 26,
            "completion_tokens": 7,
            "total_tokens": 33
        },
        "choices": [{
            "message": {
                "role": "assistant",
                "content": "\"The address you provided is incorrect.\""
            },
            "finish_reason": "stop",
            "index": 0
        }]
    }
*/
func parseReply(json string) *Message {
    msgObj := Message{}
    res, err := simplejson.NewJson([]byte(json))
    if err != nil {
        fmt.Printf("%v\n", err)
        return nil
    }
    choices, err := res.Get("choices").Array()
    if err != nil {
        fmt.Printf("%v\n", err)
        return nil
    }
    for _, choice := range choices {
        choiceMap := choice.(map[string]interface{})
        message := choiceMap["message"].(map[string]interface{})
        msgObj.Role = message["role"].(string)
        msgObj.Content = message["content"].(string)
        break
    }
    return &msgObj
}

func main() {
    var content string
    flag.StringVar(&content, "c", "感觉gpt在处理一些复杂句子的时候比google翻译更好一些", "源语言内容")
    flag.Parse()
    dst := translate(content)
    fmt.Printf("[GPT]: \n%s\n", dst.Content)
}

官方 API 文档

https://platform.openai.com/docs/api-reference/chat/create
  • 第三方封装好的包:
github.com/sashabaranov/go-gpt3
# 教程
https://zhuanlan.zhihu.com/p/611290902