-
Notifications
You must be signed in to change notification settings - Fork 2k
/
llms.ts
213 lines (182 loc) Β· 5.33 KB
/
llms.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import {
CallbackManagerForLLMRun,
Callbacks,
} from "@langchain/core/callbacks/manager";
import { LLM } from "@langchain/core/language_models/llms";
import { type BaseLanguageModelCallOptions } from "@langchain/core/language_models/base";
import { BaseMessage, MessageContent } from "@langchain/core/messages";
import { GenerationChunk } from "@langchain/core/outputs";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { AbstractGoogleLLMConnection } from "./connection.js";
import {
GoogleAIBaseLLMInput,
GoogleAIModelParams,
GoogleAISafetySetting,
GooglePlatformType,
GeminiContent,
} from "./types.js";
import {
copyAIModelParams,
copyAndValidateModelParamsInto,
} from "./utils/common.js";
import {
messageContentToParts,
responseToBaseMessage,
responseToGeneration,
responseToString,
} from "./utils/gemini.js";
import { JsonStream } from "./utils/stream.js";
import { ApiKeyGoogleAuth, GoogleAbstractedClient } from "./auth.js";
class GoogleLLMConnection<AuthOptions> extends AbstractGoogleLLMConnection<
MessageContent,
AuthOptions
> {
formatContents(
input: MessageContent,
_parameters: GoogleAIModelParams
): GeminiContent[] {
const parts = messageContentToParts(input);
const contents: GeminiContent[] = [
{
role: "user", // Required by Vertex AI
parts,
},
];
return contents;
}
}
/**
* Input to LLM class.
*/
export interface GoogleBaseLLMInput<AuthOptions>
extends GoogleAIBaseLLMInput<AuthOptions> {}
/**
* Integration with an LLM.
*/
export abstract class GoogleBaseLLM<AuthOptions>
extends LLM<BaseLanguageModelCallOptions>
implements GoogleBaseLLMInput<AuthOptions>
{
// Used for tracing, replace with the same name as your class
static lc_name() {
return "GoogleLLM";
}
lc_serializable = true;
model = "gemini-pro";
temperature = 0.7;
maxOutputTokens = 1024;
topP = 0.8;
topK = 40;
stopSequences: string[] = [];
safetySettings: GoogleAISafetySetting[] = [];
protected connection: GoogleLLMConnection<AuthOptions>;
protected streamedConnection: GoogleLLMConnection<AuthOptions>;
constructor(fields?: GoogleBaseLLMInput<AuthOptions>) {
super(fields ?? {});
copyAndValidateModelParamsInto(fields, this);
const client = this.buildClient(fields);
this.buildConnection(fields ?? {}, client);
}
abstract buildAbstractedClient(
fields?: GoogleAIBaseLLMInput<AuthOptions>
): GoogleAbstractedClient;
buildApiKeyClient(apiKey: string): GoogleAbstractedClient {
return new ApiKeyGoogleAuth(apiKey);
}
buildApiKey(fields?: GoogleAIBaseLLMInput<AuthOptions>): string | undefined {
return fields?.apiKey ?? getEnvironmentVariable("GOOGLE_API_KEY");
}
buildClient(
fields?: GoogleAIBaseLLMInput<AuthOptions>
): GoogleAbstractedClient {
const apiKey = this.buildApiKey(fields);
if (apiKey) {
return this.buildApiKeyClient(apiKey);
} else {
return this.buildAbstractedClient(fields);
}
}
buildConnection(
fields: GoogleBaseLLMInput<AuthOptions>,
client: GoogleAbstractedClient
) {
this.connection = new GoogleLLMConnection(
{ ...fields, ...this },
this.caller,
client,
false
);
this.streamedConnection = new GoogleLLMConnection(
{ ...fields, ...this },
this.caller,
client,
true
);
}
get platform(): GooglePlatformType {
return this.connection.platform;
}
// Replace
_llmType() {
return "googlellm";
}
formatPrompt(prompt: string): MessageContent {
return prompt;
}
/**
* For some given input string and options, return a string output.
*/
async _call(
_prompt: string,
_options: this["ParsedCallOptions"],
_runManager?: CallbackManagerForLLMRun
): Promise<string> {
const parameters = copyAIModelParams(this);
const result = await this.connection.request(_prompt, parameters, _options);
const ret = responseToString(result);
return ret;
}
async *_streamResponseChunks(
_prompt: string,
_options: this["ParsedCallOptions"],
_runManager?: CallbackManagerForLLMRun
): AsyncGenerator<GenerationChunk> {
// Make the call as a streaming request
const parameters = copyAIModelParams(this);
const result = await this.streamedConnection.request(
_prompt,
parameters,
_options
);
// Get the streaming parser of the response
const stream = result.data as JsonStream;
// Loop until the end of the stream
// During the loop, yield each time we get a chunk from the streaming parser
// that is either available or added to the queue
while (!stream.streamDone) {
const output = await stream.nextChunk();
const chunk =
output !== null
? new GenerationChunk(responseToGeneration({ data: output }))
: new GenerationChunk({
text: "",
generationInfo: { finishReason: "stop" },
});
yield chunk;
}
}
async predictMessages(
messages: BaseMessage[],
options?: string[] | BaseLanguageModelCallOptions,
_callbacks?: Callbacks
): Promise<BaseMessage> {
const { content } = messages[0];
const result = await this.connection.request(
content,
{},
options as BaseLanguageModelCallOptions
);
const ret = responseToBaseMessage(result);
return ret;
}
}