golang 访问本地ollama实现翻译API

262 阅读1分钟

创建golang项目

  1. 新建 translator 目录
  2. 初始化项目(go 1.23.2)
go mod init translator
  1. 安装依赖
go get github.com/gin-gonic/gin
go get github.com/tmc/langchaingo/llms
  1. 新建main.go 入口文件

API 功能实现

main.go

package main

import (
	"context"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/tmc/langchaingo/llms"
	"github.com/tmc/langchaingo/llms/ollama"
	"github.com/tmc/langchaingo/prompts"
)

func main() {
	r := gin.Default()
	v1 := r.Group("/api/v1")
	v1.POST("/translate", translator)
	r.Run(":8080")
}

func translator(c *gin.Context) {
	var requestData struct {
		OutputLang string `json:"outputLang"`
		Text       string `json:"text"`
	}
	if err := c.BindJSON(&requestData); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Json."})
		return
	}

	//创建 prompt
	prompt := prompts.NewChatPromptTemplate([]prompts.MessageFormatter{
		prompts.NewSystemMessagePromptTemplate("你是一个只能翻译文本的翻译引擎,不需要进行解释。", nil),
		prompts.NewHumanMessagePromptTemplate("翻译这段文字到 {{.outputLang}}: {{.text}}", []string{"outputLang", "text"}),
	})

	// 填充 prompt
	vals := map[string]any{
		"outputLang": requestData.OutputLang,
		"text":       requestData.Text,
	}
	messages, err := prompt.FormatMessages(vals)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	//链接ollama
	llm, err := ollama.New(ollama.WithModel("qwen2.5"))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	content := []llms.MessageContent{
		llms.TextParts(messages[0].GetType(), messages[0].GetContent()),
		llms.TextParts(messages[1].GetType(), messages[1].GetContent()),
	}
	response, err := llm.GenerateContent(context.Background(), content)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	// 返回结果
	c.JSON(http.StatusOK, gin.H{"response": response.Choices[0].Content})
}

启动ollama

ollama serve

mac 端口占用

解决方法

查找并停止占用端口的进程:
lsof -i tcp:11434

如果找到了占用端口的进程,使用kill命令停止它:
kill -9 PID
其中PID是占用端口的进程ID。

调用测试

测试工具postman

// http://localhost:8080/api/v1/translate

//body
{
    "outputLang": "英语",
    "text": "今天天气不错"
}