Download the PHP package ldkafka/yii2-google-gemini without Composer
On this page you can find all versions of the php package ldkafka/yii2-google-gemini. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package yii2-google-gemini
Yii2 Google Gemini Component (v2.0.0)
Native, strongly-typed Yii2 component for the Google Gemini REST API. No external SDKs – only yii\\httpclient. Provides generation (text & multimodal), streaming, embeddings, Files API, token counting, and flexible caching strategies.
What’s New in 2.0.0
- Rebuilt on pure REST calls (no Gemini SDK)
- Added multimodal inline data handling
- Added SSE streaming helper
- Full embeddings single + batch support
- Files API wiring (simplified upload flow)
- Model discovery (list + get)
- Uniform response shape & error handling
- Client & server caching patterns
- Strict typing,
finalclass, consistent helper methods
Feature Summary
| Area | Capabilities |
|---|---|
| Generation | Text, multimodal (image/audio/video/document via inline or file references) |
| Streaming | SSE incremental output with user callback |
| Caching | none, client (Yii cache history), server (Gemini CachedContent) |
| Embeddings | Single + batch embeddings for RAG / similarity |
| Files | Upload, list, get, delete (simplified direct PUT) |
| Models | Enumerate models, inspect limits/capabilities |
| Tokens | Pre-flight token counting for cost estimation |
| Helpers | extractText, getFinishReason, getUsageMetadata |
Requirements
- PHP >= 8.0
- Yii2 >= 2.0.40
- yiisoft/yii2-httpclient
Installation
Quick Start
Basic Configuration
Simple Text Generation
Usage Examples
1. Basic Text Generation
2. Streaming Responses
3. Multimodal (Text + Image)
4. Client-side Conversation Caching
5. Server-side Context Caching (Advanced)
6. System Instructions
7. File Uploads
8. Embeddings
9. Token Counting
10. Model Discovery
Caching Modes Deep Dive
| Mode | Purpose | Storage | Pros | Cons |
|---|---|---|---|---|
none |
Stateless requests | None | Simplicity | No memory of prior turns |
client |
Short/medium chats | Yii cache (gem_chat_<id>) |
Fast, light, adjustable TTL | History grows; prune for very long sessions |
server |
Large domain context | Gemini CachedContent | Huge reusable context on provider side | Requires ~32K+ tokens; creation often fails if too small |
Server cache creation requires a very large system instruction document. Use countTokens() before attempting createServerCache().
Console Commands
Example test commands in console/controllers/TestController.php:
Configuration Options
Component Properties
| Property | Type | Default | Description |
|---|---|---|---|
apiKey |
string | required | Your Gemini API key (Get one) |
baseUrl |
string | https://generativelanguage.googleapis.com/v1/ |
API base URL |
generationConfig |
array | [] |
Default generation parameters |
safetySettings |
array | [] |
Content safety filters |
systemInstruction |
array|null | null |
Default system instruction |
cacheType |
string | 'none' |
Cache mode: 'none', 'client', 'server' |
cacheTtl |
int | 3600 |
Cache TTL in seconds |
cacheComponent |
string|null | 'cache' |
Yii cache component name |
httpConfig |
array | [] |
Custom HTTP client configuration |
Generation Config Options
Supported Models (Snapshot)
| Model | Description | Context Window |
|---|---|---|
gemini-2.5-pro |
Most powerful thinking model | 2M tokens |
gemini-2.5-flash |
Balanced, fast, 1M context | 1M tokens |
gemini-2.5-flash-lite |
Fastest, cost-efficient | 1M tokens |
text-embedding-004 |
Text embeddings for RAG | N/A |
See Gemini Models Documentation for full list.
Canonical Response Format
All methods return:
Helper Methods
Helper Methods
Cache Modes (Summary)
None (Stateless)
Client (Local Conversation History)
Server (Gemini Context Caching)
Note: Server caching requires minimum 32,000 tokens in cached content.
Error Handling Pattern
Advanced Usage
Custom HTTP Configuration
Multimodal with Multiple Images
Custom Safety Settings
Safety Settings Explained
safetySettings lets you tell Gemini which kinds of harmful content to filter and at what strictness. The value is an array of objects with a category and a threshold.
- Common categories:
HARM_CATEGORY_HARASSMENT,HARM_CATEGORY_HATE_SPEECH,HARM_CATEGORY_SEXUALLY_EXPLICIT,HARM_CATEGORY_DANGEROUS_CONTENT,HARM_CATEGORY_VIOLENCE. - Typical thresholds (in order of strictness):
BLOCK_NONE,BLOCK_LOW_AND_ABOVE,BLOCK_MEDIUM_AND_ABOVE,BLOCK_ONLY_HIGH.
Example JSON payload as sent to the API:
Notes:
- If
safetySettingsis empty, no custom filters are applied (provider defaults may still apply). - You can mix categories with different thresholds.
- Overly strict settings can block benign answers; adjust to your domain’s tolerance.
Testing
The package includes comprehensive test actions:
- actionGeminiNone - Test stateless generation
- actionGeminiClient - Test client-side conversation caching
- actionGeminiServer - Test server-side context caching
Troubleshooting
"API key not configured"
Ensure your API key is set in the component configuration or params.
"Failed to create server cache"
Server caching requires:
- Minimum 32,000 tokens in the cached content
- Supported model (gemini-2.5-flash, gemini-2.5-pro)
- System instruction or large document
Use client-side caching for shorter conversations.
Streaming not working
Ensure your HTTP client supports Server-Sent Events (SSE). The default Yii2 HTTP client may need custom transport configuration.
Production Notes
- Implement backoff + retry for
429& transient5xxresponses. - Prune client cache histories when token counts get large (outside of scope for this base component).
- For server caching: build and store a domain knowledge base (e.g., large markdown/text corpus) and verify token count with
countTokens(). - Log latency and token usage:
Yii::info([...], 'gemini')for observability.
Links
License
BSD-3-Clause (matches class header).
Support / Contributing
Open issues or PRs at: https://github.com/ldkafka/yii2-google-gemini
When reporting an issue, include:
- PHP / Yii versions
- Failing method and sample call
- Full response array (mask secrets)
- Expected vs actual behavior
Enjoy building with Gemini! Suggestions & improvements welcome.