koishi-plugin-chatluna-google-gemini-adapter 1.0.0-beta.9 → 1.0.0-rc.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/package.json CHANGED
@@ -1,13 +1,23 @@
1
1
  {
2
2
  "name": "koishi-plugin-chatluna-google-gemini-adapter",
3
3
  "description": "google-gemini adapter for chatluna",
4
- "version": "1.0.0-beta.9",
5
- "main": "lib/index.js",
4
+ "version": "1.0.0-rc.0",
5
+ "main": "lib/index.cjs",
6
+ "module": "lib/index.mjs",
6
7
  "typings": "lib/index.d.ts",
7
8
  "files": [
8
9
  "lib",
9
10
  "dist"
10
11
  ],
12
+ "exports": {
13
+ ".": {
14
+ "types": "./lib/index.d.ts",
15
+ "import": "./lib/index.mjs",
16
+ "require": "./lib/index.cjs"
17
+ },
18
+ "./package.json": "./package.json"
19
+ },
20
+ "type": "module",
11
21
  "author": "dingyi222666 <dingyi222666@foxmail.com>",
12
22
  "repository": {
13
23
  "type": "git",
@@ -22,6 +32,20 @@
22
32
  "scripts": {
23
33
  "build": "atsc -b"
24
34
  },
35
+ "resolutions": {
36
+ "@langchain/core": "0.3.18",
37
+ "js-tiktoken": "npm:@dingyi222666/js-tiktoken@^1.0.15"
38
+ },
39
+ "overrides": {
40
+ "@langchain/core": "0.3.18",
41
+ "js-tiktoken": "npm:@dingyi222666/js-tiktoken@^1.0.15"
42
+ },
43
+ "pnpm": {
44
+ "overrides": {
45
+ "@langchain/core": "0.3.18",
46
+ "js-tiktoken": "npm:@dingyi222666/js-tiktoken@^1.0.15"
47
+ }
48
+ },
25
49
  "engines": {
26
50
  "node": ">=18.0.0"
27
51
  },
@@ -38,22 +62,23 @@
38
62
  "adapter"
39
63
  ],
40
64
  "dependencies": {
41
- "@langchain/core": "^0.1.38",
42
- "@streamparser/json": "^0.0.20",
43
- "zod": "^3.23.0-canary.20240222T232722",
44
- "zod-to-json-schema": "^3.22.4"
65
+ "@langchain/core": "^0.3.18",
66
+ "@streamparser/json": "^0.0.21",
67
+ "zod": "^3.24.0-canary.20241107T043915",
68
+ "zod-to-json-schema": "^3.23.5"
45
69
  },
46
70
  "devDependencies": {
47
- "atsc": "^2.0.1",
48
- "koishi": "^4.17.1"
71
+ "atsc": "^2.1.0",
72
+ "koishi": "^4.18.1"
49
73
  },
50
74
  "peerDependencies": {
51
- "koishi": "^4.16.0",
52
- "koishi-plugin-chatluna": "^1.0.0-beta.41"
75
+ "koishi": "^4.18.1",
76
+ "koishi-plugin-chatluna": "^1.0.0-rc.0"
53
77
  },
54
78
  "koishi": {
55
79
  "description": {
56
- "zh": "ChatLuna 的 Google gemini 平台适配器"
80
+ "zh": "ChatLuna 的 Google Gemini 适配器",
81
+ "en": "Google Gemini adapter for ChatLuna"
57
82
  },
58
83
  "service": {
59
84
  "required": [
package/lib/client.d.ts DELETED
@@ -1,17 +0,0 @@
1
- import { PlatformModelAndEmbeddingsClient } from 'koishi-plugin-chatluna/lib/llm-core/platform/client';
2
- import { ClientConfig } from 'koishi-plugin-chatluna/lib/llm-core/platform/config';
3
- import { ChatHubBaseEmbeddings, ChatLunaChatModel } from 'koishi-plugin-chatluna/lib/llm-core/platform/model';
4
- import { ModelInfo } from 'koishi-plugin-chatluna/lib/llm-core/platform/types';
5
- import { Context } from 'koishi';
6
- import { Config } from '.';
7
- export declare class GeminiClient extends PlatformModelAndEmbeddingsClient {
8
- private _config;
9
- platform: string;
10
- private _requester;
11
- private _models;
12
- constructor(ctx: Context, _config: Config, clientConfig: ClientConfig);
13
- init(): Promise<void>;
14
- refreshModels(): Promise<ModelInfo[]>;
15
- getModels(): Promise<ModelInfo[]>;
16
- protected _createModel(model: string): ChatLunaChatModel | ChatHubBaseEmbeddings;
17
- }
package/lib/client.js DELETED
@@ -1,79 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.GeminiClient = void 0;
4
- const client_1 = require("koishi-plugin-chatluna/lib/llm-core/platform/client");
5
- const model_1 = require("koishi-plugin-chatluna/lib/llm-core/platform/model");
6
- const types_1 = require("koishi-plugin-chatluna/lib/llm-core/platform/types");
7
- const error_1 = require("koishi-plugin-chatluna/lib/utils/error");
8
- const requester_1 = require("./requester");
9
- class GeminiClient extends client_1.PlatformModelAndEmbeddingsClient {
10
- _config;
11
- platform = 'gemini';
12
- _requester;
13
- _models;
14
- constructor(ctx, _config, clientConfig) {
15
- super(ctx, clientConfig);
16
- this._config = _config;
17
- this._requester = new requester_1.GeminiRequester(clientConfig);
18
- }
19
- async init() {
20
- await this.getModels();
21
- }
22
- async refreshModels() {
23
- try {
24
- const rawModels = await this._requester.getModels();
25
- if (!rawModels.length) {
26
- throw new error_1.ChatLunaError(error_1.ChatLunaErrorCode.MODEL_INIT_ERROR, new Error('No model found'));
27
- }
28
- return rawModels
29
- .map((model) => model.replace('models/', ''))
30
- .map((model) => {
31
- return {
32
- name: model,
33
- maxTokens: model.includes('vision') ? 12288 : 30720,
34
- type: model.includes('embedding')
35
- ? types_1.ModelType.embeddings
36
- : types_1.ModelType.llm,
37
- functionCall: !model.includes('vision'),
38
- supportMode: ['all']
39
- };
40
- });
41
- }
42
- catch (e) {
43
- throw new error_1.ChatLunaError(error_1.ChatLunaErrorCode.MODEL_INIT_ERROR, e);
44
- }
45
- }
46
- async getModels() {
47
- if (this._models) {
48
- return Object.values(this._models);
49
- }
50
- const models = await this.refreshModels();
51
- this._models = {};
52
- for (const model of models) {
53
- this._models[model.name] = model;
54
- }
55
- }
56
- _createModel(model) {
57
- const info = this._models[model];
58
- if (info == null) {
59
- throw new error_1.ChatLunaError(error_1.ChatLunaErrorCode.MODEL_NOT_FOUND);
60
- }
61
- if (info.type === types_1.ModelType.llm) {
62
- return new model_1.ChatLunaChatModel({
63
- modelInfo: info,
64
- requester: this._requester,
65
- model,
66
- maxTokens: this._config.maxTokens,
67
- timeout: this._config.timeout,
68
- temperature: this._config.temperature,
69
- maxRetries: this._config.maxRetries,
70
- llmType: 'gemini'
71
- });
72
- }
73
- return new model_1.ChatLunaEmbeddings({
74
- client: this._requester,
75
- maxRetries: this._config.maxRetries
76
- });
77
- }
78
- }
79
- exports.GeminiClient = GeminiClient;
package/lib/index.js DELETED
@@ -1,63 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.name = exports.inject = exports.Config = exports.apply = exports.logger = void 0;
4
- const chat_1 = require("koishi-plugin-chatluna/lib/services/chat");
5
- const koishi_1 = require("koishi");
6
- const client_1 = require("./client");
7
- const logger_1 = require("koishi-plugin-chatluna/lib/utils/logger");
8
- function apply(ctx, config) {
9
- const plugin = new chat_1.ChatLunaPlugin(ctx, config, 'gemini');
10
- exports.logger = (0, logger_1.createLogger)(ctx, 'chatluna-gemini-adapter');
11
- ctx.on('ready', async () => {
12
- await plugin.registerToService();
13
- await plugin.parseConfig((config) => {
14
- return config.apiKeys.map(([apiKey, apiEndpoint]) => {
15
- return {
16
- apiKey,
17
- apiEndpoint,
18
- platform: 'gemini',
19
- chatLimit: config.chatTimeLimit,
20
- timeout: config.timeout,
21
- maxRetries: config.maxRetries,
22
- concurrentMaxSize: config.chatConcurrentMaxSize
23
- };
24
- });
25
- });
26
- await plugin.registerClient((_, clientConfig) => new client_1.GeminiClient(ctx, config, clientConfig));
27
- await plugin.initClients();
28
- });
29
- }
30
- exports.apply = apply;
31
- exports.Config = koishi_1.Schema.intersect([
32
- chat_1.ChatLunaPlugin.Config,
33
- koishi_1.Schema.object({
34
- apiKeys: koishi_1.Schema.array(koishi_1.Schema.tuple([
35
- koishi_1.Schema.string()
36
- .role('secret')
37
- .description('Gemini 的 API Key')
38
- .required(),
39
- koishi_1.Schema.string()
40
- .description('请求 Gemini API 的地址')
41
- .default('https://generativelanguage.googleapis.com/v1beta')
42
- ]))
43
- .description('Gemini 的 API Key 和请求地址列表')
44
- .default([['', 'https://generativelanguage.googleapis.com/v1beta']])
45
- }).description('请求设置'),
46
- koishi_1.Schema.object({
47
- maxTokens: koishi_1.Schema.number()
48
- .description('回复的最大 Token 数(16~32800,必须是16的倍数)(注意如果你目前使用的模型的最大 Token 为 8000 及以上的话才建议设置超过 512 token)')
49
- .min(16)
50
- .max(128000)
51
- .step(16)
52
- .default(1024),
53
- temperature: koishi_1.Schema.percent()
54
- .description('回复温度,越高越随机')
55
- .min(0)
56
- .max(1)
57
- .step(0.1)
58
- .default(0.8)
59
- }).description('模型设置')
60
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
61
- ]);
62
- exports.inject = ['chatluna'];
63
- exports.name = 'chatluna-google-gemini-adapter';
@@ -1,16 +0,0 @@
1
- import { EmbeddingsRequester, EmbeddingsRequestParams, ModelRequester, ModelRequestParams } from 'koishi-plugin-chatluna/lib/llm-core/platform/api';
2
- import { ClientConfig } from 'koishi-plugin-chatluna/lib/llm-core/platform/config';
3
- import { ChatGenerationChunk } from '@langchain/core/outputs';
4
- export declare class GeminiRequester extends ModelRequester implements EmbeddingsRequester {
5
- private _config;
6
- constructor(_config: ClientConfig);
7
- completionStream(params: ModelRequestParams): AsyncGenerator<ChatGenerationChunk>;
8
- embeddings(params: EmbeddingsRequestParams): Promise<number[] | number[][]>;
9
- getModels(): Promise<string[]>;
10
- private _post;
11
- private _get;
12
- private _concatUrl;
13
- private _buildHeaders;
14
- init(): Promise<void>;
15
- dispose(): Promise<void>;
16
- }
package/lib/requester.js DELETED
@@ -1,259 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.GeminiRequester = void 0;
4
- const api_1 = require("koishi-plugin-chatluna/lib/llm-core/platform/api");
5
- const messages_1 = require("@langchain/core/messages");
6
- const outputs_1 = require("@langchain/core/outputs");
7
- const error_1 = require("koishi-plugin-chatluna/lib/utils/error");
8
- const sse_1 = require("koishi-plugin-chatluna/lib/utils/sse");
9
- const utils_1 = require("./utils");
10
- const request_1 = require("koishi-plugin-chatluna/lib/utils/request");
11
- const _1 = require(".");
12
- const json_1 = require("@streamparser/json");
13
- const stream_1 = require("koishi-plugin-chatluna/lib/utils/stream");
14
- class GeminiRequester extends api_1.ModelRequester {
15
- _config;
16
- constructor(_config) {
17
- super();
18
- this._config = _config;
19
- }
20
- async *completionStream(params) {
21
- try {
22
- const response = await this._post(`models/${params.model}:streamGenerateContent`, {
23
- contents: await (0, utils_1.langchainMessageToGeminiMessage)(params.input, params.model),
24
- safetySettings: [
25
- {
26
- category: 'HARM_CATEGORY_HARASSMENT',
27
- threshold: 'BLOCK_NONE'
28
- },
29
- {
30
- category: 'HARM_CATEGORY_HATE_SPEECH',
31
- threshold: 'BLOCK_NONE'
32
- },
33
- {
34
- category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
35
- threshold: 'BLOCK_NONE'
36
- },
37
- {
38
- category: 'HARM_CATEGORY_DANGEROUS_CONTENT',
39
- threshold: 'BLOCK_NONE'
40
- }
41
- ],
42
- generationConfig: {
43
- stopSequences: params.stop,
44
- temperature: params.temperature,
45
- maxOutputTokens: params.model.includes('vision')
46
- ? undefined
47
- : params.maxTokens,
48
- topP: params.topP
49
- },
50
- tools: !params.model.includes('vision') && params.tools != null
51
- ? {
52
- functionDeclarations: (0, utils_1.formatToolsToGeminiAITools)(params.tools)
53
- }
54
- : undefined
55
- }, {
56
- signal: params.signal
57
- });
58
- let errorCount = 0;
59
- const stream = new TransformStream();
60
- const iterable = (0, stream_1.readableStreamToAsyncIterable)(stream.readable);
61
- const jsonParser = new json_1.JSONParser();
62
- const writable = stream.writable.getWriter();
63
- jsonParser.onEnd = async () => {
64
- await writable.close();
65
- };
66
- jsonParser.onValue = async ({ value }) => {
67
- const transformValue = value;
68
- if (transformValue.candidates && transformValue.candidates[0]) {
69
- const parts = transformValue.candidates[0].content.parts;
70
- if (parts.length < 1) {
71
- throw new Error(JSON.stringify(value));
72
- }
73
- for (const part of parts) {
74
- await writable.write(part);
75
- }
76
- }
77
- };
78
- await (0, sse_1.sse)(response, async (rawData) => {
79
- jsonParser.write(rawData);
80
- return true;
81
- }, 10);
82
- let content = '';
83
- let isVisionModel = params.model.includes('vision');
84
- const functionCall = {
85
- name: '',
86
- args: '',
87
- arguments: ''
88
- };
89
- for await (const chunk of iterable) {
90
- const messagePart = (0, utils_1.partAsType)(chunk);
91
- const chatFunctionCallingPart = (0, utils_1.partAsType)(chunk);
92
- if (messagePart.text) {
93
- content += messagePart.text;
94
- // match /w*model:
95
- if (isVisionModel && /\s*model:\s*/.test(content)) {
96
- isVisionModel = false;
97
- content = content.replace(/\s*model:\s*/, '');
98
- }
99
- }
100
- if (chatFunctionCallingPart.functionCall) {
101
- const deltaFunctionCall = chatFunctionCallingPart.functionCall;
102
- if (deltaFunctionCall) {
103
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
104
- let args = deltaFunctionCall.args?.input ??
105
- deltaFunctionCall.args;
106
- try {
107
- let parsedArgs = JSON.parse(args);
108
- if (typeof parsedArgs !== 'string') {
109
- args = parsedArgs;
110
- }
111
- parsedArgs = JSON.parse(args);
112
- if (typeof parsedArgs !== 'string') {
113
- args = parsedArgs;
114
- }
115
- }
116
- catch (e) { }
117
- functionCall.args = JSON.stringify(args);
118
- functionCall.name =
119
- functionCall.name + (deltaFunctionCall.name ?? '');
120
- functionCall.arguments = deltaFunctionCall.args;
121
- }
122
- }
123
- try {
124
- const messageChunk = new messages_1.AIMessageChunk(content);
125
- messageChunk.additional_kwargs = {
126
- function_call: functionCall.name.length > 0
127
- ? {
128
- name: functionCall.name,
129
- arguments: functionCall.args,
130
- args: functionCall.arguments
131
- }
132
- : undefined
133
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
134
- };
135
- messageChunk.content = content;
136
- const generationChunk = new outputs_1.ChatGenerationChunk({
137
- message: messageChunk,
138
- text: messageChunk.content
139
- });
140
- yield generationChunk;
141
- content = messageChunk.content;
142
- }
143
- catch (e) {
144
- if (errorCount > 5) {
145
- _1.logger.error('error with chunk', chunk);
146
- throw new error_1.ChatLunaError(error_1.ChatLunaErrorCode.API_REQUEST_FAILED, e);
147
- }
148
- else {
149
- errorCount++;
150
- continue;
151
- }
152
- }
153
- }
154
- }
155
- catch (e) {
156
- if (e instanceof error_1.ChatLunaError) {
157
- throw e;
158
- }
159
- else {
160
- throw new error_1.ChatLunaError(error_1.ChatLunaErrorCode.API_REQUEST_FAILED, e);
161
- }
162
- }
163
- }
164
- async embeddings(params) {
165
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
166
- let data;
167
- try {
168
- const response = await this._post(`models/${params.model}:embedContent`, {
169
- model: `models/${params.model}`,
170
- content: {
171
- parts: [
172
- {
173
- text: params.input
174
- }
175
- ]
176
- }
177
- });
178
- data = await response.text();
179
- data = JSON.parse(data);
180
- if (data.embedding && data.embedding.values?.length > 0) {
181
- return data.embedding.values;
182
- }
183
- throw new Error('error when calling gemini embeddings, Result: ' +
184
- JSON.stringify(data));
185
- }
186
- catch (e) {
187
- const error = new Error('error when calling gemini embeddings, Result: ' +
188
- JSON.stringify(data));
189
- error.stack = e.stack;
190
- error.cause = e.cause;
191
- _1.logger.debug(e);
192
- throw new error_1.ChatLunaError(error_1.ChatLunaErrorCode.API_REQUEST_FAILED, error);
193
- }
194
- }
195
- async getModels() {
196
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
197
- let data;
198
- try {
199
- const response = await this._get('models');
200
- data = await response.text();
201
- data = JSON.parse(data);
202
- if (!data.models || !data.models.length) {
203
- throw new Error('error when listing gemini models, Result:' +
204
- JSON.stringify(data));
205
- }
206
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
207
- return data.models
208
- .map((model) => model.name)
209
- .filter((model) => model.includes('gemini') || model.includes('embedding'));
210
- }
211
- catch (e) {
212
- const error = new Error('error when listing gemini models, Result: ' +
213
- JSON.stringify(data));
214
- error.stack = e.stack;
215
- error.cause = e.cause;
216
- throw error;
217
- }
218
- }
219
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
220
- _post(url, data, params = {}) {
221
- const requestUrl = this._concatUrl(url);
222
- for (const key in data) {
223
- if (data[key] === undefined) {
224
- delete data[key];
225
- }
226
- }
227
- const body = JSON.stringify(data);
228
- return (0, request_1.chatLunaFetch)(requestUrl, {
229
- body,
230
- headers: this._buildHeaders(),
231
- method: 'POST',
232
- ...params
233
- });
234
- }
235
- _get(url) {
236
- const requestUrl = this._concatUrl(url);
237
- return (0, request_1.chatLunaFetch)(requestUrl, {
238
- method: 'GET',
239
- headers: this._buildHeaders()
240
- });
241
- }
242
- _concatUrl(url) {
243
- const apiEndPoint = this._config.apiEndpoint;
244
- // match the apiEndPoint ends with '/v1' or '/v1/' using regex
245
- if (apiEndPoint.endsWith('/')) {
246
- return apiEndPoint + url + `?key=${this._config.apiKey}`;
247
- }
248
- return apiEndPoint + '/' + url + `?key=${this._config.apiKey}`;
249
- }
250
- _buildHeaders() {
251
- return {
252
- /* Authorization: `Bearer ${this._config.apiKey}`, */
253
- 'Content-Type': 'application/json'
254
- };
255
- }
256
- async init() { }
257
- async dispose() { }
258
- }
259
- exports.GeminiRequester = GeminiRequester;
package/lib/types.d.ts DELETED
@@ -1,60 +0,0 @@
1
- export interface ChatCompletionResponseMessage {
2
- role: string;
3
- parts?: ChatPart[];
4
- }
5
- export type ChatPart = ChatMessagePart | ChatUploadDataPart | ChatFunctionCallingPart | ChatFunctionResponsePart;
6
- export type ChatMessagePart = {
7
- text: string;
8
- };
9
- export type ChatUploadDataPart = {
10
- inline_data: {
11
- mime_type: string;
12
- data?: string;
13
- };
14
- };
15
- export type ChatFunctionCallingPart = {
16
- functionCall: {
17
- name: string;
18
- args?: any;
19
- };
20
- };
21
- export type ChatFunctionResponsePart = {
22
- functionResponse: {
23
- name: string;
24
- response: any;
25
- };
26
- };
27
- export interface ChatResponse {
28
- candidates: {
29
- content: ChatCompletionResponseMessage;
30
- finishReason: string;
31
- index: number;
32
- safetyRatings: {
33
- category: string;
34
- probability: string;
35
- }[];
36
- }[];
37
- promptFeedback: {
38
- safetyRatings: {
39
- category: string;
40
- probability: string;
41
- }[];
42
- };
43
- }
44
- export interface ChatCompletionFunction {
45
- name: string;
46
- description?: string;
47
- parameters?: {
48
- [key: string]: any;
49
- };
50
- }
51
- export interface ChatCompletionMessageFunctionCall {
52
- name: string;
53
- args?: any;
54
- }
55
- export interface CreateEmbeddingResponse {
56
- embedding: {
57
- values: number[];
58
- };
59
- }
60
- export type ChatCompletionResponseMessageRoleEnum = 'system' | 'model' | 'user' | 'function';
package/lib/types.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
package/lib/utils.d.ts DELETED
@@ -1,9 +0,0 @@
1
- import { AIMessageChunk, BaseMessage, ChatMessageChunk, HumanMessageChunk, MessageType, SystemMessageChunk } from '@langchain/core/messages';
2
- import { ChatCompletionFunction, ChatCompletionResponseMessage, ChatCompletionResponseMessageRoleEnum, ChatPart } from './types';
3
- import { StructuredTool } from '@langchain/core/tools';
4
- export declare function langchainMessageToGeminiMessage(messages: BaseMessage[], model?: string): Promise<ChatCompletionResponseMessage[]>;
5
- export declare function partAsType<T extends ChatPart>(part: ChatPart): T;
6
- export declare function formatToolsToGeminiAITools(tools: StructuredTool[]): ChatCompletionFunction[];
7
- export declare function formatToolToGeminiAITool(tool: StructuredTool): ChatCompletionFunction;
8
- export declare function messageTypeToGeminiRole(type: MessageType): ChatCompletionResponseMessageRoleEnum;
9
- export declare function convertDeltaToMessageChunk(delta: Record<string, any>, defaultRole?: ChatCompletionResponseMessageRoleEnum): HumanMessageChunk | AIMessageChunk | SystemMessageChunk | ChatMessageChunk;