惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Jina AI
Jina AI
宝玉的分享
宝玉的分享
Last Week in AI
Last Week in AI
Help Net Security
Help Net Security
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
人人都是产品经理
人人都是产品经理
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
GbyAI
GbyAI
博客园_首页
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
MongoDB | Blog
MongoDB | Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
L
LINUX DO - 最新话题
PCI Perspectives
PCI Perspectives
博客园 - 三生石上(FineUI控件)
V2EX - 技术
V2EX - 技术
Spread Privacy
Spread Privacy
T
Tor Project blog
量子位
阮一峰的网络日志
阮一峰的网络日志
S
SegmentFault 最新的问题
小众软件
小众软件
博客园 - 叶小钗
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Blog — PlanetScale
Blog — PlanetScale
H
Help Net Security
Y
Y Combinator Blog
N
News | PayPal Newsroom
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
T
Tenable Blog
Scott Helme
Scott Helme
G
GRAHAM CLULEY
大猫的无限游戏
大猫的无限游戏
aimingoo的专栏
aimingoo的专栏
IT之家
IT之家
Schneier on Security
Schneier on Security
F
Fortinet All Blogs
Martin Fowler
Martin Fowler
T
Threat Research - Cisco Blogs
博客园 - 司徒正美
Application and Cybersecurity Blog
Application and Cybersecurity Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Attack and Defense Labs
Attack and Defense Labs
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
The Last Watchdog
The Last Watchdog
L
LangChain Blog
C
Check Point Blog
Google Online Security Blog
Google Online Security Blog
V
Visual Studio Blog
Latest news
Latest news

Google Developers Blog

Expanding Choice in Gemini Enterprise Agent Platform: Introducing Grounding with Parallel Web Search- Google Developers Blog Building scalable AI agents with modular prompt transpilation- Google Developers Blog Evolving Spec-Driven Development: Conductor Now Supports Antigravity- Google Developers Blog Systems Engineering Playbook: Optimizing Qwen 3.5-397B MoE on Ironwood (TPU7x)- Google Developers Blog Unlocking the Next Era of On-Device AI with Google Tensor and Pixel- Google Developers Blog LiteRT.js, Google's high performance Web AI Inference- Google Developers Blog Bridging the Domain Gap: AI Race Coach built with Antigravity and Gemini- Google Developers Blog We terminated a TPU mid-training and it recovered in seconds: Introduction to elastic training with MaxText- Google Developers Blog ML Development in VS Code with Google Cloud Power: Workbench Extension Now Available- Google Developers Blog Why we built ADK 2.0- Google Developers Blog Build agentic full-stack apps with Genkit- Google Developers Blog Driving the Agent Quality Flywheel from Your Coding Agent- Google Developers Blog Build reliable multi-agent applications with ADK Go 2.0. Discover our new graph-based workflow engine, built-in human-in-the-loop, and dynamic orchestration- Google Developers Blog Measuring What Matters with Jules- Google Developers Blog Build Cross-Language Multi-Agent Team with Google’s Agent Development Kit and A2A- Google Developers Blog How A2A is Building a World of Collaborative Agents- Google Developers Blog A2UI + MCP Apps: Combining the best of declarative and custom agentic UIs- Google Developers Blog Announcing the Agentic Resource Discovery specification- Google Developers Blog Enhance Security and Trust: New Session Metadata in Sign in with Google- Google Developers Blog Unlocking the Power of the TPU Stack: Introducing our new Developer Hub- Google Developers Blog DiffusionGemma: The Developer Guide Introducing the Google Colab CLI Gemma 4 12B: The Developer Guide Bringing Gemma 4 12B to your Laptop: Unlocking Local, Agentic Workflows with Google AI Edge Supercharge your integration workflow with the Google Pay & Wallet Developer MCP server How the community trained Gemma to "Think" with Tunix and TPUs The latest updates to Google Pay Enhancing Android Checkout with Dynamic Callbacks in Google Pay Empowering Service Providers and Hardware Partners with Gemini for Home Announcing ADK for Kotlin and ADK for Android 0.1.0: Building AI Agents on Android and Beyond Blazing fast on-device GenAI with LiteRT-LM One Year of Innovation: Celebrating 100k Members in the Google Cloud x NVIDIA Developer Community All the news from the Google I/O 2026 Developer keynote A Smarter Google AI Edge Gallery: MCP integration, notifications, and session continuity Google Tensor SDK Beta with LiteRT An important update: Transitioning Gemini CLI to Antigravity CLI Accelerating on-device AI: A look at Arm and Google AI Edge optimization Build Long-running AI agents that pause, resume, and never lose context with ADK Supercharging LLM inference on Google TPUs: Achieving 3X speedups with diffusion-style speculative decoding Building with Gemini Embedding 2: Agentic multimodal RAG and beyond Speeding Up AI: Bringing Google Colossus to PyTorch via GCSFS and Rapid Bucket Building real-world on-device AI with LiteRT and NPU Agents CLI in Agent Platform: create to production in one CLI
Announcing Genkit Middleware: Intercept, extend, and harden your agentic apps
Chris Gill · 2026-05-14 · via Google Developers Blog

Genkit is an open-source framework for building full-stack, AI-powered and agentic applications for any platform with support for TypeScript, Go, Dart, and Python. Building a production-ready agentic applications and AI features requires more than powerful models and careful prompting. You might need retries and fallbacks for maximum reliability, human approval before destructive tool calls, and observability across every layer.

Genkit solves this with middleware: composable hooks that intercept generation calls, including the tool execution loop, and inject custom behaviors. The middleware system is available today in TypeScript, Go, and Dart, with Python support coming soon.

How Genkit middleware works

Every generate() call in Genkit runs a tool loop: the model produces output, any requested tools execute, the results feed back into a new model call, and the cycle repeats until the model is done. Middleware hooks attach at three layers of this loop:

Hook When it runs Typical use
Generate Once per tool-loop iteration Context injection, message rewriting, conversation-level logic
Model Once per model API call Retry, fallback, caching, latency logging
Tool Once per tool execution Human-in-the-loop, sandboxing, per-tool logging

Pre-built middleware

Genkit offers several pre-built middleware solutions for common use-cases. Here's what's available today:

1. Retry

Automatically retries failed model API calls on transient errors (RESOURCE_EXHAUSTED, UNAVAILABLE, etc.) using exponential backoff with jitter. Only the model call is retried; the surrounding tool loop is not replayed.

resp, err := genkit.Generate(ctx, g,
    ai.WithModelName("googleai/gemini-flash-latest"),
    ai.WithPrompt("Summarize the quarterly earnings report."),
    ai.WithUse(&middleware.Retry{
        MaxRetries:     3,
        InitialDelayMs: 1000,
        BackoffFactor:  2,
    }),
)

Go

Copied

2. Fallback

Switches to an alternative model when the primary model fails on a specified set of error codes. Useful for falling back to a completely different provider when your primary model exceeds its quota.

resp, err := genkit.Generate(ctx, g,
    ai.WithModelName("googleai/gemini-flash-latest"),
    ai.WithPrompt("Analyze this complex document..."),
    ai.WithUse(&middleware.Fallback{
        Models: []ai.ModelRef{
            anthropic.ModelRef("claude-sonnet-4-6", nil), // fall back to Claude
        },
        Statuses: []core.StatusName{core.RESOURCE_EXHAUSTED},
    }),
)

Go

Copied

3. Tool approval

Restricts tool execution to an allow-list. Any tool not on the list triggers an interrupt, enabling human-in-the-loop confirmation before the action proceeds.

resp, _ := genkit.Generate(ctx, g,
    ai.WithPrompt("Delete the temp files"),
    ai.WithTools(deleteFilesTool),
    ai.WithUse(&middleware.ToolApproval{
        AllowedTools: []string{}, // empty = every tool call interrupts
    }),
)

if len(resp.Interrupts()) > 0 {
    interrupt := resp.Interrupts()[0]

    // Prompt the user for approval, then resume with the approval flag.
    approved, _ := deleteFilesTool.RestartWith(interrupt,
        ai.WithResumedMetadata[DeleteInput](map[string]any{"toolApproved": true}),
    )

    resp, err := genkit.Generate(ctx, g,
        ai.WithMessages(resp.History()...),
        ai.WithTools(deleteFilesTool),
        ai.WithToolRestarts(approved),
        ai.WithUse(&middleware.ToolApproval{}),
    )
    fmt.Println(resp.Text())
}

Go

Copied

4. Skills

Scans a directory for SKILL.md files and injects their content into the system prompt. Also exposes a use_skill tool so the model can load specific skills on demand.

resp, err := genkit.Generate(ctx, g,
    ai.WithPrompt("How do I deploy this service?"),
    ai.WithUse(&middleware.Skills{SkillPaths: []string{"./skills"}}),
)

Go

Copied

5. Filesystem

Gives the model scoped access to the local filesystem through injected tools (list_files, read_file, plus write_file and edit_file when writes are enabled). Path safety is enforced so the model can never escape the root directory.

resp, err := genkit.Generate(ctx, g,
    ai.WithPrompt("Create a hello world program in the workspace"),
    ai.WithUse(&middleware.Filesystem{
        RootDir:          "./workspace",
        AllowWriteAccess: true,
    }),
)

Go

Copied

Building custom middleware

The pre-built middleware covers common scenarios, but the real power of the system is in writing your own. Imagine you're building an agentic customer-support app and need to ensure the model never mentions competitor products or internal pricing data. Rather than encoding these rules in every prompt, you can enforce them deterministically with middleware.

Custom middleware follows a simple contract across all languages: provide a name and a factory function that returns the hooks you want. The factory is called once per generate() invocation, and you implement only the hooks you need.

Here's a complete, custom content filter in ~20 lines of code:

// ContentFilter rejects model responses containing any forbidden term.
type ContentFilter struct {
    ForbiddenTerms []string `json:"forbiddenTerms"`
}

func (ContentFilter) Name() string { return "app/contentFilter" }

func (f ContentFilter) New(ctx context.Context) (*ai.Hooks, error) {
    return &ai.Hooks{
        WrapModel: func(ctx context.Context, p *ai.ModelParams, next ai.ModelNext) (*ai.ModelResponse, error) {
            resp, err := next(ctx, p)
            if err != nil {
                return nil, err
            }
            text := strings.ToLower(resp.Text())
            for _, term := range f.ForbiddenTerms {
                if strings.Contains(text, strings.ToLower(term)) {
                    return nil, fmt.Errorf("content filter: response contains %q", term)
                }
            }
            return resp, nil
        },
    }, nil
}

Go

Copied

You can even compose and stack different middleware solutions. Middleware stacks left-to-right, with the first listed being the outermost wrapper and so on:

resp, err := genkit.Generate(ctx, g,
    ai.WithModelName("googleai/gemini-flash-latest"),
    ai.WithPrompt("What CRM should our customer use?"),
    ai.WithUse(
        &middleware.Retry{MaxRetries: 3},           // outer: retries the inner stack
        &ContentFilter{                              // inner: validates model output
            ForbiddenTerms: []string{"CompetitorCRM", "RivalCo", "internal price"},
        },
    ),
)

Go

Copied

Here Retry wraps ContentFilter, which wraps the model call. Order matters, and Genkit makes it explicit.

If you think you’ve built a middleware that will be valuable to other developers, you can publish it as a package for others to benefit from!

The Developer UI experience

You can use the Genkit Developer UI to inspect, test, and debug your application, including middleware execution. When you register middleware, it becomes visible in the Dev UI: you can inspect its configuration, trace execution through each hook layer, and test different combinations.

Get started

We’re excited for the capabilities that Genkit middleware unlocks for your apps, and we’re looking forward to seeing what custom middleware you’ll build to solve for your use-cases. Check out the middleware documentation to dive deeper, or get started with Genkit if you're new to the framework.

Have an idea for a new pre-built middleware? File an issue. We'd love to hear what would improve your development experience!

Happy coding! 🚀