🦾😉轻松解锁本地AI开发:Golang和Ollama与ServBay的集成🚀✨

355 阅读5分钟

各位 ServBay 用户!👋 您已经了解 ServBay 如何简化复杂的本地开发环境管理。但您猜怎么着?我们又迈出了一大步!准备好驾驭 AI 的强大功能和 Golang 开发的高效性吧,所有这些都无缝集成到您熟悉的 ServBay 平台中。🎉 image.png

核心价值:ServBay + Ollama + Golang = 无与伦比的开发便捷性 💯

还在为处理 Ollama 配置、管理大型语言模型 (LLM) 以及设置单独的 Golang 开发栈而烦恼吗?ServBay 帮您扫清这些障碍!我们已将 OllamaGolang 无缝集成到 ServBay 平台,让您专注于创新,无需进行繁琐的设置。🛠️

ServBay 的新功能和亮点:

  1. 内置 Ollama 支持 🤖🧠:是的,您没看错!ServBay 现在全面支持 Ollama。通过 ServBay 直观的界面,您只需点击一下即可轻松安装 Ollama 服务!此外,您还可以便捷地下载和管理 DeepseekQwenLlama 3 等热门 LLM。在本地运行和调试 AI 应用程序从未如此简单。无论您是开发本地 AI 功能还是使用 Visual Studio Code 等 IDE 将 LLM 功能集成到您的工作流程中,ServBay 都能为您提供帮助。 image.png
  2. 功能齐全的 Golang 环境 🐹 Gopher 威力十足!:自 ServBay 1.11.0 起,该平台提供完整的 Go 语言开发环境支持。ServBay 集成了完整的 Go 工具链,并支持多个 Go 版本(例如,从历史版本到最新版本,例如 go1.24)。需要维护旧项目或尝试最新的 Go 功能?在 ServBay 中轻松切换 Go 版本。灵活性触手可及!🔄 image.png

告别繁琐的设置,开启高效开发:使用 Golang + Ollama,ServBay 之道

告别手动安装 Go 语言、令人头疼的环境变量以及单独下载和管理 Ollama 的时代。ServBay 让整个流程变得无比精简:

环境设置(ServBay 之道✅):

  1. 启动 ServBay:确保您的 ServBay 应用程序正在运行。
  2. 安装 Ollama:前往 ServBay 的服务管理(或类似部分),找到 Ollama,然后点击“安装”。非常简单!
  3. 下载模型:安装 Ollama 后,点击 ServBay 左侧的“AI”,搜索/选择您需要的模型,然后点击绿色按钮进行下载。 image.png
  4. 启用 Go 环境:在 ServBay 中,选择并启用您需要的 Go 版本(例如,go1.21.6 或更新版本)。完整的工具链已为您准备就绪。
  5. 创建您的项目:打开您的终端(确保它使用的是 ServBay 管理的 Go 环境),创建您的项目目录,并初始化 Go 模块:
      mkdir ollama-go-demo && cd ollama-go-demo
go mod init ollama-go-demo

6.安装 Ollama Go 客户端:在您的项目目录中,使用 go 命令(由 ServBay 提供支持)安装官方 Ollama API 客户端:

      go get github.com/ollama/ollama/api

注意:一切顺利,因为 ServBay 已经完美配置了您的 Go 环境。

实际开发:使用 Go 与您的本地 LLM 对话(由 ServBay 提供支持!)

现在,您拥有一个由 ServBay 提供的强大集成开发环境。让我们看看使用 Go 与本地 LLM 交互是多么简单。

(示例 1:基本聊天 💬)

在您的 ollama-go-demo 目录中创建 chat/main.go 文件,并包含以下内容(使用类似 llama3:8b 的模型 - 确保您已将其拉取!):

      package main

import ("context""fmt""log""github.com/ollama/ollama/api"
)

func main() {// ServBay manages the Ollama service; ClientFromEnvironment finds it automatically! ✨
        client, err := api.ClientFromEnvironment()if err != nil {
                log.Fatal("❌ Failed to connect to the Ollama service managed by ServBay: ", err)
        }
        messages := []api.Message{
                {
                        Role:    "user",
                        Content: "Why is the sky blue? Keep it concise.",
                },
        }
        ctx := context.Background()
        req := &api.ChatRequest{
                Model:    "llama3:8b", // Make sure this model is downloaded via `ollama pull llama3:8b`
                Messages: messages,
        }
        fmt.Println("Asking the local LLM: Why is the sky blue?")
        fmt.Println("Model says:")
        respFunc := func(resp api.ChatResponse) error {
                fmt.Print(resp.Message.Content)return nil
        }
        err = client.Chat(ctx, req, respFunc)if err != nil {
                log.Fatal("❌ Error during Ollama interaction: ", err)
        }
        fmt.Println() // Newline for neatness
}

从项目根目录运行它:

      go run chat/main.go

观察本地 llama3:8b 模型的响应!

(示例 2:流式输出 💨)

创建 generate-streaming/main.go

      package main

import ("context""fmt""log""github.com/ollama/ollama/api"
)

func main() {
        client, err := api.ClientFromEnvironment()if err != nil {
                log.Fatal("❌ Failed to connect to the Ollama service managed by ServBay: ", err)
        }
        req := &api.GenerateRequest{
                Model:  "llama3:8b", // Ensure model is ready
                Prompt: "Briefly explain Rayleigh scattering.",
                Stream: new(bool),    // Explicitly request streaming
        }
        *req.Stream = true // Make sure streaming is enabled
        ctx := context.Background()
        fmt.Println("Asking the local LLM (streaming): Briefly explain Rayleigh scattering.")
        fmt.Println("Model streams:")
        respFunc := func(resp api.GenerateResponse) error {
                fmt.Print(resp.Response) // Print response chunks as they arrivereturn nil
        }
        err = client.Generate(ctx, req, respFunc)if err != nil {
                log.Fatal("❌ Error during Ollama interaction: ", err)
        }
        fmt.Println() // Newline at the end
}

运行它:

      go run generate-streaming/main.go

看到答案逐个词法单元地出现,就像打字机效果一样!

(示例 3:结构化输出 (JSON) {})

创建structured_output/main.go

      package main

import ("context""encoding/json""fmt""log""strings""github.com/ollama/ollama/api"
)

// Define the structure we expecttype TechInfo struct {
        Language   string   `json:"language"`
        Creator    string   `json:"creator"`
        UseCases   []string `json:"use_cases"`
}

func main() {
        client, err := api.ClientFromEnvironment()if err != nil {
                log.Fatal("❌ Failed to connect to the Ollama service managed by ServBay: ", err)
        }
        messages := []api.Message{
                {
                        Role:    "system", // Give the model context on the desired format
                        Content: "You are a helpful assistant that provides information in JSON format.",
                },
                {
                        Role:    "user",
                        Content: "Provide info about the Go programming language: its creator and primary use cases. Use JSON format with keys 'language', 'creator', and 'use_cases' (an array of strings).",
                },
        }
        ctx := context.Background()
        req := &api.ChatRequest{
                Model:    "llama3:8b",  // Ensure model is ready
                Messages: messages,
                Format:   "json",       // Request JSON output format! 🤓
                Stream:   new(bool),    // Ensure non-streaming for a complete JSON object
                Options: map[string]interface{}{"temperature": 0.2, // Lower temperature for more deterministic JSON output
                },
        }
        *req.Stream = false // Explicitly disable streaming
        fmt.Println("Requesting structured data (JSON)...")
var fullResponse strings.Builder
        respFunc := func(resp api.ChatResponse) error {
                fullResponse.WriteString(resp.Message.Content) // Collect the full responsereturn nil
        }
        err = client.Chat(ctx, req, respFunc)if err != nil {
                log.Fatal("❌ Error during Ollama interaction: ", err)
        }
// Attempt to parse the JSON
        rawJSON := strings.TrimSpace(fullResponse.String())
        fmt.Println("Received raw JSON string:", rawJSON)
var info TechInfo
        err = json.Unmarshal([]byte(rawJSON), &info)if err != nil {// Sometimes models add markdown backticks around JSON, try removing themif strings.HasPrefix(rawJSON, "```json") && strings.HasSuffix(rawJSON, "```") {
                        rawJSON = strings.TrimPrefix(rawJSON, "```json")
                        rawJSON = strings.TrimSuffix(rawJSON, "```")
                        rawJSON = strings.TrimSpace(rawJSON)
                        fmt.Println("Attempting parse after removing markdown backticks:", rawJSON)
                        err = json.Unmarshal([]byte(rawJSON), &info)
                }
        }
if err != nil {
                log.Fatalf("❌ Failed to parse JSON: %v\nCheck if the model returned valid JSON matching the requested structure.", err)
        }
        fmt.Printf("Parsed Result -> Language: %s, Creator: %s, Use Cases: %v\n", info.Language, info.Creator, info.UseCases)
}

运行它:

      go run structured_output/main.go

该模型将尝试返回 JSON,您的 Go 程序会对其进行解析并清晰地打印。

无缝 IDE 集成 🔌💡

由于 ServBay 能够专业地管理您的 Go 环境和 Ollama 服务,因此与您常用的 IDE(例如 VS Code)集成变得轻而易举。只需将您的 IDE 指向 ServBay 管理的 Go SDK 路径即可。您可以直接在 IDE 中编写、调试和运行您的 Go 应用程序,而 ServBay 会在后台可靠地处理 Ollama 服务。您的 Go 代码只需进行 API 调用即可!

总结

ServBay 对 Ollama 的集成及其强大的 Golang 支持,极大地简化了在本地构建 AI 应用的工作流程。作为 ServBay 用户,您现在可以:

  • ✅ 一键轻松安装和管理 Ollama 及各种 LLM。
  • ✅ 享受开箱即用、多版本的 Golang 开发环境。
  • ✅ 在您的 Go 项目中快速利用本地 LLM 功能。
  • ✅ 轻松将 AI 功能集成到您现有的开发工作流程和 IDE 中。

拥抱 ServBay 的强大功能!让 Golang 与 Ollama 的协同效应为您的下一个创新项目注入活力。祝您编程愉快!🥳👍