> ## Content Index
> Fetch the complete content index at: https://www.hubwiz.com/blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# Genkit Go全栈AI应用开发框架
- URL: https://www.hubwiz.com/blog/genkit-go-full-stack-ai-apps-golang-framework/
- Published: 2025-10-16T02:01:34.000Z
- Updated: 2025-10-16T02:01:34.000Z
- Description: Genkit Go是一个开源框架，旨在构建全栈 AI 应用，可以轻松连接 Gemini、OpenAI、Ollama 等模型，并管理结构化输出、RAG、工具调用，甚至代理工作流。
- Author: admin
- Tags: #Import 2026-10-14 14:41

如果您曾经尝试用 Go 构建 AI 应用，您可能知道这有多么令人沮丧。不同的 API、到处都是混乱的 JSON、随机的 SDK 在项目中途崩溃——这真是太混乱了。而这正是 Genkit 正在解决的问题。

它是一个开源框架，旨在构建全栈 AI 应用。您将获得一个简洁的界面，轻松连接 Gemini、OpenAI、Ollama 等模型。它管理结构化输出、RAG、工具调用，甚至代理工作流——所有这些都在一个平台上完成。

现在，Genkit Go 1.0 正式稳定并可投入生产。所以，Go 开发者终于有了一个可以使用的基础 AI 框架。

## 1、那么……Genkit 到底是什么？

可以将 Genkit 视为应用程序和 AI 模型之间的一层。无论您调用的是 Gemini 还是 GPT，它都只提供一个简洁的 API 来生成文本、结构化数据，甚至是多模态内容。

您只需编写流程、添加插件、运行本地 CLI，即可开始使用。它非常简单。而且由于它采用“Go 风格”构建，因此感觉轻量级、类型安全且可预测。

![](https://www.hubwiz.com/blog/content/images/2025/10/image-79.png)

## 2、Genkit Go 现已稳定

随着 1.0 版本的发布，Go SDK 正式脱离了“实验”阶段。API 已锁定，测试已完成，您使用 Genkit 1.x 构建的所有内容即使在 1.1 或 1.2 版本发布后也将继续有效。

它本应以最好的方式保持简洁——稳定、安全，并为生产环境做好准备。

## 3、类型安全的 AI 流程

这是最初吸引我的功能——流程。

流程本质上是由 AI 驱动的函数，具有明确定义的输入和输出。您只需设置一次，像标准 Go 函数一样执行它们，Genkit 会管理其间的所有 AI 处理。

下面是一个创建食谱的简短示例：

```
package main

import (
    "context"
    "encoding/json"
    "fmt"
    "log"

    "github.com/firebase/genkit/go/ai"
    "github.com/firebase/genkit/go/genkit"
    "github.com/firebase/genkit/go/plugins/googlegenai"
)

// Define your data structures
type RecipeInput struct {
    Ingredient          string `json:"ingredient" jsonschema:"description=Main ingredient or cuisine type"`
    DietaryRestrictions string `json:"dietaryRestrictions,omitempty" jsonschema:"description=Any dietary restrictions"`
}

type Recipe struct {
    Title        string   `json:"title"`
    Description  string   `json:"description"`
    PrepTime     string   `json:"prepTime"`
    CookTime     string   `json:"cookTime"`
    Servings     int      `json:"servings"`
    Ingredients  []string `json:"ingredients"`
    Instructions []string `json:"instructions"`
    Tips         []string `json:"tips,omitempty"`
}

func main() {
    ctx := context.Background()

    // Initialize Genkit with plugins
    g := genkit.Init(ctx,
        genkit.WithPlugins(&googlegenai.GoogleAI{}),
        genkit.WithDefaultModel("googleai/gemini-2.5-flash"),
    )

    // Define a type-safe flow
    recipeFlow := genkit.DefineFlow(g, "recipeGeneratorFlow", 
        func(ctx context.Context, input *RecipeInput) (*Recipe, error) {
            dietaryRestrictions := input.DietaryRestrictions
            if dietaryRestrictions == "" {
                dietaryRestrictions = "none"
            }

            prompt := fmt.Sprintf(`Create a recipe with the following requirements:
                Main ingredient: %s
                Dietary restrictions: %s`, input.Ingredient, dietaryRestrictions)

            // Generate structured data with type safety
            recipe, _, err := genkit.GenerateData[Recipe](ctx, g,
                ai.WithPrompt(prompt),
            )
            if err != nil {
                return nil, fmt.Errorf("failed to generate recipe: %w", err)
            }

            return recipe, nil
        })

    // Run the flow
    recipe, err := recipeFlow.Run(ctx, &RecipeInput{
        Ingredient:          "avocado",
        DietaryRestrictions: "vegetarian",
    })
    if err != nil {
        log.Fatalf("could not generate recipe: %v", err)
    }

    // Print the structured recipe
    recipeJSON, _ := json.MarshalIndent(recipe, "", "  ")
    fmt.Println("Sample recipe generated:")
    fmt.Println(string(recipeJSON))

    <-ctx.Done() // Used for local testing only
}
```

无需再处理 JSON 或随机解析错误——所有内容都经过强类型验证，并在后台进行验证。感觉就像编写普通的 Go 代码一样，但更智能。

## 4、一个接口，所有模型

每次更改模型提供程序时，您无需修改​​代码。只需更新模型名称即可：

```
// Use Google AI models
resp, err := genkit.Generate(ctx, g,
    ai.WithModelName("googleai/gemini-2.5-flash"),
    ai.WithPrompt("What is the weather like today?"),
)

// Use OpenAI models
resp, err := genkit.Generate(ctx, g,
    ai.WithModelName("openai/gpt-4o"),
    ai.WithPrompt("How are you today?"),
)

// Switch to Ollama for local models
resp, err := genkit.Generate(ctx, g,
    ai.WithModelName("ollama/llama3"),
    ai.WithPrompt("What is the meaning of life?"),
)
```

相同的代码，不同的引擎。就这样。

## 5、工具调用——真正能做的事情的 AI

这个很有趣。Genkit 允许你的 AI 调用真正的 Go 函数——它称之为“工具”。所以你的模型不仅仅是聊天；它实际上可以执行代码。

示例：一个简单的天气工具。

```
// Define a tool
type WeatherInput struct {
    Location string `json:"location" jsonschema_description:"Location to get weather for"`
}

getWeatherTool := genkit.DefineTool(g, "getWeather", 
    "Gets the current weather in a given location",
    func(ctx *ai.ToolContext, input WeatherInput) (string, error) {
        // Your weather API logic here
        return fmt.Sprintf("The current weather in %s is 72°F and sunny.", input.Location), nil
    })

// Use the tool in generation
resp, err := genkit.Generate(ctx, g,
    ai.WithPrompt("What's the weather in San Francisco?"),
    ai.WithTools(getWeatherTool),
)
```

现在您的 AI 可以在需要时自动调用 getWeather()。这类似于安全地授予它访问您的 Go 函数的权限。

## 6、几秒钟内从流到 API

部署？很简单。

```
// Create HTTP handlers for your flows
mux := http.NewServeMux()
mux.HandleFunc("POST /recipeGeneratorFlow", genkit.Handler(recipeFlow))

// Start the server
log.Fatal(server.Start(ctx, "127.0.0.1:3400", mux))
```

您的流现在是一个实时端点。完成。

## 7、CLI + 开发者 UI = 快速调试

这部分使本地开发变得轻而易举。安装 CLI：

```
curl -sL cli.genkit.dev | bash
```

然后运行：

```
genkit start -- go run .
```

它会启动您的应用并打开开发者界面，您可以在其中执行以下操作：

- 使用测试输入运行流程
- 逐步查看跟踪记录
- 检查延迟和令牌使用情况
- 即时调整提示

感觉像 Postman，但专为 AI 打造。

## 8、AI 助手集成

您甚至可以将您常用的 AI 编码工具（Gemini CLI、Claude Code、Cursor）直接链接到您的 Genkit 项目：

```
genkit init:ai-tools
```

它会添加一个 MCP 服务器，让助手列出流程、运行流程、获取文档并进行调试。如果您喜欢 AI 辅助编码，那么这个功能非常实用。

## 9、入门指南

```
mkdir my-genkit-app && cd my-genkit-app
go mod init example/my-genkit-app

go get github.com/firebase/genkit/go
curl -sL cli.genkit.dev | bash
genkit init:ai-tools
genkit start -- go run .
```

这就是你启动第一个 AI 应用所需的一切。

## 10、结束语

Genkit Go 1.0 终于为 Go 开发者提供了一种构建 AI 应用的稳定方式——它不再只是边缘实验，而是功能齐全、可直接投入生产的软件。它类型安全、简洁且易于调试。它与 Go 的简洁性无缝集成——完美契合。如果你一直在等待一种 Go 原生的方式来使用像 Gemini 或 GPT 这样的 AI 模型，那么现在就是了。

查看 genkit.dev 上的文档，开始尝试吧。

---

原文链接：[Genkit Go 1.0: Build Full-Stack AI Apps in Go, Now Production Ready](https://medium.com/coding-nexus/genkit-go-1-0-build-full-stack-ai-apps-in-go-now-production-ready-c2185c00b953?ref=hubwiz.com)

汇智网翻译整理，转载请标明出处