-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
portkey.ts
179 lines (155 loc) Β· 4.3 KB
/
portkey.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
import _ from "lodash";
import { LLMOptions, Portkey as _Portkey } from "portkey-ai";
import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";
import { GenerationChunk, LLMResult } from "@langchain/core/outputs";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { BaseLLM } from "@langchain/core/language_models/llms";
interface PortkeyOptions {
apiKey?: string;
baseURL?: string;
mode?: string;
llms?: [LLMOptions] | null;
}
const readEnv = (env: string, default_val?: string): string | undefined =>
getEnvironmentVariable(env) ?? default_val;
export class PortkeySession {
portkey: _Portkey;
constructor(options: PortkeyOptions = {}) {
if (!options.apiKey) {
/* eslint-disable no-param-reassign */
options.apiKey = readEnv("PORTKEY_API_KEY");
}
if (!options.baseURL) {
/* eslint-disable no-param-reassign */
options.baseURL = readEnv("PORTKEY_BASE_URL", "https://api.portkey.ai");
}
this.portkey = new _Portkey({});
this.portkey.llms = [{}];
if (!options.apiKey) {
throw new Error("Set Portkey ApiKey in PORTKEY_API_KEY env variable");
}
this.portkey = new _Portkey(options);
}
}
const defaultPortkeySession: {
session: PortkeySession;
options: PortkeyOptions;
}[] = [];
/**
* Get a session for the Portkey API. If one already exists with the same options,
* it will be returned. Otherwise, a new session will be created.
* @param options
* @returns
*/
export function getPortkeySession(options: PortkeyOptions = {}) {
let session = defaultPortkeySession.find((session) =>
_.isEqual(session.options, options)
)?.session;
if (!session) {
session = new PortkeySession(options);
defaultPortkeySession.push({ session, options });
}
return session;
}
/**
* @example
* ```typescript
* const model = new Portkey({
* mode: "single",
* llms: [
* {
* provider: "openai",
* virtual_key: "open-ai-key-1234",
* model: "gpt-3.5-turbo-instruct",
* max_tokens: 2000,
* },
* ],
* });
*
* // Stream the output of the model and process it
* const res = await model.stream(
* "Question: Write a story about a king\nAnswer:"
* );
* for await (const i of res) {
* process.stdout.write(i);
* }
* ```
*/
export class Portkey extends BaseLLM {
apiKey?: string = undefined;
baseURL?: string = undefined;
mode?: string = undefined;
llms?: [LLMOptions] | null = undefined;
session: PortkeySession;
constructor(init?: Partial<Portkey>) {
super(init ?? {});
this.apiKey = init?.apiKey;
this.baseURL = init?.baseURL;
this.mode = init?.mode;
this.llms = init?.llms;
this.session = getPortkeySession({
apiKey: this.apiKey,
baseURL: this.baseURL,
llms: this.llms,
mode: this.mode,
});
}
_llmType() {
return "portkey";
}
async _generate(
prompts: string[],
options: this["ParsedCallOptions"],
_?: CallbackManagerForLLMRun
): Promise<LLMResult> {
const choices = [];
for (let i = 0; i < prompts.length; i += 1) {
const response = await this.session.portkey.completions.create({
prompt: prompts[i],
...options,
stream: false,
});
choices.push(response.choices);
}
const generations = choices.map((promptChoices) =>
promptChoices.map((choice) => ({
text: choice.text ?? "",
generationInfo: {
finishReason: choice.finish_reason,
logprobs: choice.logprobs,
},
}))
);
return {
generations,
};
}
async *_streamResponseChunks(
input: string,
options: this["ParsedCallOptions"],
runManager?: CallbackManagerForLLMRun
): AsyncGenerator<GenerationChunk> {
const response = await this.session.portkey.completions.create({
prompt: input,
...options,
stream: true,
});
for await (const data of response) {
const choice = data?.choices[0];
if (!choice) {
continue;
}
const chunk = new GenerationChunk({
text: choice.text ?? "",
generationInfo: {
finishReason: choice.finish_reason,
},
});
yield chunk;
void runManager?.handleLLMNewToken(chunk.text ?? "");
}
if (options.signal?.aborted) {
throw new Error("AbortError");
}
}
}