-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
ai21.ts
201 lines (171 loc) Β· 5.38 KB
/
ai21.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
import { LLM, type BaseLLMParams } from "@langchain/core/language_models/llms";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
/**
* Type definition for AI21 penalty data.
*/
export type AI21PenaltyData = {
scale: number;
applyToWhitespaces: boolean;
applyToPunctuations: boolean;
applyToNumbers: boolean;
applyToStopwords: boolean;
applyToEmojis: boolean;
};
/**
* Interface for AI21 input parameters.
*/
export interface AI21Input extends BaseLLMParams {
ai21ApiKey?: string;
model?: string;
temperature?: number;
minTokens?: number;
maxTokens?: number;
topP?: number;
presencePenalty?: AI21PenaltyData;
countPenalty?: AI21PenaltyData;
frequencyPenalty?: AI21PenaltyData;
numResults?: number;
logitBias?: Record<string, number>;
stop?: string[];
baseUrl?: string;
}
/**
* Class representing the AI21 language model. It extends the LLM (Large
* Language Model) class, providing a standard interface for interacting
* with the AI21 language model.
*/
export class AI21 extends LLM implements AI21Input {
lc_serializable = true;
model = "j2-jumbo-instruct";
temperature = 0.7;
maxTokens = 1024;
minTokens = 0;
topP = 1;
presencePenalty = AI21.getDefaultAI21PenaltyData();
countPenalty = AI21.getDefaultAI21PenaltyData();
frequencyPenalty = AI21.getDefaultAI21PenaltyData();
numResults = 1;
logitBias?: Record<string, number>;
ai21ApiKey?: string;
stop?: string[];
baseUrl?: string;
constructor(fields?: AI21Input) {
super(fields ?? {});
this.model = fields?.model ?? this.model;
this.temperature = fields?.temperature ?? this.temperature;
this.maxTokens = fields?.maxTokens ?? this.maxTokens;
this.minTokens = fields?.minTokens ?? this.minTokens;
this.topP = fields?.topP ?? this.topP;
this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty;
this.countPenalty = fields?.countPenalty ?? this.countPenalty;
this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty;
this.numResults = fields?.numResults ?? this.numResults;
this.logitBias = fields?.logitBias;
this.ai21ApiKey =
fields?.ai21ApiKey ?? getEnvironmentVariable("AI21_API_KEY");
this.stop = fields?.stop;
this.baseUrl = fields?.baseUrl;
}
/**
* Method to validate the environment. It checks if the AI21 API key is
* set. If not, it throws an error.
*/
validateEnvironment() {
if (!this.ai21ApiKey) {
throw new Error(
`No AI21 API key found. Please set it as "AI21_API_KEY" in your environment variables.`
);
}
}
/**
* Static method to get the default penalty data for AI21.
* @returns AI21PenaltyData
*/
static getDefaultAI21PenaltyData(): AI21PenaltyData {
return {
scale: 0,
applyToWhitespaces: true,
applyToPunctuations: true,
applyToNumbers: true,
applyToStopwords: true,
applyToEmojis: true,
};
}
/** Get the type of LLM. */
_llmType() {
return "ai21";
}
/** Get the default parameters for calling AI21 API. */
get defaultParams() {
return {
temperature: this.temperature,
maxTokens: this.maxTokens,
minTokens: this.minTokens,
topP: this.topP,
presencePenalty: this.presencePenalty,
countPenalty: this.countPenalty,
frequencyPenalty: this.frequencyPenalty,
numResults: this.numResults,
logitBias: this.logitBias,
};
}
/** Get the identifying parameters for this LLM. */
get identifyingParams() {
return { ...this.defaultParams, model: this.model };
}
/** Call out to AI21's complete endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
The string generated by the model.
Example:
let response = ai21._call("Tell me a joke.");
*/
async _call(
prompt: string,
options: this["ParsedCallOptions"]
): Promise<string> {
let stop = options?.stop;
this.validateEnvironment();
if (this.stop && stop && this.stop.length > 0 && stop.length > 0) {
throw new Error("`stop` found in both the input and default params.");
}
stop = this.stop ?? stop ?? [];
const baseUrl =
this.baseUrl ?? this.model === "j1-grande-instruct"
? "https://api.ai21.com/studio/v1/experimental"
: "https://api.ai21.com/studio/v1";
const url = `${baseUrl}/${this.model}/complete`;
const headers = {
Authorization: `Bearer ${this.ai21ApiKey}`,
"Content-Type": "application/json",
};
const data = { prompt, stopSequences: stop, ...this.defaultParams };
const responseData = await this.caller.callWithOptions({}, async () => {
const response = await fetch(url, {
method: "POST",
headers,
body: JSON.stringify(data),
signal: options.signal,
});
if (!response.ok) {
const error = new Error(
`AI21 call failed with status code ${response.status}`
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(error as any).response = response;
throw error;
}
return response.json();
});
if (
!responseData.completions ||
responseData.completions.length === 0 ||
!responseData.completions[0].data
) {
throw new Error("No completions found in response");
}
return responseData.completions[0].data.text ?? "";
}
}