# gemini cheatsheet
Every export of @deckyard/gemini. Guides are listed in the introduction .
jennifer import "@deckyard/gemini/" as gemini;
A c argument is a Client; a req is a request (json.Value) from newRequest; a reply is what chat returned. A request the API refused throws GeminiError (kind "gemini") with the HTTP status, Google's googleStatus and the ErrorInfo reason; the deck's own refusals are the same struct with status 0. text and textJson of a reply without an answer throw GeminiError kind "gemini.blocked", its blockReason the reason. A cap is kind "limit", a deadline "timeout", a network failure "net" (a net.NetError, passed on as it is), a connection closed mid-answer "closed", a cancelled task "cancelled".
# Constants
Constant Value Meaning VERSION"0.1.0"this deck's version DEFAULT_BASE_URL"https://generativelanguage.googleapis.com"Google AI Studio's server API_VERSION"v1beta"the version every path is below DEFAULT_TIMEOUT_MS300000the deadline of one request DEFAULT_RETRIES3retries of a 408, 409, 429 or 5xx, or a network failure before the request was sent DEFAULT_BACKOFF_MS1000the first retry's wait when the server names none DEFAULT_MAX_BYTES33554432the largest reply MAX_RETRY_WAIT_MS60000a server asking for a longer wait is not retried MAX_REQUEST_BYTES100000000the largest JSON request DEFAULT_MAX_TOOL_INPUT1048576the largest arguments of a call handed to a tool handler, as JSON MAX_PAGES100the most pages a listing reads; together they are under the reply cap BLOCKED_FINISH_REASONS["SAFETY", "RECITATION", "LANGUAGE", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII", "IMAGE_SAFETY", "IMAGE_PROHIBITED_CONTENT", "IMAGE_RECITATION"]finish reasons that mean no full answer THINKING_LEVELS["minimal", "low", "medium", "high", "xhigh"]what withThinkingLevel takes SAFETY_THRESHOLDS["BLOCK_NONE", "BLOCK_ONLY_HIGH", "BLOCK_MEDIUM_AND_ABOVE", "BLOCK_LOW_AND_ABOVE", "OFF"]what withSafety takes MAX_TOOL_TURNS100the most replies runTools asks for TOOL_MODES["AUTO", "ANY", "NONE", "VALIDATED"]what withToolMode takes MAX_EMBED_BATCH100texts per batchEmbedContents request MAX_FILE_BYTES2000000000the largest upload, Google's 2 GB MAX_FILE_PAGES1000the most pages files reads (100 files each) MAX_CACHE_TTL_SECONDS31536000the longest cache TTL
# The client
Function Returns Does client(apiKey)Clienta client for Google AI Studio with an API key, sent in x-goog-api-key withBaseUrl(c, baseUrl)Clientanother server serving the same API (a proxy, a fake) withTls(c, tls)Clientcertificate options (caCert, skipVerify) withPlainHttp(c)Clientallow plain http to another machine withTimeout(c, ms)Clientthe deadline of one attempt, 1000 to 3600000 ms withRetries(c, n)Clientretries of a 408, 409, 429 or 5xx, or a network failure before the request was sent (NetError.sent false), 0 to 10; nothing sent in full is sent again withBackoff(c, ms)Clientthe first retry's wait when the server names none, 0 to 60000 ms withMaxBytes(c, most)Clientthe largest reply, 65536 to 1073741824 bytes withMaxToolInput(c, most)Clientthe largest arguments of a call the tool loop hands to a handler, 1024 to 1073741824 bytes as JSON; larger is answered with a toolError withUploadTimeout(c, ms)Clientthe deadline of an upload's data step, 1000 to 86400000 ms (default 5 min plus 1 min per 100 MB) models(c)list of ModelInfoevery model the key may use, all pages model(c, name)ModelInfoone model call(c, method, path, body)json.Valueany other request below /v1beta; a query goes in path, encoded by the caller
# Requests
Function Returns Does newRequest(model)json.Value{"model": "models/<id>", "contents": []}withSystem(req, text)json.Valuethe system instruction textPart(text)json.Valuea text part inlinePart(mimeType, data)json.Valuemedia in the request, base64 filePart(mimeType, uri)json.Valuemedia by URI (an uploaded file's uri) addParts(req, role, parts)json.Valuea turn of parts, role user or model addText(req, role, text)json.Valuea text turn addUserText(req, text)json.Valuea user text turn addReply(req, reply)json.Valuethe reply's answer as the model's turn, signatures kept withConfig(req, name, value)json.Valuea generationConfig field withJsonSchema(req, schema)json.ValueJSON output matching a JSON Schema withThinkingLevel(req, level)json.Valuea thinking level; clears a budget withThinkingBudget(req, tokens)json.Valuea thinking budget, -1 to 32768; clears a level withThoughts(req, wanted)json.Valueask for thought summaries withSafety(req, category, threshold)json.Valuea safety threshold for a harm category withCachedContent(req, name)json.Valueread the prefix from a cache
# Generating and reading
Function Returns Does chat(c, req)json.ValuegenerateContent: the reply as Google sent itcountTokens(c, req)intthe tokens the request's input takes text(reply)stringthe answer's text; throws "gemini.blocked" without an answer thoughts(reply)stringthe thought summaries textJson(reply)json.Valuethe answer parsed as JSON finishReason(reply)stringwhy the first candidate stopped blockReason(reply)stringwhy there is no full answer, "" when there is one usage(reply)Usagethe token counts
# Function calling
Gemini has no strict mode for tools, so there is no withStrict (the openai and anthropic decks have one): its schemas are an OpenAPI subset that steers the model, and withToolMode(req, "VALIDATED", []) is the closest it offers. Check arguments before acting on them.
Function Returns Does tool(name, description, schema)json.Valuea function declaration to offer addTool(req, decl)json.Valueoffer one more, in the one functionDeclarations entry addTools(req, decls)json.Valueoffer several more toolError(message)json.Value{"error": message}, a failed call's result for the modelwithToolMode(req, mode, allowed)json.Valuethe function-calling mode toolCalls(reply)list of ToolCallthe functions the answer calls, in order addToolResults(req, calls, results)json.Valuethe results as one user turn, ids kept runTools(c, req, handler, maxTurns)ToolRunthe tool loop; handler(name, input) returns a json.Value; a throw ends it unchanged; out of turns it returns with stopped "maxTurns" runToolsWith(c, req, handler, context, maxTurns)ToolRunthe tool loop; handler(name, input, context)
# Embeddings
Function Returns Does embed(c, model, text, taskType, dimensions)list of floatone text's embedding; dimensions 128 to 3072, or 0 for the model's own embedMany(c, model, texts, taskType, dimensions)list of list of floatmany, in batches of MAX_EMBED_BATCH
# Files
Function Returns Does uploadFile(c, data, mimeType, displayName)FileInfoa resumable upload file(c, name)FileInfoone file files(c)list of FileInfoevery file, all pages deleteFile(c, name)nulldelete a file waitForFile(c, name, timeoutMs)FileInfopoll until ACTIVE
# Context caching
Function Returns Does createCache(c, req, ttlSeconds, displayName)CacheInfocache a request's prefix cache(c, name)CacheInfoone cache caches(c)list of CacheInfoevery cache, all pages updateCacheTtl(c, name, ttlSeconds)CacheInfoa new TTL from now (updateMask=ttl) deleteCache(c, name)nulldelete a cache
# Structs
# Client
Field Meaning apiKey as stringthe key; do not print a client baseUrl as stringthe server, without the API version tls as http.TlsOptionscertificate checks for https allowPlainHttp as boolplain http to another machine allowed timeoutMs as intthe deadline of one attempt retries as intretries of a 408, 409, 429 or 5xx, or a network failure before the request was sent backoffMs as intthe first retry's wait when the server names none maxBytes as intthe largest reply maxToolInput as intthe largest arguments handed to a tool handler, bytes as JSON uploadTimeoutMs as intthe deadline of an upload's data step; 0 for 5 min plus 1 min per 100 MB
# GeminiError
Field Meaning kind as string"gemini" or "gemini.blocked"message as stringwhat happened, never the key status as intthe HTTP status; 0 without an answer; 200 when blocked googleStatus as stringGoogle's error status name (RESOURCE_EXHAUSTED, ...); "" for a block blockReason as stringfor kind "gemini.blocked", the block or finish reason (SAFETY, RECITATION, ...) reason as stringthe ErrorInfo reason (API_KEY_INVALID, ...), or PROMPT_BLOCKED / RESPONSE_BLOCKED retryAfterMs as intthe wait the server asked for (retry-after-ms, retry-after, RetryInfo), at most 1e12, 0 when none limits as map of string to stringthe answer's rate-limit headers, names lower-cased (x-ratelimit-*, retry-after, retry-after-ms), at most 32
# ModelInfo
Field Meaning name as stringmodels/<id>displayName as stringthe name for people description as stringwhat it is for version as stringits version inputTokenLimit as intthe most input tokens outputTokenLimit as intthe most output tokens methods as list of stringthe supported methods, such as generateContent thinking as boolwhether it thinks
# Usage
Field Meaning inputTokens as intthe prompt, cache included (promptTokenCount) outputTokens as intthe answer (candidatesTokenCount) totalTokens as intall of them (summed when the API sends none) cachedTokens as intthe part read from a cache reasoningTokens as intthe thinking (thoughtsTokenCount) toolUseTokens as intbuilt-in tools' results
Field Meaning id as stringthe call's id, "" when the model sent none name as stringthe function input as json.Valuethe arguments (args), an object
Field Meaning reply as json.Valuethe last reply request as json.Valuethe whole conversation, ready for the next turn (after "maxTurns", with the last calls' results) turns as intthe replies asked for calls as intthe function calls the handler ran usage as Usagethe token counts of every reply, summed stopped as string"" when the model finished, "maxTurns" when the loop ran out of turns
# FileInfo
Field Meaning name as stringfiles/<id>displayName as stringthe name given at upload mimeType as stringits MIME type sizeBytes as intits size uri as stringfor filePart state as stringPROCESSING, ACTIVE or FAILEDcreateTime as stringwhen it was uploaded expirationTime as stringwhen Google deletes it sha256Hash as stringits hash, base64 errorMessage as stringwhy processing failed
# CacheInfo
Field Meaning name as stringcachedContents/<id>displayName as stringthe name given at creation model as stringmodels/<id>createTime as stringwhen it was created updateTime as stringwhen it was last updated expireTime as stringwhen it expires totalTokens as intthe tokens it holds