genai.go

Overview

The genai.go file in the testutil package provides utilities for configuring HTTP client transport tailored for Google’s Gemini AI services, specifically enabling record and replay (RR) capabilities during testing. It wraps the HTTP transport with a custom round-tripper that records outbound requests and responses, and replays them during tests to ensure deterministic behavior. The file also implements request scrubbing logic to canonicalize Gemini API requests by removing or normalizing headers and JSON payloads that could vary between calls, such as API keys or version identifiers. This facilitates consistent replay and comparison of HTTP interactions.

Functions and Methods

NewGeminiTransport(rrfile string) (http.RoundTripper, error)

rr, err := httprr.Open(rrfile, http.DefaultTransport)
if err != nil {
    return nil, fmt.Errorf("httprr.Open(%q) failed: %w", rrfile, err)
}
rr.ScrubReq(scrubGeminiRequest)
return rr, nil

scrubGeminiRequest(req *http.Request) error

if ctype := req.Header.Get("Content-Type"); ctype == "application/json" || strings.HasPrefix(ctype, "application/json;") {
    b := req.Body.(*httprr.Body)
    var buf bytes.Buffer
    if err := json.Compact(&buf, b.Data); err == nil {
        b.Data = buf.Bytes()
    }
}

Important Implementation Details


Interaction With Other System Components


Visual Diagram

flowchart TD
A["NewGeminiTransport(rrfile)"] -->|calls| B["httprr.Open(rrfile, DefaultTransport)"]
B -->|returns| C[httprr.RecordReplayTransport]
C -->|registers scrub function| D["scrubGeminiRequest(req)"]
D -->|removes headers| E[x-goog-api-key, x-goog-api-client, user-agent]
D -->|canonicalizes JSON body| F[json.Compact]

Summary of Key Elements

Function

Purpose

Key Points

NewGeminiTransport

Creates RR transport for Gemini API testing

Opens RR file, sets scrub function

scrubGeminiRequest

Normalizes request headers and JSON body

Deletes volatile headers, compacts JSON bodies


This file is a utility specifically crafted for Gemini AI HTTP client setup in test environments, ensuring reproducible and sanitized HTTP request/response cycles. It is a foundational piece in the test infrastructure surrounding Gemini AI integration, facilitating reliable and consistent test execution.

For further details on HTTP transport and adapter patterns, see Agent Invocation Context and REST API and Web Launchers. For integration with Gemini and other Google AI services, refer to Google Search Tool - Gemini-native tool.