ak-gemini 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +212 -0
- package/index.cjs +41668 -0
- package/index.js +451 -0
- package/logger.js +16 -0
- package/package.json +62 -0
- package/types.ts +65 -0
package/README.md
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
# AK-Gemini
|
|
2
|
+
|
|
3
|
+
**Generic, type-safe, and highly configurable wrapper for Google's Gemini AI JSON transformation.**
|
|
4
|
+
Use this to power LLM-driven data pipelines, JSON mapping, or any automated AI transformation step, locally or in cloud functions.
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Features
|
|
9
|
+
|
|
10
|
+
* **Model-Agnostic**: Configure for any Gemini model (`gemini-2.0-flash` by default)
|
|
11
|
+
* **Declarative Examples**: Seed transformations using example mappings, with support for custom keys (`PROMPT`, `ANSWER`, `CONTEXT`, or your own)
|
|
12
|
+
* **Automatic Validation & Repair**: Validate outputs with your own async function; auto-repair failed payloads with LLM feedback loop (exponential backoff, fully configurable)
|
|
13
|
+
* **Strong TypeScript/JSDoc Typings**: All public APIs fully typed (see `/types`)
|
|
14
|
+
* **Minimal API Surface**: Dead simple, no ceremony—init, seed, transform, validate.
|
|
15
|
+
* **Robust Logging**: Pluggable logger for all steps, easy debugging
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
npm install ak-gemini
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Requires Node.js 18+, and [@google/genai](https://www.npmjs.com/package/@google/genai).
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## Usage
|
|
30
|
+
|
|
31
|
+
### 1. **Setup**
|
|
32
|
+
|
|
33
|
+
Set your `GEMINI_API_KEY` environment variable:
|
|
34
|
+
|
|
35
|
+
```sh
|
|
36
|
+
export GEMINI_API_KEY=sk-your-gemini-api-key
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
or pass it directly in the constructor options.
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
### 2. **Basic Example**
|
|
44
|
+
|
|
45
|
+
```js
|
|
46
|
+
import AITransformer from 'ai-transformer';
|
|
47
|
+
|
|
48
|
+
const transformer = new AITransformer({
|
|
49
|
+
modelName: 'gemini-2.0-flash', // or your preferred Gemini model
|
|
50
|
+
sourceKey: 'INPUT', // Custom prompt key (default: 'PROMPT')
|
|
51
|
+
targetKey: 'OUTPUT', // Custom answer key (default: 'ANSWER')
|
|
52
|
+
contextKey: 'CONTEXT', // Optional, for per-example context
|
|
53
|
+
maxRetries: 2, // Optional, for validation-repair loops
|
|
54
|
+
// responseSchema: { ... }, // Optional, strict output typing
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
const examples = [
|
|
58
|
+
{
|
|
59
|
+
CONTEXT: "Generate professional profiles with emoji representations",
|
|
60
|
+
INPUT: { "name": "Alice" },
|
|
61
|
+
OUTPUT: { "name": "Alice", "profession": "data scientist", "life_as_told_by_emoji": ["🔬", "💡", "📊", "🧠", "🌟"] }
|
|
62
|
+
}
|
|
63
|
+
];
|
|
64
|
+
|
|
65
|
+
await transformer.init();
|
|
66
|
+
await transformer.seed(examples);
|
|
67
|
+
|
|
68
|
+
const result = await transformer.message({ name: "Bob" });
|
|
69
|
+
console.log(result);
|
|
70
|
+
// → { name: "Bob", profession: "...", life_as_told_by_emoji: [ ... ] }
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
---
|
|
74
|
+
|
|
75
|
+
### 3. **Automatic Validation & Self-Healing**
|
|
76
|
+
|
|
77
|
+
You can pass a custom async validator—if it fails, the transformer will attempt to self-correct using LLM feedback, retrying up to `maxRetries` times:
|
|
78
|
+
|
|
79
|
+
```js
|
|
80
|
+
const validator = async (payload) => {
|
|
81
|
+
if (!payload.profession || !Array.isArray(payload.life_as_told_by_emoji)) {
|
|
82
|
+
throw new Error('Invalid profile format');
|
|
83
|
+
}
|
|
84
|
+
return payload;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const validPayload = await transformer.transformWithValidation({ name: "Lynn" }, validator);
|
|
88
|
+
console.log(validPayload);
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
---
|
|
92
|
+
|
|
93
|
+
## API
|
|
94
|
+
|
|
95
|
+
### Constructor
|
|
96
|
+
|
|
97
|
+
```js
|
|
98
|
+
new AITransformer(options)
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
| Option | Type | Default | Description |
|
|
102
|
+
| ------------------ | ------ | ------------------ | ------------------------------------------------- |
|
|
103
|
+
| modelName | string | 'gemini-2.0-flash' | Gemini model to use |
|
|
104
|
+
| sourceKey | string | 'PROMPT' | Key for prompt/example input |
|
|
105
|
+
| targetKey | string | 'ANSWER' | Key for expected output in examples |
|
|
106
|
+
| contextKey | string | 'CONTEXT' | Key for per-example context (optional) |
|
|
107
|
+
| examplesFile | string | null | Path to JSON file containing examples |
|
|
108
|
+
| exampleData | array | null | Inline array of example objects |
|
|
109
|
+
| responseSchema | object | null | Optional JSON schema for strict output validation |
|
|
110
|
+
| maxRetries | number | 3 | Retries for validation+rebuild loop |
|
|
111
|
+
| retryDelay | number | 1000 | Initial retry delay in ms (exponential backoff) |
|
|
112
|
+
| chatConfig | object | ... | Gemini chat config overrides |
|
|
113
|
+
| systemInstructions | string | ... | System prompt for Gemini |
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
### Methods
|
|
118
|
+
|
|
119
|
+
#### `await transformer.init()`
|
|
120
|
+
|
|
121
|
+
Initializes Gemini chat session (idempotent).
|
|
122
|
+
|
|
123
|
+
#### `await transformer.seed(examples?)`
|
|
124
|
+
|
|
125
|
+
Seeds the model with example transformations (uses keys from constructor).
|
|
126
|
+
You can omit `examples` to use the `examplesFile` (if provided).
|
|
127
|
+
|
|
128
|
+
#### `await transformer.message(sourcePayload)`
|
|
129
|
+
|
|
130
|
+
Transforms input JSON to output JSON using the seeded examples and system instructions.
|
|
131
|
+
|
|
132
|
+
#### `await transformer.transformWithValidation(sourcePayload, validatorFn, options?)`
|
|
133
|
+
|
|
134
|
+
Runs transformation, validates with your async validator, and (optionally) repairs payload using LLM until valid or retries are exhausted.
|
|
135
|
+
Throws if all attempts fail.
|
|
136
|
+
|
|
137
|
+
#### `await transformer.rebuild(lastPayload, errorMessage)`
|
|
138
|
+
|
|
139
|
+
Given a failed payload and error message, uses LLM to generate a corrected payload.
|
|
140
|
+
|
|
141
|
+
#### `await transformer.reset()`
|
|
142
|
+
|
|
143
|
+
Resets the Gemini chat session, clearing all history/examples.
|
|
144
|
+
|
|
145
|
+
#### `transformer.getHistory()`
|
|
146
|
+
|
|
147
|
+
Returns the current chat history (for debugging).
|
|
148
|
+
|
|
149
|
+
---
|
|
150
|
+
|
|
151
|
+
## Examples
|
|
152
|
+
|
|
153
|
+
### Seed with Custom Example Keys
|
|
154
|
+
|
|
155
|
+
```js
|
|
156
|
+
const transformer = new AITransformer({
|
|
157
|
+
sourceKey: 'INPUT',
|
|
158
|
+
targetKey: 'OUTPUT',
|
|
159
|
+
contextKey: 'CTX'
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
await transformer.init();
|
|
163
|
+
await transformer.seed([
|
|
164
|
+
{
|
|
165
|
+
CTX: "You are a dog expert.",
|
|
166
|
+
INPUT: { breed: "golden retriever" },
|
|
167
|
+
OUTPUT: { breed: "golden retriever", size: "large", friendly: true }
|
|
168
|
+
}
|
|
169
|
+
]);
|
|
170
|
+
|
|
171
|
+
const dog = await transformer.message({ breed: "chihuahua" });
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
---
|
|
175
|
+
|
|
176
|
+
### Use With Validation and Retry
|
|
177
|
+
|
|
178
|
+
```js
|
|
179
|
+
const result = await transformer.transformWithValidation(
|
|
180
|
+
{ name: "Bob" },
|
|
181
|
+
async (output) => {
|
|
182
|
+
if (!output.name || !output.profession) throw new Error("Missing fields");
|
|
183
|
+
return output;
|
|
184
|
+
}
|
|
185
|
+
);
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
---
|
|
189
|
+
|
|
190
|
+
## Testing
|
|
191
|
+
|
|
192
|
+
* **Jest test suite included**
|
|
193
|
+
* Mocks Google Gemini, logger, ak-tools
|
|
194
|
+
* 100% coverage for all error cases, configuration options, edge cases
|
|
195
|
+
|
|
196
|
+
Run tests with:
|
|
197
|
+
|
|
198
|
+
```sh
|
|
199
|
+
npm test
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
---
|
|
203
|
+
|
|
204
|
+
## Error Handling
|
|
205
|
+
|
|
206
|
+
* Throws on missing `GEMINI_API_KEY`
|
|
207
|
+
* All API and parsing errors surfaced as `Error` with context
|
|
208
|
+
* Validator and retry failures include the number of attempts and last error
|
|
209
|
+
|
|
210
|
+
---
|
|
211
|
+
|
|
212
|
+
|