Skip to content

Google Antigravity

The Google Antigravity provider connects Loom to Google’s internal Cloud Code / Antigravity LLM backend, supporting streaming completions, dynamic model discovery, thinking effort configuration, and quota inspection.

1. Setup & Authentication

The provider integrates directly with Loom’s standard auth package and accepts any standard oauth2.TokenSource:

Automatically loads tokens from developer-managed storage, handles background token refreshes, saves updated tokens, and falls back to an interactive browser PKCE loopback login if needed:

import (
"context"
"fmt"
"log"
"github.com/masterkeysrd/loom/auth"
loomantigravity "github.com/masterkeysrd/loom/providers/antigravity"
"golang.org/x/oauth2"
)
ctx := context.Background()
oauthCfg := loomantigravity.NewOAuthConfig(loomantigravity.OAuthOptions{})
tokenPath := "/path/to/token.json"
tokenSource := auth.NewPersistentTokenSource(ctx, oauthCfg, auth.PersistentConfig{
Load: func() (*oauth2.Token, error) {
return auth.LoadTokenFile(tokenPath)
},
Save: func(tok *oauth2.Token) error {
return auth.SaveTokenFile(tokenPath, tok)
},
Login: func(ctx context.Context) (*oauth2.Token, error) {
return auth.LoginLoopback(ctx, oauthCfg, auth.LoopbackOptions{
OnAuthURL: func(url string) {
fmt.Printf("Please log in: %s\n", url)
_ = auth.OpenBrowser(url)
},
})
},
})

Or authenticate via the example CLI tool:

Terminal window
go run ./examples/antigravity --login

Option B: Environment Variables

Automatically resolve bearer tokens from ANTIGRAVITY_TOKEN or GOOGLE_ACCESS_TOKEN:

Terminal window
export ANTIGRAVITY_TOKEN="<your-oauth-bearer-token>"
# or
export GOOGLE_ACCESS_TOKEN="<your-oauth-bearer-token>"
tokenSource := auth.EnvTokenSource("ANTIGRAVITY_TOKEN", "GOOGLE_ACCESS_TOKEN")

Option C: Static Token

Pass an existing token programmatically:

tokenSource := auth.StaticTokenSource("<your-oauth-bearer-token>")

2. Basic Usage

package main
import (
"context"
"fmt"
"log"
"github.com/masterkeysrd/loom/auth"
"github.com/masterkeysrd/loom/llm"
loomantigravity "github.com/masterkeysrd/loom/providers/antigravity"
"github.com/masterkeysrd/loom/message"
)
func main() {
ctx := context.Background()
// 1. Initialize token source & provider
tokenSource := auth.EnvTokenSource("ANTIGRAVITY_TOKEN", "GOOGLE_ACCESS_TOKEN")
provider, err := loomantigravity.NewProvider(&loomantigravity.Config{
TokenSource: tokenSource,
})
if err != nil {
log.Fatal(err)
}
// 2. Instantiate model (e.g. Gemini 3.8 Flash)
model, err := llm.NewModel(provider, "gemini-3.8-flash", nil)
if err != nil {
log.Fatal(err)
}
// 3. Stream a completion
stream, err := model.Stream(ctx, message.MessageList{
message.NewUserText("Explain quantum computing in three sentences."),
})
if err != nil {
log.Fatal(err)
}
for chunk, err := range stream {
if err != nil {
log.Fatal(err)
}
fmt.Print(chunk.Content.Text())
}
fmt.Println()
}

3. Advanced Features

Thinking & Reasoning Effort

Antigravity models support configurable thinking budgets and levels (low, medium, high):

// 1. Via fluent Model configuration
model = model.WithThinkingEffort("high")
// 2. Or using dynamic model alias names
fastModel, err := llm.NewModel(provider, "gemini-3.8-flash-low", nil)
if err != nil {
log.Fatal(err)
}
deepModel, err := llm.NewModel(provider, "gemini-3.8-flash-high", nil)
if err != nil {
log.Fatal(err)
}

The provider’s heuristic resolver normalizes thinkingConfig.thinkingLevel to uppercase ("LOW", "MEDIUM", "HIGH") and routes requests to either the family’s -tiered gateway endpoint (such as gemini-3.8-flash-tiered) or its dedicated per-effort endpoint (such as gemini-4-carbon-high). When a canonical model family with only per-effort endpoints is invoked without an explicit thinking effort, it automatically falls back to -medium → -low → -high.

Dynamic Model Discovery, Companion Project & Client Configuration

Antigravity discovers available models dynamically at runtime directly from Google’s /v1internal:fetchAvailableModels endpoint:

  • Zero hardcoded catalogs: Newly published models (e.g. Gemini 4 Carbon/Argon, Claude updates) work immediately without code changes, and availableModels is lazily populated on cold Stream calls if not yet fetched.
  • Automatic Companion Project Discovery: Resolves cloudaicompanionProject once per OAuth token via POST /v1internal:loadCodeAssist and passes it in the JSON body "project" field without setting X-Goog-User-Project. To override the body project explicitly, set Config.CompanionProject (or ANTIGRAVITY_COMPANION_PROJECT). Set Config.ProjectID only when attributing quota/billing to an explicit user GCP project via X-Goog-User-Project.
  • Versioned Client User-Agent: Emits antigravity/cli/<version> (<os>/<arch>) by default so frontier tiers on daily-cloudcode-pa.googleapis.com are unlocked. Override via Config.UserAgent or ANTIGRAVITY_USER_AGENT (alongside ANTIGRAVITY_BASE_URL).
  • Compact View (RawProfiles: false, default): Groups -tiered and -low/-medium/-high endpoints by canonical family across ListModels(ctx), GetModel(ctx, id), ListProfiles(), and GetProfile(), surfacing ReasoningOptions and family limits.
  • Raw View (RawProfiles: true): Exposes all raw backend endpoints and variants.
  • llm.ModelLister Support: Call provider.ListModels(ctx) or provider.GetModel(ctx, "gemini-3.8-flash") for explicit, context-aware live discovery with error propagation.
  • Custom Aliases & Resolvers: Map custom shorthand names (e.g. "fast" -> "gemini-3.8-flash-low") or inject a custom ModelResolver function in loomantigravity.Config.
provider, _ := loomantigravity.NewProvider(&loomantigravity.Config{
TokenSource: tokenSource,
Aliases: map[string]string{
"fast": "gemini-3.8-flash-low",
"smart": "gemini-2.5-pro",
},
})

Sticky Session Affinity & Prompt Correlation (loomantigravity.Session)

Attach loomantigravity.Session via WithExtension (or per-call llm.WithCallExtension) to set request.session_id for sticky replica / implicit KV-cache affinity and user_prompt_id on the outer envelope:

model = model.WithExtension(loomantigravity.Session{
ID: "session-uuid",
UserPromptID: "turn-uuid",
})

4. Quota & Rate Limit Inspection (llm.QuotaProvider)

The Antigravity provider implements Loom’s llm.QuotaProvider interface, combining model mappings from /v1internal:fetchAvailableModels with multi-window pools (such as 5-hour and weekly buckets) from /v1internal:retrieveUserQuotaSummary. Quotas are decoupled from the 1-hour profile metadata cache to ensure fresh reporting without staleness:

// Assert llm.QuotaProvider
if qp, ok := provider.(llm.QuotaProvider); ok {
// Check quota buckets for a specific model (resolves aliases automatically)
if buckets, found, err := qp.GetQuota(ctx, "gemini-3.8-flash"); found && err == nil {
if bottleneck, ok := buckets.Bottleneck(); ok {
fmt.Printf("Remaining: %.1f%%\n", bottleneck.Percentage())
if bottleneck.ResetAt != nil {
fmt.Printf("Replenishes at: %s\n", bottleneck.ResetAt.Format(time.RFC3339))
}
}
}
// Retrieve deduplicated quota snapshot across shared buckets and model bindings
snap, _ := qp.GetQuotaSnapshot(ctx)
for model := range snap.Models {
if buckets, ok := snap.ForModel(model); ok {
if b, ok := buckets.Bottleneck(); ok {
fmt.Printf("• %-30s | Remaining: %5.1f%%\n", model, b.Percentage())
}
}
}
}

Cache Configuration

Quota caching can be tuned in loomantigravity.Config:

  • QuotaCacheTTL: 30 * time.Second (Default): Avoids redundant network roundtrips during rapid polling.
  • QuotaCacheTTL: -1: Bypasses the cache and always executes direct live network queries.
  • Direct uncached raw protocol queries can also be executed via provider.Client() (*sdk.Client, e.g. RetrieveUserQuotaSummary(ctx) and FetchAvailableModels(ctx)).

5. Token Counting & Metrics (llm.TokenCounter)

The Antigravity provider implements Loom’s llm.TokenCounter interface and provides comprehensive token metrics during streaming:

Pre-call Token Counting (CountTokens)

Computes exact token counts for message sequences using Google Cloud Code’s /v1internal:countTokens endpoint. If network or server issues occur, it gracefully falls back to llm.ApproximateTokenCounter:

// Assert llm.TokenCounter
if counter, ok := provider.(llm.TokenCounter); ok {
msgs := message.MessageList{
message.NewSystemText("You are an expert Go developer."),
message.NewUserText("Explain channels in Go."),
}
count, err := counter.CountTokens(ctx, msgs)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Total tokens: %d\n", count)
}

This enables seamless integration with Loom’s memory.Summarizer and conversational memory pruning.

Streaming Token Metrics

The provider extracts detailed token usage from UsageMetadata chunks:

  • chunk.Metrics.TotalTokens: Total tokens.
  • chunk.Metrics.Tokens.Input: Prompt / input token count.
  • chunk.Metrics.Tokens.Output: Candidate completion token count.
  • chunk.Metrics.Tokens.CacheRead: Tokens served from Google’s cached content (cachedContentTokenCount).
  • chunk.Metrics.Tokens.Reasoning: Reasoning / thinking tokens generated by the model (thoughtsTokenCount).

6. CLI Test Runner

The repository includes a ready-to-run interactive CLI test runner at examples/antigravity:

Terminal window
# 1. Authenticate via Google OAuth
go run ./examples/antigravity --login
# 2. Inspect available models and remaining quotas
go run ./examples/antigravity --list-models
# 3. View raw endpoints
go run ./examples/antigravity --list-models --raw
# 4. Check detailed quota and reset windows
go run ./examples/antigravity --quota
# 5. Count tokens for a prompt using the server endpoint
go run ./examples/antigravity --count-tokens "The quick brown fox jumps over the lazy dog."
# 6. Run a prompt with thinking effort and inspect token metrics
go run ./examples/antigravity --model gemini-3.8-flash --effort high --prompt "Analyze the complexity of QuickSort."