Gemini4KT
0.9.0indexedLightweight wrapper for Gemini REST API, offering simple request/response handling, Gradle example runner, generated API documentation and minimal dependency footprint.
Lightweight wrapper for Gemini REST API, offering simple request/response handling, Gradle example runner, generated API documentation and minimal dependency footprint.
We will not maintain this library anymore. We are moving to Google Gen AI Java SDK(https://github.com/googleapis/java-genai).
This is a Kotlin Multiplatform wrapper library for Gemini's RestAPI, a lightweight library that does not require the Android SDK.
See RestAPI specifications and https://ai.google.dev/gemini-api/reference/rest for more information.
Set your Gemini API key as an environment variable before running the sample:
cp .env.example .env
# Edit .env and set GEMINI_API_KEY=your-real-key
source .env
./gradlew jvmRun
.env is ignored by git so your key stays local. Look at src/commonTest/kotlin/io/github/ugaikit/gemini4kt/samples for sample usage.
For paid-tier projects created on or after October 26, 2026, the Generate Content API
stores requests by default. Older projects retain their existing setting. Gemini4KT
leaves store unspecified by default so the project's setting applies.
Set store = false to disable storage for an individual request, or store = true
to explicitly enable it:
val request = generateContentRequest {
content { part { text { "Hello" } } }
store = false
}
val response = gemini.generateContent(request)
The constructor also accepts GenerateContentRequest(contents = contents, store = false).
The same setting applies when the request is passed to streamGenerateContent, used
for automatic function calling, or included in a batch with batchItemRequest { request(request) }.
For file-backed batches, include "store": false in each Generate Content request in
the input JSONL file; Gemini4KT does not rewrite uploaded files.
You can also change the project default in the Logs and Datasets dashboard's Settings panel. See Logs and datasets and the October 26 release notes.
Agent.baseEnvironment and CreateAgentRequest.baseEnvironment accept either an inline
AgentEnvironment or an AgentEnvironmentReference. Code that needs inline environment fields
such as , , or can use or
and should handle when the API returns an environment ID.
xhigh thinkingUse model = "gemini-4-hydrogen" with either generation API. Hydrogen supports
low, medium, high (the server default), and xhigh. Generate Content uses
ThinkingConfig(thinkingLevel = ThinkingLevel.XHIGH); Interactions uses
InteractionGenerationConfig(thinkingLevel = io.github.ugaikit.gemini4kt.interaction.ThinkingLevel.XHIGH):
val response = geminiAI.createInteraction(
CreateInteractionRequest(
model = "gemini-4-hydrogen",
input = "Review this migration design for concurrency problems.",
generationConfig = InteractionGenerationConfig(
thinkingLevel = io.github.ugaikit.gemini4kt.interaction.ThinkingLevel.XHIGH,
),
),
)
When migrating from Gemini 3.8 Flash, omit minimal, legacy thinking budgets,
explicit cachedContent, and sampling overrides (temperature, topP, topK).
The shared 1,048,576-token context includes input, thinking, and output. Synchronous
requests are limited to 65,536 tokens per hop; use Interactions background = true
with a larger for longer outputs. The library leaves output caps
and thinking depth unset unless configured by the caller.
For background generation, poll with getInteraction(id) while the status is
QUEUED or IN_PROGRESS, then read allOutputText to concatenate text from all
model output steps. To resume a stored stream, collect
resumeInteractionStream(id, lastEventId) using the latest received event_id.
For foreground long decode, Gemini4KT exposes the REST continuation tokens so the caller controls each request:
Automatic function-calling helpers return a response that requires continuation so the caller can resume generation. A request submitting a tool result starts a new turn and omits the previous generation hop's token.
See the long decode guides for Interactions and Generate Content.
The Managed Agents Antigravity default is selected by the service and now uses
Hydrogen. Existing antigravity-preview-09-2026 requests inherit it when no model
override is supplied; InteractionAgentConfig.model and AgentConfig.model also
accept gemini-4-hydrogen explicitly. See the
Hydrogen migration guide
and model card and pricing.
Use a paid Gemini API project to create a world with createGenieInteraction().
For browsers, mint a scoped credential on the server with
createInteractionAuthToken(interaction.id) and give the browser the interaction
ID and token. Keep the long-lived API key on the server.
connectGenieWebSocket(id, authToken) receives JPEG video and
48 kHz stereo PCM audio as base64 data in step.delta events. A backend can
omit the scoped token and use its configured API key.Once connected, call setupWorld(text, referenceImage) once with text, an
inline base64 16:9 JPEG/PNG, or both. Use sendKey(GenieKey.W, GenieKeyAction.DOWN)
and the matching UP to move, arrow keys to look around, and sendText(...) to
change the scene. Collect receive() for media and lifecycle events.
When finished, call and read the terminal event before calling
. To abort generation, send . Closing the transport alone
can leave server generation and billing active.
See Genie 4, prompts and controls, and rate limits.
For server-side retrieval on Gemini 3.6 and later, include
InteractionTool(type = "tool_search") alongside the function declarations or
remote MCP servers you want to defer. Set deferLoading = true on those tools
and keep the tool list on follow-up requests.
For client-managed retrieval, declare InteractionTool(type = "tool_search", execution = "client", name = "search_registry", description = "...", parameters = schema).
Handle the search function_call by selecting matching declarations locally.
Return interactionToolSearchResult(callId, "search_registry", matches) inside
interactionStepsInput(...) with the previous interaction ID. In stateless
conversations, preserve the original search steps in order, including their
signatures. See Tool retrieval.
Select model = "gemini-4-neon" with either generation API on a paid project.
Neon uses the same XHIGH setting and long-decode flow as Hydrogen. Its default
thinking level is high and its 1,048,576-token context is shared by input,
thinking, and output. For more than 65,536 generated tokens, set a larger output
budget and use background execution or continuation. See the
Neon migration guide.
Attach Office or OpenDocument files directly with the file's MIME type. The existing Files API and inline data inputs support Word, PowerPoint, and Excel formats, as well as OpenDocument text, presentations, and spreadsheets.
For Interactions, attach a file in an InteractionContent block and set
processing = InteractionStaticProcessing(...). This example selects a range
from the second worksheet. Use pageOptions for page or slide ranges, or
startOffset and endOffset for an audio or video clip. Video also supports
fps and such as .
val sheet = InteractionContent(
type = "document",
uri = workbookUri,
mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
processing = InteractionStaticProcessing(
spreadsheetOptions = InteractionSpreadsheetOptions(
sheetIndex = 2,
visibleCells = "A1:H50",
contentLayers = listOf("data", "formulas"),
),
),
)
val request = CreateInteractionRequest(
model = "gemini-4-neon",
input = interactionContentInput(
arrayOf(sheet, InteractionContent(type = "text", text = "Summarize this range.")),
),
)
To return that same slice from a function, use
interactionStepsInput(arrayOf(interactionFunctionResult(callId, "inspect", arrayOf(sheet))))
as the next request's input and pass the previous interaction's ID.
For Generate Content, set documentMetadata, spreadsheetMetadata,
videoMetadata, or audioMetadata on a Part with or .
Generate Content layer values are uppercase, for example
.
The same metadata can be used on attachments in .
See the document, video, audio, and function response guides.
Use Smart mode to dictate and edit in the same recording, or pass sourceText
to apply spoken edits to existing text. The API accepts up to 64 KiB of UTF-8
source text. Omit sourceText to start from dictation.
For the Interactions API, pass the recording as audio input. To apply another
spoken edit, send the new recording and use the preceding response's
outputText as sourceText.
val result = geminiAI.createInteraction(
CreateInteractionRequest(
model = "gemini-3.5-transcribe",
input = interactionContentInput(
arrayOf(InteractionContent(type = "audio", uri = audioUri, mimeType = "audio/mpeg")),
),
generationConfig = InteractionGenerationConfig(
transcriptionConfig = InteractionTranscriptionConfig(
mode = InteractionTranscriptionMode(
type = InteractionTranscriptionModeType.SMART,
sourceText = "The review starts at noon.",
),
),
),
),
)
println(result.outputText)
For Live transcription, set the initial text during WebSocket setup and send
PCM audio with sendRealtimeInput. When serverContent.inputTranscription
arrives, replace the editor text with its text.orEmpty(). Use
interimInputTranscription to preview the spoken instruction. The server carries
the latest finalized text across spoken turns. Reconnect with updated source text
after a manual edit.
This example uses manual turn boundaries. Send ActivityStart before the first
audio chunk and ActivityEnd after the final chunk of each turn.
val live = GeminiLive(
apiKey = apiKey,
model = "gemini-3.5-transcribe-live",
config = LiveConnectConfig(
responseModalities = arrayOf(Modality.TEXT),
inputAudioTranscription = AudioTranscriptionConfig(
mode = AudioTranscriptionMode.SMART,
sourceText = "The review starts at noon.",
),
realtimeInputConfig = RealtimeInputConfig(
automaticActivityDetection = AutomaticActivityDetection(disabled = true),
),
),
)
val session = live.connect()
See the Audio transcription and Live transcription guides.
GeminiAI.createDecision evaluates typed questions over shared input and returns
calibrated probabilities without generated text tokens:
The default model is . or accepts text, image, audio, video, and PDF document blocks using inline data or URI references. Question instructions also accept , restricted to text blocks. Binary questions optionally accept ; categorical answers expose and ; rubric answers expose , , and . reports token counts, including zero output tokens. API errors use the existing . For media URIs, use the Files API or public/signed HTTPS URLs; the Decisions API does not accept YouTube URLs or direct references.
See the Decisions API guide, pricing, and rate limits.
Use OmniVideoSample.request() with GeminiAI.createInteraction to generate a
video with gemini-omni-1.2-flash:
val video = geminiAI.createInteraction(
OmniVideoSample.request("Generate a 15-second video of a marble rolling along a wooden track."),
)
// Once the first interaction has completed, continue with an edit or extension:
val extended = geminiAI.createInteraction(
OmniVideoSample.request(
prompt = "Extend the video by 5 seconds as the marble reaches the finish line.",
task = InteractionVideoTask.EXTEND,
previousInteractionId = video.id,
),
)
The sample's optional media accepts InteractionContent images or video. Pass
up to six reference images for reference-to-video, or first/last images for
interpolation. InteractionGenerationConfig.videoConfig and InteractionVideoTask
provide optional task overrides for text-to-video, image-to-video,
reference-to-video, editing, and extension. Otherwise the model infers the task.
Describe durations and media roles in natural language: general generation supports
up to 15 seconds; interpolation and each extension support 3–10 seconds, with
extended videos up to 30 seconds total. Generated media is available in
interaction.outputVideo.
The service automatically routes gemini-omni-1.1-flash to 1.2 starting December 3,
2026. New examples use 1.2 explicitly. Pricing and paid-tier quota changes are
service-side; see the Omni guide,
pricing, and
rate limits.
Office and OpenDocument MIME types work with InlineData, FileData, and
Interactions InteractionContent(type = "document", ...) using data or uri.
The expanded formats include:
DOCX, DOTX, ODT, PPTX, XLSX, and XLS retain their existing processing behavior. MIME types remain strings, so uploads accept the expanded formats without a new file-type restriction. See Office and OpenDocument files.
Generate Content FunctionResponse.parts accepts inline or URI-based documents,
audio, and video as well as image, PDF, and text results. Both InlineData and
FileData support displayName. Video parts can specify MediaProcessing.STATIC
or MediaProcessing.AGENTIC:
val result = FunctionResponse(
name = "read_video",
response = buildJsonObject { },
parts = arrayOf(
Part(
fileData = FileData("video/mp4", uploadedVideoUri, displayName = "walkthrough"),
mediaProcessing = MediaProcessing.AGENTIC,
),
),
)
For Interactions, put typed media blocks into a function_result step's JSON
result. Existing image and text blocks continue to work alongside the new types:
val resultStep = InteractionStep(
type = "function_result",
name = "read_files",
callId = functionCallId,
result = Json.encodeToJsonElement(
arrayOf(
InteractionContent(type = "document", uri = documentUri, mimeType = "application/vnd.ms-powerpoint"),
InteractionContent(type = "audio", data = audioBase64, mimeType = "audio/wav"),
InteractionContent(
type = "video", uri = videoUri, mimeType = "video/mp4",
processing = InteractionVideoProcessing.AGENTIC,
),
),
),
)
Submit the step through InteractionInput.StepList. Interactions video results
use the v1beta endpoint already used by this library. See
multimodal function responses.
Computer Use is available through both APIs. For Generate Content, configure the existing tool DSL with a browser, mobile, or desktop environment:
val request = generateContentRequest {
content { part { text { "Search for Gemini API documentation." } } }
tool {
computerUse {
environment = Environment.ENVIRONMENT_BROWSER
enablePromptInjectionDetection = true
}
}
store = false
}
val response = gemini.generateContent(request, model = "gemini-4-hydrogen")
For Interactions, use InteractionTool(type = "computer_use", environment = "browser", enablePromptInjectionDetection = true) in CreateInteractionRequest.tools.
Use "mobile" or "desktop" for the other environments. Both tool types expose
disabledSafetyPolicies; Generate Content uses uppercase policy names such as
DATA_MODIFICATION, while Interactions uses lowercase names such as .
Leaving the option unset retains the API's safety policies.
ComputerUseSample.run() demonstrates Interactions and
ComputerUseSample.runGenerateContent() demonstrates Generate Content, using
gemini-4-hydrogen by default. Both accept a model override. These samples request
actions; applications supply screenshots, execute allowed actions, handle
safety_decision confirmations, and return action results. See the
Computer Use guide for supported
models and the action loop.
Create an independent stored voice from a prebuilt voice name, a catalog voice ID,
or an existing designed/remixed voice_... ID:
val remixed = geminiAI.createRemixedVoice(
baseVoice = "Puck",
instructions = "Make the delivery softer and slightly lower in pitch.",
displayName = "Soft narrator",
)
val speech = geminiAI.generateSpeech(
text = "Welcome to the next chapter.",
voice = remixed.id,
model = "gemini-3.8-flash-lite-tts",
)
Remixing uses with and . It creates a new voice without modifying the source. The returned ID supports both and for synthesis. The response includes when available, and for lineage, and for retention metadata. The existing , , and methods also work with remixed voices. See the .
Gemini API CLI (gemini-api) is Google's
stateless command-line client for the Interactions API. Use it to call Gemini from
an AI coding agent, a shell script, or a CI job. Use Gemini4KT when calling the API
from Kotlin code. gemini-api is a separate tool from the interactive Gemini CLI
(@google/gemini-cli) and is not required to build or use this library.
Install a specific release on macOS or Linux, using an actual tag from the
CLI releases in place of
<release-tag>:
curl -fsSL https://raw.githubusercontent.com/google-gemini/gemini-api-cli/main/scripts/install.sh \
| GEMINI_VERSION='<release-tag>' bash
Keep the release pinned in scripts and CI because the CLI is beta. Provide
GEMINI_API_KEY through the environment, as for this repository's Kotlin samples.
Inspect the available commands and request schema, then preview a request offline:
gemini-api --usage
gemini-api generate --schema
gemini-api generate "Explain Kotlin coroutines briefly." \
--stream=false -o json --body '{"store":false}' --dry-run
Remove --dry-run to make an API request. Use --stream=false -o json for a single
JSON result in scripts. These examples generate text and media, analyze a local
file, and start a background managed agent:
gemini-api generate "Explain Kotlin coroutines briefly." \
--stream=false -o json --body '{"store":false}'
gemini-api image "A small blue robot reading a book" --out ./robot.jpg
gemini-api analyze -i ./report.pdf "Summarize the key findings."
gemini-api agent run "Compare Kotlin HTTP clients and cite sources." \
--agent deep-research-preview-04-2026 --background --stream=false -o json
# Save the returned interaction id and pass it to:
# gemini-api agent status <interaction-id> -o json
Commands keep no hidden local conversation state. Continue an interaction explicitly
with --previous-interaction-id. Local statelessness does not disable server-side
request logging; use --body '{"store":false}' where supported to opt out of storage.
For advanced options, inspect the command's --schema before supplying --body.
In a GitHub Actions job with a pinned CLI release installed on PATH, a step can
inject the API key from repository secrets and capture structured output:
- name: Generate text with Gemini API CLI
env:
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
run: |
mkdir -p artifacts
gemini-api generate "Explain Kotlin coroutines briefly." \
--stream=false -o json --body '{"store":false}' > artifacts/gemini-response.json
Check the command's exit status: 0 means success, 1 a runtime or API error,
2 invalid usage, and 3 an authentication error. Standard HTTP, SSE streaming,
and asynchronous polling are supported. For bidirectional real-time audio or video,
use this library's GeminiLive client.
The API documentation is available at https://takanori-ugai.github.io/Gemini4KT/.
kotlin {
sourceSets {
commonMain {
dependencies {
implementation("io.github.ugaikit:gemini4kt:0.8.0")
}
}
}
}
sourcestypenetworkagent.inlineEnvironmentrequest.inlineEnvironmentnullmaxOutputTokensREQUIRES_CONTINUATION, create the next request with the
same model and generation settings, the hop's continuationToken, and its ID
as previousInteractionId. Omit input for a stored interaction. For
store = false, resend the original input and omit previousInteractionId.finishReason == "CONTINUATION", resend the same
request with the candidate's continuationToken at the request top level,
for example request.copy(continuationToken = candidate.continuationToken).
Combine output parts across hops in order to preserve thought signatures when replaying history.connectGenieWebRtc(id, peer, authToken)BrowserGenieWebRtcPeer(videoElement)<video autoplay playsinline>GenieWebRtcPeercomplete()close()cancel()contentLayerstranscriptfileDatainlineDataDocumentMetadata(startPage = 3, endPage = 7, contentLayers = listOf("PAGE_TEXT"))FunctionResponse.partsimport io.github.ugaikit.gemini4kt.decisions.*
val decision = geminiAI.createDecision(
CreateDecisionRequest(
input = "The item arrived broken and I need a replacement.",
questions = mapOf(
"damaged" to DecisionQuestion.Noul("Did the item arrive damaged?"),
"route" to DecisionQuestion.Choice(
"Which team should handle this?",
mapOf("support" to "Product problems", "billing" to "Payment problems"),
),
"severity" to DecisionQuestion.Score(
"How severe is this issue?",
listOf("Minor", "Workaround available", "Blocked"),
),
),
),
)
val damaged = decision.answers.getValue("damaged") as DecisionAnswer.Noul
println("Probability of yes: ${damaged.noul}; confidence: ${damaged.confidence}")
gemini-decision-1DecisionInput(InteractionContent(...))DecisionInput(listOf(...))DecisionInputNoulCriteriachoiceprobabilitiesscoreprobabilitieslegenddecision.usageGeminiExceptiongs://| Format | MIME type | Model input |
|---|
| DOC | application/msword | Rendered page images |
| PPT | application/vnd.ms-powerpoint | Rendered slide images |
| ODP | application/vnd.oasis.opendocument.presentation | Rendered slide images |
| ODS | application/vnd.oasis.opendocument.spreadsheet | First sheet's data and formulas |
data_modificationPOST /v1beta/voicesgemini-3.8-flash-ttsstore=truegemini-3.8-flash-ttsgemini-3.8-flash-lite-ttssampleAudioprompted.baseVoiceprompted.inputexpireTimegetVoicelistVoicesdeleteVoiceSurfaced from shared tags and platforms — no rankings paid for.