|
| 1 | +# gapps-gemini-client |
| 2 | + |
| 3 | +A Google Apps Script client library for interacting with Google's Gemini AI API. This library provides a clean, feature-rich interface for generating text, structured JSON responses, and managing conversational AI interactions within Google Apps Script projects. |
| 4 | + |
| 5 | +## Features |
| 6 | + |
| 7 | +- **Text Generation**: Generate plain text responses from prompts |
| 8 | +- **Structured JSON Output**: Force JSON responses with optional schema validation |
| 9 | +- **Conversation Management**: Maintain conversation history with user/model turns |
| 10 | +- **System Instructions**: Set persistent system-level instructions |
| 11 | +- **Model Selection**: Switch between different Gemini models (e.g., gemini-1.5-flash, gemini-1.5-pro) |
| 12 | +- **Automatic Retries**: Built-in retry logic with exponential backoff for transient errors |
| 13 | +- **Character Budget Management**: Automatic conversation history trimming to stay within token limits |
| 14 | +- **Comprehensive Testing**: Extensive test suite using the gapps-unit-test-library |
| 15 | + |
| 16 | +## Dependencies |
| 17 | + |
| 18 | +This project depends on the **gapps-unit-test-library** for its comprehensive test suite. The testing framework provides: |
| 19 | +- Test class structure with `before()` and `after()` hooks |
| 20 | +- Assertion utilities (`Assert.isTrue`, `Assert.match`, `Assert.deepEquals`) |
| 21 | +- Automated test discovery and execution |
| 22 | + |
| 23 | +## Setup |
| 24 | + |
| 25 | +1. **API Key Configuration**: Set your Gemini API key as a Script Property named `gemini.key` |
| 26 | +2. **Include Dependencies**: Ensure both `GeminiClient.js` and the `Test.js` from gapps-unit-test-library are included in your Google Apps Script project |
| 27 | + |
| 28 | +## Basic Usage |
| 29 | + |
| 30 | +### Simple Text Generation |
| 31 | + |
| 32 | +```javascript |
| 33 | +const client = new GeminiClient(PropertiesService.getScriptProperties().getProperty('gemini.key')); |
| 34 | + |
| 35 | +// Generate plain text |
| 36 | +const response = client.generateText('Write a 2-sentence fun fact about Belize.', { |
| 37 | + temperature: 0.7 |
| 38 | +}); |
| 39 | +console.log(response); |
| 40 | +``` |
| 41 | + |
| 42 | +### Structured JSON Output |
| 43 | + |
| 44 | +```javascript |
| 45 | +const schema = { |
| 46 | + type: 'array', |
| 47 | + items: { |
| 48 | + type: 'object', |
| 49 | + properties: { |
| 50 | + district: { type: 'string' }, |
| 51 | + attraction: { type: 'string' }, |
| 52 | + tags: { type: 'array', items: { type: 'string' } } |
| 53 | + }, |
| 54 | + required: ['district', 'attraction'] |
| 55 | + } |
| 56 | +}; |
| 57 | + |
| 58 | +const response = client.generateJSON( |
| 59 | + 'Return 3 Belize travel attractions as JSON array of {district, attraction, tags}.', |
| 60 | + schema, |
| 61 | + { temperature: 0.2 } |
| 62 | +); |
| 63 | + |
| 64 | +const attractions = JSON.parse(response); |
| 65 | +``` |
| 66 | + |
| 67 | +### Conversational AI |
| 68 | + |
| 69 | +```javascript |
| 70 | +// Initialize with conversation history |
| 71 | +const client = new GeminiClient(apiKey, { |
| 72 | + history: [ |
| 73 | + { role: 'user', parts: [{ text: 'Plan a 1-day Belize City itinerary.' }] } |
| 74 | + ], |
| 75 | + systemInstruction: 'Be concise, friendly, and factual.' |
| 76 | +}); |
| 77 | + |
| 78 | +// Send message and get response |
| 79 | +const response = client.send({ temperature: 0.4 }); |
| 80 | + |
| 81 | +// Add follow-up |
| 82 | +client.addTurn('user', 'Add a family-friendly lunch spot.'); |
| 83 | +const followUpResponse = client.send({ temperature: 0.4 }); |
| 84 | +``` |
| 85 | + |
| 86 | +## API Reference |
| 87 | + |
| 88 | +### Constructor |
| 89 | + |
| 90 | +```javascript |
| 91 | +new GeminiClient(apiKey, opts = {}, fetch = UrlFetchApp.fetch) |
| 92 | +``` |
| 93 | + |
| 94 | +**Parameters:** |
| 95 | +- `apiKey` (string): Your Gemini API key |
| 96 | +- `opts` (object, optional): |
| 97 | + - `model` (string): Gemini model name (default: 'gemini-1.5-flash') |
| 98 | + - `timeoutMs` (number): Request timeout in milliseconds (default: 60000) |
| 99 | + - `history` (array): Initial conversation history |
| 100 | + - `systemInstruction` (string): System-level instruction |
| 101 | +- `fetch` (function): Fetch function for testing (default: UrlFetchApp.fetch) |
| 102 | + |
| 103 | +### Core Methods |
| 104 | + |
| 105 | +#### `generateText(prompt, generationConfig = {})` |
| 106 | +Generate plain text from a prompt. |
| 107 | + |
| 108 | +#### `generateJSON(prompt, schema = undefined, config = {})` |
| 109 | +Generate structured JSON output with optional schema validation. |
| 110 | + |
| 111 | +#### `send(generationConfig = {})` |
| 112 | +Send the current conversation and get model reply. Appends the response to history. |
| 113 | + |
| 114 | +#### `sendJSON(schema = undefined, config = {})` |
| 115 | +Send conversation and force JSON response with optional schema. |
| 116 | + |
| 117 | +### Conversation Management |
| 118 | + |
| 119 | +#### `addTurn(role, text)` |
| 120 | +Add a user or model turn to conversation history. |
| 121 | + |
| 122 | +#### `clearHistory()` |
| 123 | +Clear all conversation history. |
| 124 | + |
| 125 | +#### `truncateHistory(maxParts = 20)` |
| 126 | +Trim history to keep last N parts. |
| 127 | + |
| 128 | +#### `ensureCharBudget(maxChars = 12000)` |
| 129 | +Ensure history stays under character budget (rough proxy for tokens). |
| 130 | + |
| 131 | +### Configuration |
| 132 | + |
| 133 | +#### `setModel(model)` |
| 134 | +Switch to a different Gemini model. |
| 135 | + |
| 136 | +#### `setSystemInstruction(text)` |
| 137 | +Set a persistent system instruction. |
| 138 | + |
| 139 | +## Testing |
| 140 | + |
| 141 | +The library includes comprehensive tests that demonstrate proper usage: |
| 142 | + |
| 143 | +- **Basic Functionality**: API key validation, text generation, JSON responses |
| 144 | +- **Conversation Management**: History management, turn handling, system instructions |
| 145 | +- **Error Handling**: Retry logic, invalid responses, edge cases |
| 146 | +- **Configuration**: Model switching, character budget management |
| 147 | + |
| 148 | +Run tests using the provided test functions: |
| 149 | +- `test_GeminiClient()` - Basic functionality tests |
| 150 | +- `test_GeminiClientChat()` - Conversation management tests |
| 151 | +- `test_GeminiClientChatEdgeCases()` - Edge case and error handling tests |
| 152 | + |
| 153 | +## Error Handling |
| 154 | + |
| 155 | +The client includes robust error handling: |
| 156 | +- Automatic retries with exponential backoff for transient errors |
| 157 | +- Validation of API responses and JSON output |
| 158 | +- Clear error messages for common issues |
| 159 | +- Graceful handling of empty conversation history |
| 160 | + |
| 161 | +## Examples |
| 162 | + |
| 163 | +See the test classes in the source code for comprehensive usage examples covering all features and edge cases. |
| 164 | + |
| 165 | + |
0 commit comments