AIStudio2API icon indicating copy to clipboard operation
AIStudio2API copied to clipboard

feat(embeddings): route embeddings via account free-tier Gemini API key (generativelanguage.googleapis.com)

Open lawrancehoy-cyber opened this issue 3 days ago • 1 comments

想要什么,用来做什么 / What you want and what for

Problem & Verified Evidence (v0.3.15 / ddb1af5)

AIStudio2API already exposes /v1/embeddings, /v1beta/models/{model}:embedContent, and /v1beta/models/{model}:batchEmbedContents (internal/api/embeddings.go, internal/app/embeddings.go, internal/aistudio/build_embed.go), plus code snippets on the Access page (web/src/access/capabilities.ts). However, all three endpoints are currently non-functional because they route exclusively through legacy ChannelBuild (ProxyUnaryCall), which Google has shut down for embeddings (related to #82).

Verified live on v0.3.15 (ddb1af5) with UPSTREAM_CHANNELS=playground,build:

Path / RPC Observed Result
Playground MakerSuiteService/ListModels 0 embedding models
MakerSuiteService/EmbedContent & BatchEmbedContents Does not exist (CORS preflight HTTP 302)
ProxyUnaryCall GET /v1beta/models 53 models; only gemini-embedding-001 (gemini-embedding-2 absent)
POST /v1/embeddings (gemini-embedding-001) HTTP 400 (code 3): PROXY_GENERATION_DISABLED: batchEmbedContents is not supported
POST /v1beta/models/gemini-embedding-001:embedContent HTTP 400 (code 3): PROXY_GENERATION_DISABLED: batchEmbedContents is not supported
ProxyUnaryCall /v1beta/models/gemini-embedding-001:embedContent HTTP 400 (code 3): Request contains an invalid argument.
POST /v1/embeddings (gemini-embedding-2) HTTP 404 model_not_found

Unlike chat generation (where Playground already provides free/Pro quota and using API keys makes no sense), Playground has no embedding RPC at all. Meanwhile, Google's Gemini Developer API (generativelanguage.googleapis.com/v1beta) provides $0 Free Tier embedding quota (~100 RPM / 1,000 RPD per project, no billing account required) for both gemini-embedding-001 and gemini-embedding-2 (including multimodal inlineData), and AIStudio2API already implements the exact MakerSuite RPC chain (ListImportedProjects -> ListCloudProjects -> ListCloudApiKeys / GenerateCloudApiKey) in internal/aistudio/assistant_applet.go.

Live Verification of Direct Free-Tier Path

Tested across 5 accounts (4 with tier=20 Free Tier projects including 3 pure zero-billing billing=[] accounts, plus 1 fresh account with 0 projects) using the existing MakerSuite RPC chain followed by direct HTTPS requests (x-goog-api-key) through each account's egress proxy:

Account ListCloudProjects Active Free-Tier Key (row[8]==nil) gemini-embedding-001:batchEmbedContents gemini-embedding-2:batchEmbedContents
account_a (tier=20, closed billing) 2 projects (tier=20) AIza... (rows 0–1 had row[8]=1 -> API_KEY_INVALID; row 2 had row[8]=nil) HTTP 200 (331 ms, 2×256d) HTTP 200 (425 ms, 2×256d, promptTokenCount=4)
account_b (tier=20, billing=[]) 1 project (tier=20) AIza... HTTP 200 (746 ms) HTTP 200 (324 ms, promptTokenCount=3)
account_c (tier=20, billing=[]) 1 project (tier=20) AQ.... HTTP 200 (1022 ms) HTTP 200 (484 ms, promptTokenCount=3)
account_d (tier=20, billing=[]) 1 project (tier=20) AQ.... HTTP 200 (1033 ms) HTTP 200 (512 ms, promptTokenCount=3)
account_e (0 projects) [] CreateCloudProject -> HTTP 403 (code 7): Project must be created from the Google Cloud console. Ineligible (skip) Ineligible (skip)

Additional wire facts verified live:

  • GET https://generativelanguage.googleapis.com/v1beta/models?pageSize=200 with a Free-Tier key returns 65 models, including all 3 embedding models:
    • models/gemini-embedding-001 (inputTokenLimit: 2048)
    • models/gemini-embedding-2-preview (inputTokenLimit: 8192, multimodal)
    • models/gemini-embedding-2 (inputTokenLimit: 8192, multimodal)
  • Multimodal inlineData (text + PNG) on gemini-embedding-2:embedContent returns HTTP 200 (443 ms) with usageMetadata.promptTokenCount: 261 (IMAGE: 258, TEXT: 3).
  • taskType is accepted (HTTP 200) on both gemini-embedding-001 and gemini-embedding-2.
  • Once the account's Free-Tier key is resolved and cached in memory, embedding requests require zero WAA proof and zero browser/SpiderMonkey round-trips per request.

Proposed Minimal Architecture

Replace the dead ProxyUnaryCall path in internal/aistudio/build_embed.go with direct calls to https://generativelanguage.googleapis.com/v1beta/models/{model}:batchEmbedContents using each eligible account's Free-Tier API key over that account's existing egress proxy (MakerSuiteHTTPTransport), with no new config flags:

  1. Free-Tier key resolution (reusing internal/aistudio/assistant_applet.go):
    • Strictly restrict to tier == 20 (assistantFreeProjectTier) projects; do not fall back to paid projects (tier == 50, keys[0]) to avoid accidental billing.
    • Skip keys where ListCloudApiKeys field 9 (row[8]) is non-null (verified: row[8] == 1 keys return HTTP 400 API_KEY_INVALID).
    • Do not filter by AIza prefix (newer Google AI Studio keys use AQ.).
    • Cache the resolved Free-Tier key per account in memory; if an account has no Free-Tier project (CreateCloudProject returns HTTP 403 on accounts without GCP Console onboarding), mark it ineligible for embeddings and skip it in pool selection.
  2. Model catalog & routing (internal/aistudio/channel.go, internal/app/embeddings.go):
    • Decouple embeddings from UPSTREAM_CHANNELS=build / ProxyUnaryCall. Discover embedding models (supportedGenerationMethods containing embedContent) via GET https://generativelanguage.googleapis.com/v1beta/models?pageSize=200 using a resolved Free-Tier key (reusing ParseBuildModels in internal/aistudio/build.go:1135), which also exposes gemini-embedding-2 and gemini-embedding-2-preview.
  3. Direct request/response & usage parsing (internal/aistudio/build_embed.go):
    • Reuse EncodeBuildEmbedRequest directly against https://generativelanguage.googleapis.com with x-goog-api-key and Content-Type: application/json, removing the EncodeBuildProxyRequest + DoProtectedBuild wrapper.
    • Parse direct JSON responses (embeddings[].values) and read token count from usageMetadata.promptTokenCount (returned by gemini-embedding-2*) in addition to optional tokenCount (gemini-embedding-001 omits both, which internal/api/embeddings.go already handles).
  4. REST JSON error decoding & multi-account failover (internal/aistudio/client.go, internal/aistudio/quota.go):
    • Decode standard Gemini REST error payloads ({"error":{"code":...,"message":"...","status":"...","details":[...]}}) into *RPCError (extracting ErrorInfo metadata/reason and RetryInfo.retryDelay), so existing QuotaCooldownForError (429 RPM/RPD per-project limits) and account rotation in PooledService.Embed work out of the box.
    • On 400 API_KEY_INVALID or 403 PERMISSION_DENIED (e.g. FREE_TIER_VERIFICATION_REQUIRED), invalidate the cached key / mark the account ineligible for embeddings and rotate to the next eligible account.

版本 / Version

v0.3.15 (ddb1af5)

lawrancehoy-cyber avatar Nov 29 '26 16:11 lawrancehoy-cyber

if it runs on the account's API key you can just call the official API with that key directly, there's no need to route it through this project.

Mag1cFall avatar Nov 29 '26 19:11 Mag1cFall