File size: 9,395 Bytes
bce29b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import type { getProviderHelper } from "../lib/getProviderHelper.js";
import { makeRequestOptions } from "../lib/makeRequestOptions.js";
import type { InferenceTask, Options, RequestArgs } from "../types.js";
import type { EventSourceMessage } from "../vendor/fetch-event-source/parse.js";
import { getLines, getMessages } from "../vendor/fetch-event-source/parse.js";
import { InferenceClientProviderApiError } from "../errors.js";
import type { JsonObject } from "../vendor/type-fest/basic.js";

export interface ResponseWrapper<T> {
	data: T;
	requestContext: {
		url: string;
		info: RequestInit;
	};
}

function requestArgsToJson(args: RequestArgs): JsonObject {
	// Convert the entire args object to a JSON-serializable format
	const argsWithData = args as RequestArgs & { data?: Blob | ArrayBuffer };
	return JSON.parse(
		JSON.stringify({
			...argsWithData,
			data: argsWithData.data ? "[Blob or ArrayBuffer]" : null,
		})
	) as JsonObject;
}

/**
 * Primitive to make custom calls to the inference provider
 */
export async function innerRequest<T>(
	args: RequestArgs,
	providerHelper: ReturnType<typeof getProviderHelper>,
	options?: Options & {
		/** In most cases (unless we pass a endpointUrl) we know the task */
		task?: InferenceTask;
		/** Is chat completion compatible */
		chatCompletion?: boolean;
	}
): Promise<ResponseWrapper<T>> {
	const { url, info } = await makeRequestOptions(args, providerHelper, options);
	const response = await (options?.fetch ?? fetch)(url, info);

	const requestContext: ResponseWrapper<T>["requestContext"] = { url, info };

	if (options?.retry_on_error !== false && response.status === 503) {
		return innerRequest(args, providerHelper, options);
	}

	if (!response.ok) {
		const contentType = response.headers.get("Content-Type");
		if (["application/json", "application/problem+json"].some((ct) => contentType?.startsWith(ct))) {
			const output = await response.json();
			if ([400, 422, 404, 500].includes(response.status) && options?.chatCompletion) {
				throw new InferenceClientProviderApiError(
					`Provider ${args.provider} does not seem to support chat completion for model ${
						args.model
					} . Error: ${JSON.stringify(output.error)}`,
					{
						url,
						method: info.method ?? "GET",
						headers: info.headers as Record<string, string>,
						body: requestArgsToJson(args),
					},
					{ requestId: response.headers.get("x-request-id") ?? "", status: response.status, body: output }
				);
			}
			if (typeof output.error === "string" || typeof output.detail === "string" || typeof output.message === "string") {
				throw new InferenceClientProviderApiError(
					`Failed to perform inference: ${output.error ?? output.detail ?? output.message}`,
					{
						url,
						method: info.method ?? "GET",
						headers: info.headers as Record<string, string>,
						body: requestArgsToJson(args),
					},
					{ requestId: response.headers.get("x-request-id") ?? "", status: response.status, body: output }
				);
			} else {
				throw new InferenceClientProviderApiError(
					`Failed to perform inference: an HTTP error occurred when requesting the provider.`,
					{
						url,
						method: info.method ?? "GET",
						headers: info.headers as Record<string, string>,
						body: requestArgsToJson(args),
					},
					{ requestId: response.headers.get("x-request-id") ?? "", status: response.status, body: output }
				);
			}
		}
		const message = contentType?.startsWith("text/plain;") ? await response.text() : undefined;
		throw new InferenceClientProviderApiError(
			`Failed to perform inference: ${message ?? "an HTTP error occurred when requesting the provider"}`,
			{
				url,
				method: info.method ?? "GET",
				headers: info.headers as Record<string, string>,
				body: requestArgsToJson(args),
			},
			{ requestId: response.headers.get("x-request-id") ?? "", status: response.status, body: message ?? "" }
		);
	}

	if (response.headers.get("Content-Type")?.startsWith("application/json")) {
		const data = (await response.json()) as T;
		return { data, requestContext };
	}

	const blob = (await response.blob()) as T;
	return { data: blob as unknown as T, requestContext };
}

/**
 * Primitive to make custom inference calls that expect server-sent events, and returns the response through a generator
 */
export async function* innerStreamingRequest<T>(
	args: RequestArgs,
	providerHelper: ReturnType<typeof getProviderHelper>,
	options?: Options & {
		/** In most cases (unless we pass a endpointUrl) we know the task */
		task?: InferenceTask;
		/** Is chat completion compatible */
		chatCompletion?: boolean;
	}
): AsyncGenerator<T> {
	const { url, info } = await makeRequestOptions({ ...args, stream: true }, providerHelper, options);
	const response = await (options?.fetch ?? fetch)(url, info);

	if (options?.retry_on_error !== false && response.status === 503) {
		return yield* innerStreamingRequest(args, providerHelper, options);
	}
	if (!response.ok) {
		if (response.headers.get("Content-Type")?.startsWith("application/json")) {
			const output = await response.json();
			if ([400, 422, 404, 500].includes(response.status) && options?.chatCompletion) {
				throw new InferenceClientProviderApiError(
					`Provider ${args.provider} does not seem to support chat completion for model ${
						args.model
					} . Error: ${JSON.stringify(output.error)}`,
					{
						url,
						method: info.method ?? "GET",
						headers: info.headers as Record<string, string>,
						body: requestArgsToJson(args),
					},
					{ requestId: response.headers.get("x-request-id") ?? "", status: response.status, body: output }
				);
			}
			if (typeof output.error === "string") {
				throw new InferenceClientProviderApiError(
					`Failed to perform inference: ${output.error}`,
					{
						url,
						method: info.method ?? "GET",
						headers: info.headers as Record<string, string>,
						body: requestArgsToJson(args),
					},
					{ requestId: response.headers.get("x-request-id") ?? "", status: response.status, body: output }
				);
			}
			if (output.error && "message" in output.error && typeof output.error.message === "string") {
				/// OpenAI errors
				throw new InferenceClientProviderApiError(
					`Failed to perform inference: ${output.error.message}`,
					{
						url,
						method: info.method ?? "GET",
						headers: info.headers as Record<string, string>,
						body: requestArgsToJson(args),
					},
					{ requestId: response.headers.get("x-request-id") ?? "", status: response.status, body: output }
				);
			}
			// Sambanova errors
			if (typeof output.message === "string") {
				throw new InferenceClientProviderApiError(
					`Failed to perform inference: ${output.message}`,
					{
						url,
						method: info.method ?? "GET",
						headers: info.headers as Record<string, string>,
						body: requestArgsToJson(args),
					},
					{ requestId: response.headers.get("x-request-id") ?? "", status: response.status, body: output }
				);
			}
		}

		throw new InferenceClientProviderApiError(
			`Failed to perform inference: an HTTP error occurred when requesting the provider.`,
			{
				url,
				method: info.method ?? "GET",
				headers: info.headers as Record<string, string>,
				body: requestArgsToJson(args),
			},
			{ requestId: response.headers.get("x-request-id") ?? "", status: response.status, body: "" }
		);
	}
	if (!response.headers.get("content-type")?.startsWith("text/event-stream")) {
		throw new InferenceClientProviderApiError(
			`Failed to perform inference: server does not support event stream content type, it returned ` +
				response.headers.get("content-type"),
			{
				url,
				method: info.method ?? "GET",
				headers: info.headers as Record<string, string>,
				body: requestArgsToJson(args),
			},
			{ requestId: response.headers.get("x-request-id") ?? "", status: response.status, body: "" }
		);
	}

	if (!response.body) {
		return;
	}

	const reader = response.body.getReader();
	let events: EventSourceMessage[] = [];

	const onEvent = (event: EventSourceMessage) => {
		// accumulate events in array
		events.push(event);
	};

	const onChunk = getLines(
		getMessages(
			() => {},
			() => {},
			onEvent
		)
	);

	try {
		while (true) {
			const { done, value } = await reader.read();
			if (done) {
				return;
			}
			onChunk(value);
			for (const event of events) {
				if (event.data.length > 0) {
					if (event.data === "[DONE]") {
						return;
					}
					const data = JSON.parse(event.data);
					if (typeof data === "object" && data !== null && "error" in data) {
						const errorStr =
							typeof data.error === "string"
								? data.error
								: typeof data.error === "object" &&
								    data.error &&
								    "message" in data.error &&
								    typeof data.error.message === "string"
								  ? data.error.message
								  : JSON.stringify(data.error);
						throw new InferenceClientProviderApiError(
							`Failed to perform inference: an occurred while streaming the response: ${errorStr}`,
							{
								url,
								method: info.method ?? "GET",
								headers: info.headers as Record<string, string>,
								body: requestArgsToJson(args),
							},
							{ requestId: response.headers.get("x-request-id") ?? "", status: response.status, body: data }
						);
					}
					yield data as T;
				}
			}
			events = [];
		}
	} finally {
		reader.releaseLock();
	}
}