-
Notifications
You must be signed in to change notification settings - Fork 201
/
Copy pathclient.ts
216 lines (195 loc) · 6.96 KB
/
client.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
214
215
216
/**
* Copyright 2024 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import grpc, {
CallOptions as GRPCCallOptions,
ClientOptions as GRPCClientOptions,
ClientReadableStream,
ClientUnaryCall,
} from "@grpc/grpc-js";
import * as R from "remeda";
// eslint-disable-next-line no-restricted-imports
import { UnaryCallback } from "@grpc/grpc-js/build/src/client.js";
import { FrameworkError, ValueError } from "@/errors.js";
import protoLoader from "@grpc/proto-loader";
import {
BatchedGenerationRequest,
BatchedGenerationResponse__Output,
BatchedTokenizeRequest,
BatchedTokenizeResponse__Output,
GenerationRequest__Output,
ModelInfoRequest,
ModelInfoResponse__Output,
ProtoGrpcType as GenerationProtoGentypes,
SingleGenerationRequest,
} from "@/adapters/ibm-vllm/types.js";
import { parseEnv } from "@/internals/env.js";
import { z } from "zod";
import { Cache } from "@/cache/decoratorCache.js";
import { Serializable } from "@/internals/serializable.js";
const GENERATION_PROTO_PATH = new URL("./proto/generation.proto", import.meta.url);
interface ClientOptions {
modelRouterSubdomain?: string;
url: string;
credentials: {
rootCert: string;
certChain: string;
privateKey: string;
};
grpcClientOptions: GRPCClientOptions;
clientShutdownDelay: number;
}
const defaultOptions = {
clientShutdownDelay: 5 * 60 * 1000,
grpcClientOptions: {
// This is needed, otherwise communication to DIPC cluster fails with "Dropped connection" error after +- 50 secs
"grpc.keepalive_time_ms": 25000,
"grpc.max_receive_message_length": 32 * 1024 * 1024, // 32MiB
},
};
const generationPackageObject = grpc.loadPackageDefinition(
protoLoader.loadSync([GENERATION_PROTO_PATH.pathname], {
longs: Number,
enums: String,
arrays: true,
objects: true,
oneofs: true,
keepCase: true,
defaults: true,
}),
) as unknown as GenerationProtoGentypes;
const GRPC_CLIENT_TTL = 15 * 60 * 1000;
type CallOptions = GRPCCallOptions & { signal?: AbortSignal };
type RequiredModel<T> = T & { model_id: string };
export class Client extends Serializable {
public readonly options: ClientOptions;
private usedDefaultCredentials = false;
@Cache({ ttl: GRPC_CLIENT_TTL })
protected getClient(modelId: string) {
const modelSpecificUrl = this.options.url.replace(/{model_id}/, modelId.replaceAll("/", "--"));
const client = new generationPackageObject.fmaas.GenerationService(
modelSpecificUrl,
grpc.credentials.createSsl(
Buffer.from(this.options.credentials.rootCert),
Buffer.from(this.options.credentials.privateKey),
Buffer.from(this.options.credentials.certChain),
),
this.options.grpcClientOptions,
);
setTimeout(() => {
try {
client.close();
} catch {
/* empty */
}
}, GRPC_CLIENT_TTL + this.options.clientShutdownDelay).unref();
return client;
}
protected getDefaultCredentials() {
this.usedDefaultCredentials = true;
return {
rootCert: parseEnv("IBM_VLLM_ROOT_CERT", z.string()),
privateKey: parseEnv("IBM_VLLM_PRIVATE_KEY", z.string()),
certChain: parseEnv("IBM_VLLM_CERT_CHAIN", z.string()),
};
}
constructor(options?: Partial<ClientOptions>) {
super();
this.options = {
...defaultOptions,
...options,
url: options?.url ?? parseEnv("IBM_VLLM_URL", z.string()),
credentials: options?.credentials ?? this.getDefaultCredentials(),
};
}
async modelInfo(request: RequiredModel<ModelInfoRequest>, options?: CallOptions) {
const client = this.getClient(request.model_id);
return this.wrapGrpcCall<ModelInfoRequest, ModelInfoResponse__Output>(
client.modelInfo.bind(client),
)(request, options);
}
async generate(request: RequiredModel<BatchedGenerationRequest>, options?: CallOptions) {
const client = this.getClient(request.model_id);
return this.wrapGrpcCall<BatchedGenerationRequest, BatchedGenerationResponse__Output>(
client.generate.bind(client),
)(request, options);
}
async generateStream(request: RequiredModel<SingleGenerationRequest>, options?: CallOptions) {
const client = this.getClient(request.model_id);
return this.wrapGrpcStream<SingleGenerationRequest, GenerationRequest__Output>(
client.generateStream.bind(client),
)(request, options);
}
async tokenize(request: RequiredModel<BatchedTokenizeRequest>, options?: CallOptions) {
const client = this.getClient(request.model_id);
return this.wrapGrpcCall<BatchedTokenizeRequest, BatchedTokenizeResponse__Output>(
client.tokenize.bind(client),
)(request, options);
}
protected wrapGrpcCall<TRequest, TResponse>(
fn: (
request: TRequest,
options: CallOptions,
callback: UnaryCallback<TResponse>,
) => ClientUnaryCall,
) {
return (request: TRequest, { signal, ...options }: CallOptions = {}): Promise<TResponse> => {
return new Promise<TResponse>((resolve, reject) => {
const call = fn(request, options, (err, response) => {
signal?.removeEventListener("abort", abortHandler);
if (err) {
reject(err);
} else {
if (response === undefined) {
reject(new FrameworkError("Invalid response from GRPC server"));
} else {
resolve(response);
}
}
});
const abortHandler = () => call.cancel();
signal?.addEventListener("abort", abortHandler, { once: true });
});
};
}
protected wrapGrpcStream<TRequest, TResponse>(
fn: (request: TRequest, options: CallOptions) => ClientReadableStream<TResponse>,
) {
return async (
request: TRequest,
{ signal, ...options }: CallOptions = {},
): Promise<ClientReadableStream<TResponse>> => {
const stream = fn(request, options);
const abortHandler = () => stream.cancel();
signal?.addEventListener("abort", abortHandler, { once: true });
stream.addListener("close", () => signal?.removeEventListener("abort", abortHandler));
return stream;
};
}
createSnapshot() {
if (!this.usedDefaultCredentials) {
throw new ValueError(
"Cannot serialize a client with credentials passed directly. Use environment variables.",
);
}
return {
options: R.omit(this.options, ["credentials"]),
};
}
loadSnapshot(snapshot: ReturnType<typeof this.createSnapshot>) {
Object.assign(this, snapshot);
this.options.credentials = this.getDefaultCredentials();
}
}