@adminforth/completion-adapter-google-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.
@@ -0,0 +1,9 @@
1
+ #!/bin/bash
2
+
3
+ npm run build 2>&1 | tee build.log
4
+ build_status=${PIPESTATUS[0]}
5
+
6
+ if [ $build_status -ne 0 ]; then
7
+ echo "Build failed. Exiting with status code $build_status"
8
+ exit $build_status
9
+ fi
@@ -0,0 +1,44 @@
1
+ #!/bin/sh
2
+
3
+ set -x
4
+
5
+ COMMIT_SHORT_SHA=$(echo $CI_COMMIT_SHA | cut -c1-8)
6
+
7
+ STATUS=${1}
8
+
9
+ if [ "$STATUS" = "success" ]; then
10
+ MESSAGE="Did a build without issues on \`$CI_REPO_NAME/$CI_COMMIT_BRANCH\`. Commit: _${CI_COMMIT_MESSAGE}_ (<$CI_COMMIT_URL|$COMMIT_SHORT_SHA>)"
11
+
12
+ curl -s -X POST -H "Content-Type: application/json" -d '{
13
+ "username": "'"$CI_COMMIT_AUTHOR"'",
14
+ "icon_url": "'"$CI_COMMIT_AUTHOR_AVATAR"'",
15
+ "attachments": [
16
+ {
17
+ "mrkdwn_in": ["text", "pretext"],
18
+ "color": "#36a64f",
19
+ "text": "'"$MESSAGE"'"
20
+ }
21
+ ]
22
+ }' "$DEVELOPERS_SLACK_WEBHOOK"
23
+ exit 0
24
+ fi
25
+ export BUILD_LOG=$(cat ./build.log)
26
+
27
+ BUILD_LOG=$(echo $BUILD_LOG | sed 's/"/\\"/g')
28
+
29
+ MESSAGE="Broke \`$CI_REPO_NAME/$CI_COMMIT_BRANCH\` with commit _${CI_COMMIT_MESSAGE}_ (<$CI_COMMIT_URL|$COMMIT_SHORT_SHA>)"
30
+ CODE_BLOCK="\`\`\`$BUILD_LOG\n\`\`\`"
31
+
32
+ echo "Sending slack message to developers $MESSAGE"
33
+ curl -sS -X POST -H "Content-Type: application/json" -d '{
34
+ "username": "'"$CI_COMMIT_AUTHOR"'",
35
+ "icon_url": "'"$CI_COMMIT_AUTHOR_AVATAR"'",
36
+ "attachments": [
37
+ {
38
+ "mrkdwn_in": ["text", "pretext"],
39
+ "color": "#8A1C12",
40
+ "text": "'"$CODE_BLOCK"'",
41
+ "pretext": "'"$MESSAGE"'"
42
+ }
43
+ ]
44
+ }' "$DEVELOPERS_SLACK_WEBHOOK" 2>&1
@@ -0,0 +1,56 @@
1
+ clone:
2
+ git:
3
+ image: woodpeckerci/plugin-git
4
+ settings:
5
+ partial: false
6
+ depth: 5
7
+
8
+ steps:
9
+ init-secrets:
10
+ when:
11
+ - event: push
12
+ image: infisical/cli
13
+ environment:
14
+ INFISICAL_TOKEN:
15
+ from_secret: VAULT_TOKEN
16
+ commands:
17
+ - infisical export --domain https://vault.devforth.io/api --format=dotenv-export --env="prod" > /woodpecker/deploy.vault.env
18
+
19
+ build:
20
+ image: devforth/node20-pnpm:latest
21
+ when:
22
+ - event: push
23
+ commands:
24
+ - . /woodpecker/deploy.vault.env
25
+ - pnpm install
26
+ - /bin/bash ./.woodpecker/buildRelease.sh
27
+ - npm audit signatures
28
+
29
+ release:
30
+ image: devforth/node20-pnpm:latest
31
+ when:
32
+ - event:
33
+ - push
34
+ branch:
35
+ - main
36
+ commands:
37
+ - . /woodpecker/deploy.vault.env
38
+ - pnpm exec semantic-release
39
+
40
+ slack-on-failure:
41
+ image: curlimages/curl
42
+ when:
43
+ - event: push
44
+ status: [failure]
45
+ commands:
46
+ - . /woodpecker/deploy.vault.env
47
+ - /bin/sh ./.woodpecker/buildSlackNotify.sh failure
48
+
49
+ slack-on-success:
50
+ image: curlimages/curl
51
+ when:
52
+ - event: push
53
+ status: [success]
54
+ commands:
55
+ - . /woodpecker/deploy.vault.env
56
+ - /bin/sh ./.woodpecker/buildSlackNotify.sh success
package/Changelog.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [1.0.0] - 2024-12-06
2
+
3
+ ### Added
4
+
5
+ - Added Google Gemini completion adapter.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Devforth.io
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/build.log ADDED
@@ -0,0 +1,4 @@
1
+
2
+ > @adminforth/completion-adapter-google-gemini@2.0.6 build
3
+ > tsc
4
+
package/dist/index.js ADDED
@@ -0,0 +1,113 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { ChatGoogleGenerativeAI } from "@langchain/google-genai";
11
+ import { GoogleGenAI } from "@google/genai";
12
+ import pRetry from 'p-retry';
13
+ import { logger } from "adminforth";
14
+ const GOOGLE_LANGCHAIN_AGENT_OPTION_KEYS = [
15
+ "temperature",
16
+ "topP",
17
+ "topK",
18
+ "stopSequences",
19
+ "safetySettings",
20
+ "apiVersion",
21
+ "baseUrl",
22
+ "customHeaders",
23
+ "streaming",
24
+ "json",
25
+ "streamUsage",
26
+ "convertSystemMessageToHumanContent",
27
+ "thinkingConfig",
28
+ ];
29
+ function getGoogleLangChainAgentOptions(extraRequestBodyParameters) {
30
+ const options = {};
31
+ if (!extraRequestBodyParameters) {
32
+ return options;
33
+ }
34
+ for (const key of GOOGLE_LANGCHAIN_AGENT_OPTION_KEYS) {
35
+ if (key in extraRequestBodyParameters) {
36
+ options[key] = extraRequestBodyParameters[key];
37
+ }
38
+ }
39
+ return options;
40
+ }
41
+ export default class CompletionAdapterGoogleGemini {
42
+ constructor(options) {
43
+ this.complete = (requestOrContent_1, ...args_1) => __awaiter(this, [requestOrContent_1, ...args_1], void 0, function* (requestOrContent, stopOrMaxTokens = 50, maxTokensOrOutputSchema = 50, outputSchema) {
44
+ const request = typeof requestOrContent === "string"
45
+ ? {
46
+ content: requestOrContent,
47
+ maxTokens: typeof stopOrMaxTokens === "number"
48
+ ? stopOrMaxTokens
49
+ : typeof maxTokensOrOutputSchema === "number"
50
+ ? maxTokensOrOutputSchema
51
+ : 50,
52
+ outputSchema: typeof stopOrMaxTokens === "number"
53
+ ? maxTokensOrOutputSchema
54
+ : outputSchema,
55
+ }
56
+ : requestOrContent;
57
+ const { content, maxTokens: requestMaxTokens = 50, outputSchema: requestOutputSchema, } = request;
58
+ const ai = new GoogleGenAI({
59
+ apiKey: this.options.geminiApiKey,
60
+ });
61
+ const tryToGenerate = () => __awaiter(this, void 0, void 0, function* () {
62
+ logger.debug("Making Google Gemini API call");
63
+ try {
64
+ const response = yield ai.models.generateContent({
65
+ model: this.options.model || "gemini-3-flash-preview",
66
+ contents: content,
67
+ config: Object.assign({ responseJsonSchema: requestOutputSchema ? requestOutputSchema : undefined, maxOutputTokens: requestMaxTokens }, this.options.extraRequestBodyParameters),
68
+ });
69
+ logger.debug(`Google Gemini SUCCESSFUL API response: ${response}`);
70
+ return {
71
+ content: response.text,
72
+ };
73
+ }
74
+ catch (error) {
75
+ logger.error(`Error during Google Gemini API call: ${error}`);
76
+ throw new Error(`Error during Google Gemini API call: ${JSON.parse(error.message).error.message}`);
77
+ }
78
+ });
79
+ const result = yield pRetry(tryToGenerate, {
80
+ retries: 5,
81
+ onFailedAttempt: ({ error, attemptNumber, retriesLeft, retriesConsumed }) => {
82
+ logger.debug(`Attempt ${attemptNumber} failed. ${retriesLeft} retries left. ${retriesConsumed} retries consumed.`);
83
+ },
84
+ });
85
+ return result;
86
+ });
87
+ this.options = options;
88
+ }
89
+ validate() {
90
+ if (!this.options.geminiApiKey) {
91
+ throw new Error("geminiApiKey is required");
92
+ }
93
+ }
94
+ measureTokensCount(content) {
95
+ return __awaiter(this, void 0, void 0, function* () {
96
+ // Implement token counting logic here
97
+ const ai = new GoogleGenAI({
98
+ apiKey: this.options.geminiApiKey,
99
+ });
100
+ const countTokensResponse = yield ai.models.countTokens({
101
+ model: "gemini-2.0-flash",
102
+ contents: content,
103
+ });
104
+ return countTokensResponse.totalTokens;
105
+ });
106
+ }
107
+ getLangChainAgentSpec(params) {
108
+ const modelOptions = getGoogleLangChainAgentOptions(this.options.extraRequestBodyParameters);
109
+ return {
110
+ model: new ChatGoogleGenerativeAI(Object.assign({ model: this.options.model || "gemini-3-flash-preview", apiKey: this.options.geminiApiKey, maxOutputTokens: params.maxTokens }, modelOptions)),
111
+ };
112
+ }
113
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/index.ts ADDED
@@ -0,0 +1,162 @@
1
+ import type { AdapterOptions } from "./types.js";
2
+ import type { CompletionAdapter } from "adminforth";
3
+ import { ChatGoogleGenerativeAI } from "@langchain/google-genai";
4
+ import { GoogleGenAI } from "@google/genai";
5
+ import pRetry from 'p-retry';
6
+ import { logger } from "adminforth";
7
+
8
+ type CompletionRequestInput = {
9
+ content: string;
10
+ maxTokens?: number;
11
+ outputSchema?: any;
12
+ };
13
+
14
+ type AgentModelPurpose = "primary" | "summary";
15
+
16
+ const GOOGLE_LANGCHAIN_AGENT_OPTION_KEYS = [
17
+ "temperature",
18
+ "topP",
19
+ "topK",
20
+ "stopSequences",
21
+ "safetySettings",
22
+ "apiVersion",
23
+ "baseUrl",
24
+ "customHeaders",
25
+ "streaming",
26
+ "json",
27
+ "streamUsage",
28
+ "convertSystemMessageToHumanContent",
29
+ "thinkingConfig",
30
+ ] as const;
31
+
32
+ function getGoogleLangChainAgentOptions(
33
+ extraRequestBodyParameters?: Record<string, unknown>,
34
+ ) {
35
+ const options: Record<string, unknown> = {};
36
+
37
+ if (!extraRequestBodyParameters) {
38
+ return options;
39
+ }
40
+
41
+ for (const key of GOOGLE_LANGCHAIN_AGENT_OPTION_KEYS) {
42
+ if (key in extraRequestBodyParameters) {
43
+ options[key] = extraRequestBodyParameters[key];
44
+ }
45
+ }
46
+
47
+ return options;
48
+ }
49
+
50
+ export default class CompletionAdapterGoogleGemini
51
+ implements CompletionAdapter
52
+ {
53
+ options: AdapterOptions;
54
+
55
+ constructor(options: AdapterOptions) {
56
+ this.options = options;
57
+ }
58
+
59
+ validate() {
60
+ if (!this.options.geminiApiKey) {
61
+ throw new Error("geminiApiKey is required");
62
+ }
63
+ }
64
+
65
+ async measureTokensCount(content: string): Promise<number> {
66
+ // Implement token counting logic here
67
+ const ai = new GoogleGenAI({
68
+ apiKey: this.options.geminiApiKey,
69
+ });
70
+ const countTokensResponse = await ai.models.countTokens({
71
+ model: "gemini-2.0-flash",
72
+ contents: content,
73
+ });
74
+
75
+ return countTokensResponse.totalTokens;
76
+ }
77
+
78
+ getLangChainAgentSpec(params: {
79
+ maxTokens: number;
80
+ purpose: AgentModelPurpose;
81
+ }) {
82
+ const modelOptions = getGoogleLangChainAgentOptions(
83
+ this.options.extraRequestBodyParameters,
84
+ );
85
+
86
+ return {
87
+ model: new ChatGoogleGenerativeAI({
88
+ model: this.options.model || "gemini-3-flash-preview",
89
+ apiKey: this.options.geminiApiKey,
90
+ maxOutputTokens: params.maxTokens,
91
+ ...modelOptions,
92
+ } as any),
93
+ };
94
+ }
95
+
96
+
97
+ complete = async (
98
+ requestOrContent: CompletionRequestInput | string,
99
+ stopOrMaxTokens: string[] | number = 50,
100
+ maxTokensOrOutputSchema: number | any = 50,
101
+ outputSchema?: any,
102
+ ): Promise<{
103
+ content?: string;
104
+ finishReason?: string;
105
+ error?: string;
106
+ }> => {
107
+ const request =
108
+ typeof requestOrContent === "string"
109
+ ? {
110
+ content: requestOrContent,
111
+ maxTokens:
112
+ typeof stopOrMaxTokens === "number"
113
+ ? stopOrMaxTokens
114
+ : typeof maxTokensOrOutputSchema === "number"
115
+ ? maxTokensOrOutputSchema
116
+ : 50,
117
+ outputSchema:
118
+ typeof stopOrMaxTokens === "number"
119
+ ? maxTokensOrOutputSchema
120
+ : outputSchema,
121
+ }
122
+ : requestOrContent;
123
+ const {
124
+ content,
125
+ maxTokens: requestMaxTokens = 50,
126
+ outputSchema: requestOutputSchema,
127
+ } = request;
128
+
129
+ const ai = new GoogleGenAI({
130
+ apiKey: this.options.geminiApiKey,
131
+ });
132
+
133
+ const tryToGenerate = async () => {
134
+ logger.debug("Making Google Gemini API call");
135
+ try {
136
+ const response = await ai.models.generateContent({
137
+ model: this.options.model || "gemini-3-flash-preview",
138
+ contents: content,
139
+ config: {
140
+ responseJsonSchema: requestOutputSchema ? requestOutputSchema : undefined,
141
+ maxOutputTokens: requestMaxTokens,
142
+ ...this.options.extraRequestBodyParameters,
143
+ },
144
+ });
145
+ logger.debug(`Google Gemini SUCCESSFUL API response: ${response}`);
146
+ return {
147
+ content: response.text,
148
+ };
149
+ } catch (error) {
150
+ logger.error(`Error during Google Gemini API call: ${error}`);
151
+ throw new Error(`Error during Google Gemini API call: ${JSON.parse(error.message).error.message}`);
152
+ }
153
+ }
154
+ const result = await pRetry(tryToGenerate, {
155
+ retries: 5,
156
+ onFailedAttempt: ({error, attemptNumber, retriesLeft, retriesConsumed}) => {
157
+ logger.debug(`Attempt ${attemptNumber} failed. ${retriesLeft} retries left. ${retriesConsumed} retries consumed.`);
158
+ },
159
+ })
160
+ return result;
161
+ };
162
+ }
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@adminforth/completion-adapter-google-gemini",
3
+ "version": "1.0.0",
4
+ "main": "dist/index.js",
5
+ "types": "dist/index.d.ts",
6
+ "type": "module",
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "scripts": {
11
+ "build": "tsc"
12
+ },
13
+ "keywords": [],
14
+ "author": "DevForth (https://devforth.io)",
15
+ "license": "MIT",
16
+ "description": "",
17
+ "dependencies": {
18
+ "@google/genai": "^1.35.0",
19
+ "@langchain/google-genai": "2.1.27",
20
+ "p-retry": "^7.1.1"
21
+ },
22
+ "peerDependencies": {
23
+ "adminforth": "^2.24.0"
24
+ },
25
+ "release": {
26
+ "plugins": [
27
+ "@semantic-release/commit-analyzer",
28
+ "@semantic-release/release-notes-generator",
29
+ "@semantic-release/npm",
30
+ "@semantic-release/github",
31
+ [
32
+ "semantic-release-slack-bot",
33
+ {
34
+ "packageName": "@adminforth/completion-adapter-google-gemini",
35
+ "notifyOnSuccess": true,
36
+ "notifyOnFail": true,
37
+ "slackIcon": ":package:",
38
+ "markdownReleaseNotes": true
39
+ }
40
+ ]
41
+ ],
42
+ "branches": [
43
+ "main",
44
+ {
45
+ "name": "next",
46
+ "prerelease": true
47
+ }
48
+ ]
49
+ },
50
+ "devDependencies": {
51
+ "typescript": "^5.9.3",
52
+ "semantic-release": "^24.2.1",
53
+ "semantic-release-slack-bot": "^4.0.2"
54
+ }
55
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,12 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include*/
4
+ "module": "node16", /* Specify what module code is generated. */
5
+ "outDir": "./dist", /* Specify an output folder for all emitted files. */
6
+ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. */
7
+ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
8
+ "strict": false, /* Enable all strict type-checking options. */
9
+ "skipLibCheck": true, /* Skip type checking all .d.ts files. */
10
+ },
11
+ "exclude": ["node_modules", "dist", "custom"], /* Exclude files from compilation. */
12
+ }
package/types.ts ADDED
@@ -0,0 +1,19 @@
1
+ export interface AdapterOptions {
2
+ /**
3
+ * Google API key. Go to https://aistudio.google.com/api-keys, go to Dashboard -> API keys -> Create new secret key
4
+ * Set geminiApiKey: process.env.GEMINI_API_KEY to access it
5
+ */
6
+ geminiApiKey: string;
7
+
8
+ /**
9
+ * Model name. Go to https://ai.google.dev/gemini-api/docs/models, select model and copy name.
10
+ * Default is `gemini-3-flash-preview`. Use e.g. more expensive `gemini-3-pro-preview` for more powerful model.
11
+ */
12
+ model?: string;
13
+
14
+
15
+ /**
16
+ * Additional request body parameters to include in the API request.
17
+ */
18
+ extraRequestBodyParameters?: Record<string, unknown>;
19
+ }