GeminiLib for B4J, B4A and B4i
Recommended starting model, verified on November 14, 2026:
gemini-3.5-flash-lite. A real B4J sample successfully returned a response to “hola” using this model. This observation does not prove other models are permanently unavailable.
GeminiLib is a B4X client for the Gemini REST generateContent API. It supports text prompts, PDF analysis, image understanding, image generation, model discovery and asynchronous result events. This guide describes the actual public surface in the attached GeminiLib 6.2 diagnostic source, not every possible Google API capability.
1. Installation and your first request
Create a Gemini API key in Google AI Studio, check the project billing status, place GeminiLib.b4xlib in your B4X Additional Libraries folder, and select the library in B4J. The class uses B4X networking with HttpJob / OkHttpUtils2, JSON, StringUtils and XUI.
Sub Process_Globals
Private fx As JFX
Private MainForm As Form
Private Gemini As Gemini_IA
End Sub
Sub AppStart(Form1 As Form, Args() As String)
MainForm = Form1
MainForm.Show
Gemini.Initialize(Me, "Gemini")
Gemini.ApiKey = "KEY_FROM_A_SECURE_SOURCE"
Gemini.Model = "gemini-3.5-flash-lite"
Gemini.TimeoutMs = 120000
Gemini.Ask("Say hello in English.")
End Sub
Sub Gemini_Response(Result As Gemini_IA.GeminiResponse)
If Result.Success Then
Log("Answer: " & Result.Text)
Log("Finish reason: " & Result.FinishReason)
Else
Log("Request failed: " & Result.RequestID)
End If
End Sub
Sub Gemini_Error(Message As String)
Log("Gemini: " & Message)
End Sub
Assigning Gemini.ApiKey calls the public setApiKey(Key) setter. Do not embed a production API key in distributable executables; put it behind a trusted server with authentication, rate limits and billing controls.
2. Choose text and image models
Model is used by Ask, AskWithPdf and AskWithImage; ImageModel is used solely by GenerateImage.
Gemini.Model = "gemini-3.5-flash-lite" ' Tested: short requests
Gemini.Model = "gemini-3.5-flash" ' Alternative if enabled
Gemini.ImageModel = "gemini-3.1-flash-image"
For simple assistants, classification and document extraction, start with Flash-Lite. A higher-capability text model can be appropriate for more complex tasks if your project can use it. For image creation select an image-output model. Model IDs and available endpoints can change; consult the official model catalog.
Important: Some agents, including Deep Research, require the Interactions API or a specialized workflow. A model appearing in a list does not guarantee compatibility with a text-chat generateContent request. The model-description flags exposed by GeminiLib are suggestions, not capability tests.
3. TimeoutMs: request timeouts
TimeoutMs is a millisecond HTTP timeout. The diagnostic library defaults to 60000 (60 seconds). Try 120000 (2 minutes) for a slow request, but a longer timeout does not fix a depleted billing balance.
Gemini.TimeoutMs = 30000 ' 30 seconds for lightweight requests
Gemini.TimeoutMs = 120000 ' 2 minutes for a slower model or PDF
Gemini.TimeoutMs = 180000 ' 3 minutes for a targeted test
A java.net.SocketTimeoutException at Http2Stream.takeHeaders means the client timed out before receiving response headers. It is different from an HTTP 503 response and does not prove the JSON was malformed.
4. Retry configuration
GeminiLib 6.2 retries HTTP 500, 502, 503, 504 when enabled, with exponential delay. It does not automatically retry 429 in this implementation, even though Google's general API guidance discusses throttling retries. HTTP 402 is never retried.
Gemini.MaxTransientRetries = 2
Gemini.RetryBaseDelayMs = 1500
Gemini.RetryOnTimeout = False
Gemini.RetryImageRequests = False
The retry count is capped at five extra attempts. When an HTTP response is never received, the service may already have processed the request; enabling timeout or image-generation retries may duplicate work and charges.
One-shot diagnostic:
Gemini.Model = "gemini-3.5-flash-lite"
Gemini.TimeoutMs = 120000
Gemini.MaxTransientRetries = 0
Gemini.RetryOnTimeout = False
Gemini.Ask("Reply with only OK")
5. Generation settings and opt-in flags
The settings Temperature, TopK, TopP and MaxTokens are not sent unless their matching Send... flag is True; otherwise Gemini's model defaults apply.
| Property | Default | Purpose |
|---|---|---|
Temperature |
0.9 |
Sampling randomness |
TopK |
1 |
Top-k candidate sampling; rounded to integer |
TopP |
1 |
Nucleus sampling |
MaxTokens |
8000 |
Maximum requested output tokens |
SendTemperature |
False |
Explicitly send temperature |
SendTopK |
False |
Explicitly send topK |
SendTopP |
False |
Explicitly send topP |
SendMaxTokens |
False |
Explicitly send maxOutputTokens |
Gemini.Temperature = 0.2
Gemini.SendTemperature = True
Gemini.MaxTokens = 800
Gemini.SendMaxTokens = True
Gemini.Ask("Summarize the following concept in three bullet points: REST APIs")
Gemini.Temperature = 0.9
Gemini.SendTemperature = True
Gemini.TopP = 0.95
Gemini.SendTopP = True
Gemini.Ask("Suggest three imaginative names for a note-taking app")
Not every generation setting is supported by every model. On HTTP 400 try turning the Send... flags off before changing other parts of the request.
6. Text requests with Ask
Ask(Text As String) is asynchronous. It starts a request, and its result is raised in Response and RequestCompleted events. It does not directly return a text string.
Sub ButtonAsk_Click
Gemini.Model = "gemini-3.5-flash-lite"
Gemini.Ask("Explain the difference between JSON and XML.")
End Sub
Sub Gemini_RequestCompleted(RequestID As Long, Result As Gemini_IA.GeminiResponse)
If Result.Success Then Log(Result.Text)
End Sub
Use this for chat-style one-shot prompts, descriptions, simple extraction and classification. The class does not manage multi-turn chat history or tool/function calling.
7. PDF understanding with AskWithPdf
AskWithPdf(Text, PdfPath) reads a local PDF, validates its header and end marker, and sends inline Base64 PDF content. This class imposes a 15 MiB local-file limit; it does not implement Google's Files API.
Dim pdfFile As String = File.Combine(File.DirApp, "manual.pdf")
Gemini.TimeoutMs = 120000
Gemini.AskWithPdf("Summarize the document and list important tables.", pdfFile)
B4J desktop file picker:
Sub ButtonPdf_Click
Dim picker As FileChooser
picker.Initialize
picker.SetExtensionFilter("PDF documents", Array As String("*.pdf"))
Dim path As String = picker.ShowOpen(MainForm)
If path = "" Then Return
Gemini.AskWithPdf("Identify the title, date and key findings.", path)
End Sub
Use this for smaller manuals, invoices and reports. For larger or repeatedly referenced files, consider Google's Files API through a different integration. Remote URLs and content:// URIs are not accepted as local PDF paths.
8. Image understanding with AskWithImage
AskWithImage(Text, ImagePath) sends a local PNG, JPEG or WebP file with a question. It also enforces the internal 15 MiB size limit.
Dim imagePath As String = File.Combine(File.DirApp, "dashboard.png")
Gemini.AskWithImage("Describe the visible widgets and their labels.", imagePath)
Use it for screenshots, product photographs and visible text analysis. AI responses are not guaranteed to be correct; do not rely on them as sole evidence for safety-critical decisions.
9. Image generation with GenerateImage
GenerateImage(Prompt) sends a request through ImageModel and asks for both TEXT and IMAGE response modalities.
Gemini.ImageModel = "gemini-3.1-flash-image"
Gemini.ImageAspectRatio = "16:9"
Gemini.ImageSize = "1K"
Gemini.RetryImageRequests = False
Gemini.GenerateImage("A colorful modern software desk, no text, soft daylight.")
ImageAspectRatio supports 1:1, 1:4, 4:1, 1:8, 8:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9. ImageSize accepts 512, 1K, 2K, 4K; in this library 512 is restricted to gemini-3.1-flash-image. These are validation values, not a promise that all image models support every combination. Empty strings mean “use the model defaults.”
10. Save generated images
SaveImage(bmp, Dir, FileName) writes a PNG/JPEG without returning a value. SaveImageEx additionally returns True when the write succeeds. Supported extensions are .png, .jpg, .jpeg; an extensionless filename becomes PNG. The directory must already exist.
Sub Gemini_Response(Result As Gemini_IA.GeminiResponse)
If Result.Success = False Then Return
Log(Result.Text)
If Result.IsImage Then
Dim saved As Boolean = Gemini.SaveImageEx(Result.Image, File.DirApp, "art.png")
Log("Saved: " & saved)
For Each entry As Gemini_IA.GeminiImage In Result.Images
Log("MIME: " & entry.MimeType)
Next
End If
End Sub
Result.Image is the first image; Result.Images contains every returned GeminiImage entry with Image and MimeType. Saving directly to WebP is not supported.
11. Discover models with GetModels and GetModelsDetailed
The library paginates models.list, selects entries that declare generateContent, and emits model-list events.
Gemini.GetModels
Sub Gemini_ModelsLoaded(Models As List, Success As Boolean)
If Success = False Then Return
For Each name As String In Models
Log("Model: " & name)
Next
End Sub
Gemini.GetModelsDetailed
Sub Gemini_ModelsDetailedLoaded(Models As List, Success As Boolean)
If Success = False Then Return
For Each item As Map In Models
Log(item.Get("name"))
Log(item.Get("supportedGenerationMethods"))
Log(item.Get("inputTokenLimit"))
Log(item.Get("suggestedForImageGeneration"))
Next
End Sub
Each detailed Map contains name, displayName, description, supportedGenerationMethods, inputTokenLimit, outputTokenLimit, supportsGenerateContent, suggestedForImageGeneration, suggestedForText. The two suggested-category fields are only filename heuristics.
12. Events, result data and multiple requests
After Initialize(Me, "Gemini"), handle events using the prefix Gemini_.
| Event | Parameters | Use |
|---|---|---|
Gemini_Response |
Result As GeminiResponse |
Completion, success or failure |
Gemini_RequestCompleted |
RequestID, Result |
Same completion with explicit ID |
Gemini_Error |
Message |
General error, model-list error or request failure |
Gemini_RequestError |
RequestID, Message |
Request error with ID |
Gemini_ModelsLoaded |
Models, Success |
Basic list from either listing method |
Gemini_ModelsDetailedLoaded |
Models, Success |
Detailed list from GetModelsDetailed |
Public GeminiResponse fields: Text As String, Image As B4XBitmap, IsImage As Boolean, Success As Boolean, RequestID As Long, MimeType As String, FinishReason As String, Images As List.
Public GeminiImage fields: Image As B4XBitmap and MimeType As String. The helper LocalFilePath has Directory and FileName.
Sub Gemini_RequestCompleted(RequestID As Long, Result As Gemini_IA.GeminiResponse)
If Result.Success Then
Log("OK #" & RequestID & ": " & Result.Text)
Else
Log("Failed #" & RequestID)
End If
End Sub
Sub Gemini_RequestError(RequestID As Long, Message As String)
Log("Error #" & RequestID & ": " & Message)
End Sub
Avoid duplicate work: Response and RequestCompleted represent the same completion. Likewise, Error and RequestError can both fire for one failure. Handle side effects once, not in both event handlers. FinishReason="STOP" generally means successful stopping; safety blocks can produce Success=False.
13. Complete public API index
| Public method / property | Purpose |
|---|---|
Initialize(CallbackModule, EventName) |
Configure callback event target |
setApiKey(Key) / ApiKey setter |
Set the key held in memory |
ClearApiKey |
Clear the key from the instance |
Ask(Text) |
Start text generation |
AskWithPdf(Text, PdfPath) |
Analyze local PDF (up to 15 MiB) |
AskWithImage(Text, ImagePath) |
Analyze local PNG/JPEG/WebP (up to 15 MiB) |
GenerateImage(Prompt) |
Request image output via ImageModel |
GetModels |
Retrieve generateContent-capable model IDs |
GetModelsDetailed |
Retrieve per-model metadata |
SaveImage(bmp, Dir, FileName) |
Write PNG/JPEG bitmap |
SaveImageEx(bmp, Dir, FileName) |
Write PNG/JPEG bitmap with Boolean status |
Model |
Model used for Ask / input analysis |
ImageModel |
Image-output model ID |
TimeoutMs |
HTTP timeout in milliseconds |
Temperature, SendTemperature |
Optional temperature override |
TopK, SendTopK |
Optional topK override |
TopP, SendTopP |
Optional topP override |
MaxTokens, SendMaxTokens |
Optional output token limit |
MaxTransientRetries |
Additional retries for selected 5xx responses |
RetryBaseDelayMs |
Delay before first retry |
RetryOnTimeout |
Allow retry after no HTTP reply |
RetryImageRequests |
Allow image-request retries |
ImageAspectRatio |
Image output shape |
ImageSize |
Image output size |
GeminiResponse, GeminiImage, LocalFilePath |
Public data types |
Six Gemini_... events |
Async result, error and model-list callbacks |
Not included: streaming response output, Google's Files API uploads, automatic conversation history, function calling / tool dispatch, Deep Research orchestration, or Interactions API. Do not mistake these Google features for methods of this library.
14. Troubleshooting: real observations
| Result | Meaning | Next step |
|---|---|---|
| 402 Payment Required | Prepaid credits depleted | Review project billing. Do not retry |
| 503 Unavailable | Temporary service overload | Retry cautiously or select a compatible model |
| 429 Too Many Requests | Rate or quota limit | Check exact Google error and usage |
| 400 Bad Request | Invalid request or unsupported options | Check model/config; disable Send... flags |
| 401/403 | Invalid key or permissions | Verify API key and project |
| 404 | Unknown model or endpoint | Check model ID |
| SocketTimeoutException | No response headers in time | Review TimeoutMs, server latency, connectivity |
| Model listing succeeds but generation fails | Listing access is not proof of generate access | Check billing, service and selected endpoint |
Observed in testing on November 14, 2026: gemini-3.8-flash and gemini-3.7-flash returned 503/timeout, while gemini-3.5-flash-lite returned text and finishReason=STOP. These are time-specific observations, not permanent model availability claims.
15. Security and official references
Do not expose real API keys in Git repositories, binaries or logs. Verify generated content for critical tasks. Request timeouts and retries cannot resolve an exhausted prepayment balance. The list of Google models and their prices changes.
- Gemini models
- Gemini 3.5 Flash-Lite
- generateContent API reference
- PDF understanding
- Image generation
- Troubleshooting
- Official API error reference
- Prepay billing
- Google AI Studio projects
- B4X community forum
Documentation is based on the supplied GeminiLib 6.2 diagnostic class. Compile and run regression tests in your target B4X IDE before a production or commercial release.