@huggingface/inference 3.6.1 → 3.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +0 -25
  2. package/dist/index.cjs +256 -154
  3. package/dist/index.js +256 -154
  4. package/dist/src/config.d.ts +1 -0
  5. package/dist/src/config.d.ts.map +1 -1
  6. package/dist/src/lib/makeRequestOptions.d.ts.map +1 -1
  7. package/dist/src/providers/black-forest-labs.d.ts.map +1 -1
  8. package/dist/src/providers/cerebras.d.ts.map +1 -1
  9. package/dist/src/providers/cohere.d.ts.map +1 -1
  10. package/dist/src/providers/fal-ai.d.ts +6 -16
  11. package/dist/src/providers/fal-ai.d.ts.map +1 -1
  12. package/dist/src/providers/fireworks-ai.d.ts.map +1 -1
  13. package/dist/src/providers/hf-inference.d.ts.map +1 -1
  14. package/dist/src/providers/hyperbolic.d.ts.map +1 -1
  15. package/dist/src/providers/nebius.d.ts.map +1 -1
  16. package/dist/src/providers/novita.d.ts.map +1 -1
  17. package/dist/src/providers/openai.d.ts.map +1 -1
  18. package/dist/src/providers/replicate.d.ts.map +1 -1
  19. package/dist/src/providers/sambanova.d.ts.map +1 -1
  20. package/dist/src/providers/together.d.ts.map +1 -1
  21. package/dist/src/tasks/audio/automaticSpeechRecognition.d.ts.map +1 -1
  22. package/dist/src/tasks/custom/request.d.ts +1 -0
  23. package/dist/src/tasks/custom/request.d.ts.map +1 -1
  24. package/dist/src/tasks/custom/streamingRequest.d.ts +1 -0
  25. package/dist/src/tasks/custom/streamingRequest.d.ts.map +1 -1
  26. package/dist/src/tasks/cv/imageToText.d.ts.map +1 -1
  27. package/dist/src/tasks/cv/objectDetection.d.ts +1 -1
  28. package/dist/src/tasks/cv/objectDetection.d.ts.map +1 -1
  29. package/dist/src/tasks/cv/textToVideo.d.ts +1 -1
  30. package/dist/src/tasks/cv/textToVideo.d.ts.map +1 -1
  31. package/dist/src/tasks/cv/zeroShotImageClassification.d.ts +1 -1
  32. package/dist/src/tasks/cv/zeroShotImageClassification.d.ts.map +1 -1
  33. package/dist/src/tasks/multimodal/documentQuestionAnswering.d.ts +1 -1
  34. package/dist/src/tasks/multimodal/documentQuestionAnswering.d.ts.map +1 -1
  35. package/dist/src/tasks/multimodal/visualQuestionAnswering.d.ts.map +1 -1
  36. package/dist/src/tasks/nlp/chatCompletion.d.ts +1 -1
  37. package/dist/src/tasks/nlp/chatCompletion.d.ts.map +1 -1
  38. package/dist/src/tasks/nlp/chatCompletionStream.d.ts +1 -1
  39. package/dist/src/tasks/nlp/chatCompletionStream.d.ts.map +1 -1
  40. package/dist/src/tasks/nlp/questionAnswering.d.ts.map +1 -1
  41. package/dist/src/tasks/nlp/sentenceSimilarity.d.ts.map +1 -1
  42. package/dist/src/tasks/nlp/textClassification.d.ts.map +1 -1
  43. package/dist/src/tasks/nlp/tokenClassification.d.ts.map +1 -1
  44. package/dist/src/tasks/nlp/zeroShotClassification.d.ts.map +1 -1
  45. package/dist/src/types.d.ts +11 -2
  46. package/dist/src/types.d.ts.map +1 -1
  47. package/dist/src/utils/request.d.ts +27 -0
  48. package/dist/src/utils/request.d.ts.map +1 -0
  49. package/dist/test/InferenceClient.spec.d.ts.map +1 -1
  50. package/package.json +2 -2
  51. package/src/config.ts +1 -0
  52. package/src/lib/makeRequestOptions.ts +8 -3
  53. package/src/providers/black-forest-labs.ts +6 -2
  54. package/src/providers/cerebras.ts +6 -2
  55. package/src/providers/cohere.ts +6 -2
  56. package/src/providers/fal-ai.ts +85 -3
  57. package/src/providers/fireworks-ai.ts +6 -2
  58. package/src/providers/hf-inference.ts +6 -2
  59. package/src/providers/hyperbolic.ts +6 -2
  60. package/src/providers/nebius.ts +6 -2
  61. package/src/providers/novita.ts +5 -2
  62. package/src/providers/openai.ts +6 -2
  63. package/src/providers/replicate.ts +6 -2
  64. package/src/providers/sambanova.ts +6 -2
  65. package/src/providers/together.ts +6 -2
  66. package/src/snippets/templates.exported.ts +1 -1
  67. package/src/tasks/audio/audioClassification.ts +2 -2
  68. package/src/tasks/audio/audioToAudio.ts +2 -2
  69. package/src/tasks/audio/automaticSpeechRecognition.ts +3 -3
  70. package/src/tasks/audio/textToSpeech.ts +2 -2
  71. package/src/tasks/custom/request.ts +7 -32
  72. package/src/tasks/custom/streamingRequest.ts +5 -85
  73. package/src/tasks/cv/imageClassification.ts +2 -2
  74. package/src/tasks/cv/imageSegmentation.ts +2 -2
  75. package/src/tasks/cv/imageToImage.ts +2 -2
  76. package/src/tasks/cv/imageToText.ts +7 -9
  77. package/src/tasks/cv/objectDetection.ts +4 -4
  78. package/src/tasks/cv/textToImage.ts +3 -3
  79. package/src/tasks/cv/textToVideo.ts +23 -36
  80. package/src/tasks/cv/zeroShotImageClassification.ts +4 -5
  81. package/src/tasks/multimodal/documentQuestionAnswering.ts +13 -13
  82. package/src/tasks/multimodal/visualQuestionAnswering.ts +4 -2
  83. package/src/tasks/nlp/chatCompletion.ts +3 -4
  84. package/src/tasks/nlp/chatCompletionStream.ts +3 -3
  85. package/src/tasks/nlp/featureExtraction.ts +2 -2
  86. package/src/tasks/nlp/fillMask.ts +2 -2
  87. package/src/tasks/nlp/questionAnswering.ts +3 -2
  88. package/src/tasks/nlp/sentenceSimilarity.ts +2 -11
  89. package/src/tasks/nlp/summarization.ts +2 -2
  90. package/src/tasks/nlp/tableQuestionAnswering.ts +2 -2
  91. package/src/tasks/nlp/textClassification.ts +8 -9
  92. package/src/tasks/nlp/textGeneration.ts +16 -16
  93. package/src/tasks/nlp/textGenerationStream.ts +2 -2
  94. package/src/tasks/nlp/tokenClassification.ts +9 -10
  95. package/src/tasks/nlp/translation.ts +2 -2
  96. package/src/tasks/nlp/zeroShotClassification.ts +9 -10
  97. package/src/tasks/tabular/tabularClassification.ts +2 -2
  98. package/src/tasks/tabular/tabularRegression.ts +2 -2
  99. package/src/types.ts +13 -2
  100. package/src/utils/request.ts +161 -0
@@ -14,9 +14,17 @@
14
14
  *
15
15
  * Thanks!
16
16
  */
17
- import type { ProviderConfig, UrlParams, HeaderParams, BodyParams } from "../types";
17
+ import { InferenceOutputError } from "../lib/InferenceOutputError";
18
+ import { isUrl } from "../lib/isUrl";
19
+ import type { BodyParams, HeaderParams, InferenceTask, ProviderConfig, UrlParams } from "../types";
20
+ import { delay } from "../utils/delay";
18
21
 
19
22
  const FAL_AI_API_BASE_URL = "https://fal.run";
23
+ const FAL_AI_API_BASE_URL_QUEUE = "https://queue.fal.run";
24
+
25
+ const makeBaseUrl = (task?: InferenceTask): string => {
26
+ return task === "text-to-video" ? FAL_AI_API_BASE_URL_QUEUE : FAL_AI_API_BASE_URL;
27
+ };
20
28
 
21
29
  const makeBody = (params: BodyParams): Record<string, unknown> => {
22
30
  return params.args;
@@ -29,12 +37,86 @@ const makeHeaders = (params: HeaderParams): Record<string, string> => {
29
37
  };
30
38
 
31
39
  const makeUrl = (params: UrlParams): string => {
32
- return `${params.baseUrl}/${params.model}`;
40
+ const baseUrl = `${params.baseUrl}/${params.model}`;
41
+ if (params.authMethod !== "provider-key" && params.task === "text-to-video") {
42
+ return `${baseUrl}?_subdomain=queue`;
43
+ }
44
+ return baseUrl;
33
45
  };
34
46
 
35
47
  export const FAL_AI_CONFIG: ProviderConfig = {
36
- baseUrl: FAL_AI_API_BASE_URL,
48
+ makeBaseUrl,
37
49
  makeBody,
38
50
  makeHeaders,
39
51
  makeUrl,
40
52
  };
53
+
54
+ export interface FalAiQueueOutput {
55
+ request_id: string;
56
+ status: string;
57
+ response_url: string;
58
+ }
59
+
60
+ export async function pollFalResponse(
61
+ res: FalAiQueueOutput,
62
+ url: string,
63
+ headers: Record<string, string>
64
+ ): Promise<Blob> {
65
+ const requestId = res.request_id;
66
+ if (!requestId) {
67
+ throw new InferenceOutputError("No request ID found in the response");
68
+ }
69
+ let status = res.status;
70
+
71
+ const parsedUrl = new URL(url);
72
+ const baseUrl = `${parsedUrl.protocol}//${parsedUrl.host}${
73
+ parsedUrl.host === "router.huggingface.co" ? "/fal-ai" : ""
74
+ }`;
75
+
76
+ // extracting the provider model id for status and result urls
77
+ // from the response as it might be different from the mapped model in `url`
78
+ const modelId = new URL(res.response_url).pathname;
79
+ const queryParams = parsedUrl.search;
80
+
81
+ const statusUrl = `${baseUrl}${modelId}/status${queryParams}`;
82
+ const resultUrl = `${baseUrl}${modelId}${queryParams}`;
83
+
84
+ while (status !== "COMPLETED") {
85
+ await delay(500);
86
+ const statusResponse = await fetch(statusUrl, { headers });
87
+
88
+ if (!statusResponse.ok) {
89
+ throw new InferenceOutputError("Failed to fetch response status from fal-ai API");
90
+ }
91
+ try {
92
+ status = (await statusResponse.json()).status;
93
+ } catch (error) {
94
+ throw new InferenceOutputError("Failed to parse status response from fal-ai API");
95
+ }
96
+ }
97
+
98
+ const resultResponse = await fetch(resultUrl, { headers });
99
+ let result: unknown;
100
+ try {
101
+ result = await resultResponse.json();
102
+ } catch (error) {
103
+ throw new InferenceOutputError("Failed to parse result response from fal-ai API");
104
+ }
105
+ if (
106
+ typeof result === "object" &&
107
+ !!result &&
108
+ "video" in result &&
109
+ typeof result.video === "object" &&
110
+ !!result.video &&
111
+ "url" in result.video &&
112
+ typeof result.video.url === "string" &&
113
+ isUrl(result.video.url)
114
+ ) {
115
+ const urlResponse = await fetch(result.video.url);
116
+ return await urlResponse.blob();
117
+ } else {
118
+ throw new InferenceOutputError(
119
+ "Expected { video: { url: string } } result format, got instead: " + JSON.stringify(result)
120
+ );
121
+ }
122
+ }
@@ -14,10 +14,14 @@
14
14
  *
15
15
  * Thanks!
16
16
  */
17
- import type { ProviderConfig, UrlParams, HeaderParams, BodyParams } from "../types";
17
+ import type { BodyParams, HeaderParams, ProviderConfig, UrlParams } from "../types";
18
18
 
19
19
  const FIREWORKS_AI_API_BASE_URL = "https://api.fireworks.ai";
20
20
 
21
+ const makeBaseUrl = (): string => {
22
+ return FIREWORKS_AI_API_BASE_URL;
23
+ };
24
+
21
25
  const makeBody = (params: BodyParams): Record<string, unknown> => {
22
26
  return {
23
27
  ...params.args,
@@ -37,7 +41,7 @@ const makeUrl = (params: UrlParams): string => {
37
41
  };
38
42
 
39
43
  export const FIREWORKS_AI_CONFIG: ProviderConfig = {
40
- baseUrl: FIREWORKS_AI_API_BASE_URL,
44
+ makeBaseUrl,
41
45
  makeBody,
42
46
  makeHeaders,
43
47
  makeUrl,
@@ -11,7 +11,11 @@
11
11
  * Thanks!
12
12
  */
13
13
  import { HF_ROUTER_URL } from "../config";
14
- import type { ProviderConfig, UrlParams, HeaderParams, BodyParams } from "../types";
14
+ import type { BodyParams, HeaderParams, ProviderConfig, UrlParams } from "../types";
15
+
16
+ const makeBaseUrl = (): string => {
17
+ return `${HF_ROUTER_URL}/hf-inference`;
18
+ };
15
19
 
16
20
  const makeBody = (params: BodyParams): Record<string, unknown> => {
17
21
  return {
@@ -36,7 +40,7 @@ const makeUrl = (params: UrlParams): string => {
36
40
  };
37
41
 
38
42
  export const HF_INFERENCE_CONFIG: ProviderConfig = {
39
- baseUrl: `${HF_ROUTER_URL}/hf-inference`,
43
+ makeBaseUrl,
40
44
  makeBody,
41
45
  makeHeaders,
42
46
  makeUrl,
@@ -14,10 +14,14 @@
14
14
  *
15
15
  * Thanks!
16
16
  */
17
- import type { ProviderConfig, UrlParams, HeaderParams, BodyParams } from "../types";
17
+ import type { BodyParams, HeaderParams, ProviderConfig, UrlParams } from "../types";
18
18
 
19
19
  const HYPERBOLIC_API_BASE_URL = "https://api.hyperbolic.xyz";
20
20
 
21
+ const makeBaseUrl = (): string => {
22
+ return HYPERBOLIC_API_BASE_URL;
23
+ };
24
+
21
25
  const makeBody = (params: BodyParams): Record<string, unknown> => {
22
26
  return {
23
27
  ...params.args,
@@ -37,7 +41,7 @@ const makeUrl = (params: UrlParams): string => {
37
41
  };
38
42
 
39
43
  export const HYPERBOLIC_CONFIG: ProviderConfig = {
40
- baseUrl: HYPERBOLIC_API_BASE_URL,
44
+ makeBaseUrl,
41
45
  makeBody,
42
46
  makeHeaders,
43
47
  makeUrl,
@@ -14,10 +14,14 @@
14
14
  *
15
15
  * Thanks!
16
16
  */
17
- import type { ProviderConfig, UrlParams, HeaderParams, BodyParams } from "../types";
17
+ import type { BodyParams, HeaderParams, ProviderConfig, UrlParams } from "../types";
18
18
 
19
19
  const NEBIUS_API_BASE_URL = "https://api.studio.nebius.ai";
20
20
 
21
+ const makeBaseUrl = (): string => {
22
+ return NEBIUS_API_BASE_URL;
23
+ };
24
+
21
25
  const makeBody = (params: BodyParams): Record<string, unknown> => {
22
26
  return {
23
27
  ...params.args,
@@ -43,7 +47,7 @@ const makeUrl = (params: UrlParams): string => {
43
47
  };
44
48
 
45
49
  export const NEBIUS_CONFIG: ProviderConfig = {
46
- baseUrl: NEBIUS_API_BASE_URL,
50
+ makeBaseUrl,
47
51
  makeBody,
48
52
  makeHeaders,
49
53
  makeUrl,
@@ -14,10 +14,13 @@
14
14
  *
15
15
  * Thanks!
16
16
  */
17
- import type { ProviderConfig, UrlParams, HeaderParams, BodyParams } from "../types";
17
+ import type { BodyParams, HeaderParams, ProviderConfig, UrlParams } from "../types";
18
18
 
19
19
  const NOVITA_API_BASE_URL = "https://api.novita.ai";
20
20
 
21
+ const makeBaseUrl = (): string => {
22
+ return NOVITA_API_BASE_URL;
23
+ };
21
24
  const makeBody = (params: BodyParams): Record<string, unknown> => {
22
25
  return {
23
26
  ...params.args,
@@ -41,7 +44,7 @@ const makeUrl = (params: UrlParams): string => {
41
44
  };
42
45
 
43
46
  export const NOVITA_CONFIG: ProviderConfig = {
44
- baseUrl: NOVITA_API_BASE_URL,
47
+ makeBaseUrl,
45
48
  makeBody,
46
49
  makeHeaders,
47
50
  makeUrl,
@@ -1,10 +1,14 @@
1
1
  /**
2
2
  * Special case: provider configuration for a private models provider (OpenAI in this case).
3
3
  */
4
- import type { ProviderConfig, UrlParams, HeaderParams, BodyParams } from "../types";
4
+ import type { BodyParams, HeaderParams, ProviderConfig, UrlParams } from "../types";
5
5
 
6
6
  const OPENAI_API_BASE_URL = "https://api.openai.com";
7
7
 
8
+ const makeBaseUrl = (): string => {
9
+ return OPENAI_API_BASE_URL;
10
+ };
11
+
8
12
  const makeBody = (params: BodyParams): Record<string, unknown> => {
9
13
  if (!params.chatCompletion) {
10
14
  throw new Error("OpenAI only supports chat completions.");
@@ -27,7 +31,7 @@ const makeUrl = (params: UrlParams): string => {
27
31
  };
28
32
 
29
33
  export const OPENAI_CONFIG: ProviderConfig = {
30
- baseUrl: OPENAI_API_BASE_URL,
34
+ makeBaseUrl,
31
35
  makeBody,
32
36
  makeHeaders,
33
37
  makeUrl,
@@ -14,10 +14,14 @@
14
14
  *
15
15
  * Thanks!
16
16
  */
17
- import type { ProviderConfig, UrlParams, HeaderParams, BodyParams } from "../types";
17
+ import type { BodyParams, HeaderParams, ProviderConfig, UrlParams } from "../types";
18
18
 
19
19
  export const REPLICATE_API_BASE_URL = "https://api.replicate.com";
20
20
 
21
+ const makeBaseUrl = (): string => {
22
+ return REPLICATE_API_BASE_URL;
23
+ };
24
+
21
25
  const makeBody = (params: BodyParams): Record<string, unknown> => {
22
26
  return {
23
27
  input: params.args,
@@ -39,7 +43,7 @@ const makeUrl = (params: UrlParams): string => {
39
43
  };
40
44
 
41
45
  export const REPLICATE_CONFIG: ProviderConfig = {
42
- baseUrl: REPLICATE_API_BASE_URL,
46
+ makeBaseUrl,
43
47
  makeBody,
44
48
  makeHeaders,
45
49
  makeUrl,
@@ -14,10 +14,14 @@
14
14
  *
15
15
  * Thanks!
16
16
  */
17
- import type { ProviderConfig, UrlParams, HeaderParams, BodyParams } from "../types";
17
+ import type { BodyParams, HeaderParams, ProviderConfig, UrlParams } from "../types";
18
18
 
19
19
  const SAMBANOVA_API_BASE_URL = "https://api.sambanova.ai";
20
20
 
21
+ const makeBaseUrl = (): string => {
22
+ return SAMBANOVA_API_BASE_URL;
23
+ };
24
+
21
25
  const makeBody = (params: BodyParams): Record<string, unknown> => {
22
26
  return {
23
27
  ...params.args,
@@ -37,7 +41,7 @@ const makeUrl = (params: UrlParams): string => {
37
41
  };
38
42
 
39
43
  export const SAMBANOVA_CONFIG: ProviderConfig = {
40
- baseUrl: SAMBANOVA_API_BASE_URL,
44
+ makeBaseUrl,
41
45
  makeBody,
42
46
  makeHeaders,
43
47
  makeUrl,
@@ -14,10 +14,14 @@
14
14
  *
15
15
  * Thanks!
16
16
  */
17
- import type { ProviderConfig, UrlParams, HeaderParams, BodyParams } from "../types";
17
+ import type { BodyParams, HeaderParams, ProviderConfig, UrlParams } from "../types";
18
18
 
19
19
  const TOGETHER_API_BASE_URL = "https://api.together.xyz";
20
20
 
21
+ const makeBaseUrl = (): string => {
22
+ return TOGETHER_API_BASE_URL;
23
+ };
24
+
21
25
  const makeBody = (params: BodyParams): Record<string, unknown> => {
22
26
  return {
23
27
  ...params.args,
@@ -43,7 +47,7 @@ const makeUrl = (params: UrlParams): string => {
43
47
  };
44
48
 
45
49
  export const TOGETHER_CONFIG: ProviderConfig = {
46
- baseUrl: TOGETHER_API_BASE_URL,
50
+ makeBaseUrl,
47
51
  makeBody,
48
52
  makeHeaders,
49
53
  makeUrl,
@@ -6,7 +6,7 @@ export const templates: Record<string, Record<string, Record<string, string>>> =
6
6
  "basicAudio": "async function query(data) {\n\tconst response = await fetch(\n\t\t\"{{ fullUrl }}\",\n\t\t{\n\t\t\theaders: {\n\t\t\t\tAuthorization: \"{{ authorizationHeader }}\",\n\t\t\t\t\"Content-Type\": \"audio/flac\"\n\t\t\t},\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify(data),\n\t\t}\n\t);\n\tconst result = await response.json();\n\treturn result;\n}\n\nquery({ inputs: {{ providerInputs.asObj.inputs }} }).then((response) => {\n console.log(JSON.stringify(response));\n});",
7
7
  "basicImage": "async function query(data) {\n\tconst response = await fetch(\n\t\t\"{{ fullUrl }}\",\n\t\t{\n\t\t\theaders: {\n\t\t\t\tAuthorization: \"{{ authorizationHeader }}\",\n\t\t\t\t\"Content-Type\": \"image/jpeg\"\n\t\t\t},\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify(data),\n\t\t}\n\t);\n\tconst result = await response.json();\n\treturn result;\n}\n\nquery({ inputs: {{ providerInputs.asObj.inputs }} }).then((response) => {\n console.log(JSON.stringify(response));\n});",
8
8
  "textToAudio": "{% if model.library_name == \"transformers\" %}\nasync function query(data) {\n\tconst response = await fetch(\n\t\t\"{{ fullUrl }}\",\n\t\t{\n\t\t\theaders: {\n\t\t\t\tAuthorization: \"{{ authorizationHeader }}\",\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t},\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify(data),\n\t\t}\n\t);\n\tconst result = await response.blob();\n return result;\n}\n\nquery({ inputs: {{ providerInputs.asObj.inputs }} }).then((response) => {\n // Returns a byte object of the Audio wavform. Use it directly!\n});\n{% else %}\nasync function query(data) {\n\tconst response = await fetch(\n\t\t\"{{ fullUrl }}\",\n\t\t{\n\t\t\theaders: {\n\t\t\t\tAuthorization: \"{{ authorizationHeader }}\",\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t},\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify(data),\n\t\t}\n\t);\n const result = await response.json();\n return result;\n}\n\nquery({ inputs: {{ providerInputs.asObj.inputs }} }).then((response) => {\n console.log(JSON.stringify(response));\n});\n{% endif %} ",
9
- "textToImage": "async function query(data) {\n\tconst response = await fetch(\n\t\t\"{{ fullUrl }}\",\n\t\t{\n\t\t\theaders: {\n\t\t\t\tAuthorization: \"{{ authorizationHeader }}\",\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t},\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify(data),\n\t\t}\n\t);\n\tconst result = await response.blob();\n\treturn result;\n}\n\nquery({ inputs: {{ providerInputs.asObj.inputs }} }).then((response) => {\n // Use image\n});",
9
+ "textToImage": "async function query(data) {\n\tconst response = await fetch(\n\t\t\"{{ fullUrl }}\",\n\t\t{\n\t\t\theaders: {\n\t\t\t\tAuthorization: \"{{ authorizationHeader }}\",\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t},\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify(data),\n\t\t}\n\t);\n\tconst result = await response.blob();\n\treturn result;\n}\n\n\nquery({ {{ providerInputs.asTsString }} }).then((response) => {\n // Use image\n});",
10
10
  "zeroShotClassification": "async function query(data) {\n const response = await fetch(\n\t\t\"{{ fullUrl }}\",\n {\n headers: {\n\t\t\t\tAuthorization: \"{{ authorizationHeader }}\",\n \"Content-Type\": \"application/json\",\n },\n method: \"POST\",\n body: JSON.stringify(data),\n }\n );\n const result = await response.json();\n return result;\n}\n\nquery({\n inputs: {{ providerInputs.asObj.inputs }},\n parameters: { candidate_labels: [\"refund\", \"legal\", \"faq\"] }\n}).then((response) => {\n console.log(JSON.stringify(response));\n});"
11
11
  },
12
12
  "huggingface.js": {
@@ -1,7 +1,7 @@
1
1
  import type { AudioClassificationInput, AudioClassificationOutput } from "@huggingface/tasks";
2
2
  import { InferenceOutputError } from "../../lib/InferenceOutputError";
3
3
  import type { BaseArgs, Options } from "../../types";
4
- import { request } from "../custom/request";
4
+ import { innerRequest } from "../../utils/request";
5
5
  import type { LegacyAudioInput } from "./utils";
6
6
  import { preparePayload } from "./utils";
7
7
 
@@ -16,7 +16,7 @@ export async function audioClassification(
16
16
  options?: Options
17
17
  ): Promise<AudioClassificationOutput> {
18
18
  const payload = preparePayload(args);
19
- const res = await request<AudioClassificationOutput>(payload, {
19
+ const { data: res } = await innerRequest<AudioClassificationOutput>(payload, {
20
20
  ...options,
21
21
  task: "audio-classification",
22
22
  });
@@ -1,6 +1,6 @@
1
1
  import { InferenceOutputError } from "../../lib/InferenceOutputError";
2
2
  import type { BaseArgs, Options } from "../../types";
3
- import { request } from "../custom/request";
3
+ import { innerRequest } from "../../utils/request";
4
4
  import type { LegacyAudioInput } from "./utils";
5
5
  import { preparePayload } from "./utils";
6
6
 
@@ -37,7 +37,7 @@ export interface AudioToAudioOutput {
37
37
  */
38
38
  export async function audioToAudio(args: AudioToAudioArgs, options?: Options): Promise<AudioToAudioOutput[]> {
39
39
  const payload = preparePayload(args);
40
- const res = await request<AudioToAudioOutput>(payload, {
40
+ const { data: res } = await innerRequest<AudioToAudioOutput>(payload, {
41
41
  ...options,
42
42
  task: "audio-to-audio",
43
43
  });
@@ -2,10 +2,10 @@ import type { AutomaticSpeechRecognitionInput, AutomaticSpeechRecognitionOutput
2
2
  import { InferenceOutputError } from "../../lib/InferenceOutputError";
3
3
  import type { BaseArgs, Options, RequestArgs } from "../../types";
4
4
  import { base64FromBytes } from "../../utils/base64FromBytes";
5
- import { request } from "../custom/request";
5
+ import { omit } from "../../utils/omit";
6
+ import { innerRequest } from "../../utils/request";
6
7
  import type { LegacyAudioInput } from "./utils";
7
8
  import { preparePayload } from "./utils";
8
- import { omit } from "../../utils/omit";
9
9
 
10
10
  export type AutomaticSpeechRecognitionArgs = BaseArgs & (AutomaticSpeechRecognitionInput | LegacyAudioInput);
11
11
  /**
@@ -17,7 +17,7 @@ export async function automaticSpeechRecognition(
17
17
  options?: Options
18
18
  ): Promise<AutomaticSpeechRecognitionOutput> {
19
19
  const payload = await buildPayload(args);
20
- const res = await request<AutomaticSpeechRecognitionOutput>(payload, {
20
+ const { data: res } = await innerRequest<AutomaticSpeechRecognitionOutput>(payload, {
21
21
  ...options,
22
22
  task: "automatic-speech-recognition",
23
23
  });
@@ -2,7 +2,7 @@ import type { TextToSpeechInput } from "@huggingface/tasks";
2
2
  import { InferenceOutputError } from "../../lib/InferenceOutputError";
3
3
  import type { BaseArgs, Options } from "../../types";
4
4
  import { omit } from "../../utils/omit";
5
- import { request } from "../custom/request";
5
+ import { innerRequest } from "../../utils/request";
6
6
  type TextToSpeechArgs = BaseArgs & TextToSpeechInput;
7
7
 
8
8
  interface OutputUrlTextToSpeechGeneration {
@@ -22,7 +22,7 @@ export async function textToSpeech(args: TextToSpeechArgs, options?: Options): P
22
22
  text: args.inputs,
23
23
  }
24
24
  : args;
25
- const res = await request<Blob | OutputUrlTextToSpeechGeneration>(payload, {
25
+ const { data: res } = await innerRequest<Blob | OutputUrlTextToSpeechGeneration>(payload, {
26
26
  ...options,
27
27
  task: "text-to-speech",
28
28
  });
@@ -1,8 +1,9 @@
1
1
  import type { InferenceTask, Options, RequestArgs } from "../../types";
2
- import { makeRequestOptions } from "../../lib/makeRequestOptions";
2
+ import { innerRequest } from "../../utils/request";
3
3
 
4
4
  /**
5
5
  * Primitive to make custom calls to the inference provider
6
+ * @deprecated Use specific task functions instead. This function will be removed in a future version.
6
7
  */
7
8
  export async function request<T>(
8
9
  args: RequestArgs,
@@ -13,35 +14,9 @@ export async function request<T>(
13
14
  chatCompletion?: boolean;
14
15
  }
15
16
  ): Promise<T> {
16
- const { url, info } = await makeRequestOptions(args, options);
17
- const response = await (options?.fetch ?? fetch)(url, info);
18
-
19
- if (options?.retry_on_error !== false && response.status === 503) {
20
- return request(args, options);
21
- }
22
-
23
- if (!response.ok) {
24
- const contentType = response.headers.get("Content-Type");
25
- if (["application/json", "application/problem+json"].some((ct) => contentType?.startsWith(ct))) {
26
- const output = await response.json();
27
- if ([400, 422, 404, 500].includes(response.status) && options?.chatCompletion) {
28
- throw new Error(
29
- `Server ${args.model} does not seem to support chat completion. Error: ${JSON.stringify(output.error)}`
30
- );
31
- }
32
- if (output.error || output.detail) {
33
- throw new Error(JSON.stringify(output.error ?? output.detail));
34
- } else {
35
- throw new Error(output);
36
- }
37
- }
38
- const message = contentType?.startsWith("text/plain;") ? await response.text() : undefined;
39
- throw new Error(message ?? "An error occurred while fetching the blob");
40
- }
41
-
42
- if (response.headers.get("Content-Type")?.startsWith("application/json")) {
43
- return await response.json();
44
- }
45
-
46
- return (await response.blob()) as T;
17
+ console.warn(
18
+ "The request method is deprecated and will be removed in a future version of huggingface.js. Use specific task functions instead."
19
+ );
20
+ const result = await innerRequest<T>(args, options);
21
+ return result.data;
47
22
  }
@@ -1,10 +1,8 @@
1
1
  import type { InferenceTask, Options, RequestArgs } from "../../types";
2
- import { makeRequestOptions } from "../../lib/makeRequestOptions";
3
- import type { EventSourceMessage } from "../../vendor/fetch-event-source/parse";
4
- import { getLines, getMessages } from "../../vendor/fetch-event-source/parse";
5
-
2
+ import { innerStreamingRequest } from "../../utils/request";
6
3
  /**
7
4
  * Primitive to make custom inference calls that expect server-sent events, and returns the response through a generator
5
+ * @deprecated Use specific task functions instead. This function will be removed in a future version.
8
6
  */
9
7
  export async function* streamingRequest<T>(
10
8
  args: RequestArgs,
@@ -15,86 +13,8 @@ export async function* streamingRequest<T>(
15
13
  chatCompletion?: boolean;
16
14
  }
17
15
  ): AsyncGenerator<T> {
18
- const { url, info } = await makeRequestOptions({ ...args, stream: true }, options);
19
- const response = await (options?.fetch ?? fetch)(url, info);
20
-
21
- if (options?.retry_on_error !== false && response.status === 503) {
22
- return yield* streamingRequest(args, options);
23
- }
24
- if (!response.ok) {
25
- if (response.headers.get("Content-Type")?.startsWith("application/json")) {
26
- const output = await response.json();
27
- if ([400, 422, 404, 500].includes(response.status) && options?.chatCompletion) {
28
- throw new Error(`Server ${args.model} does not seem to support chat completion. Error: ${output.error}`);
29
- }
30
- if (typeof output.error === "string") {
31
- throw new Error(output.error);
32
- }
33
- if (output.error && "message" in output.error && typeof output.error.message === "string") {
34
- /// OpenAI errors
35
- throw new Error(output.error.message);
36
- }
37
- }
38
-
39
- throw new Error(`Server response contains error: ${response.status}`);
40
- }
41
- if (!response.headers.get("content-type")?.startsWith("text/event-stream")) {
42
- throw new Error(
43
- `Server does not support event stream content type, it returned ` + response.headers.get("content-type")
44
- );
45
- }
46
-
47
- if (!response.body) {
48
- return;
49
- }
50
-
51
- const reader = response.body.getReader();
52
- let events: EventSourceMessage[] = [];
53
-
54
- const onEvent = (event: EventSourceMessage) => {
55
- // accumulate events in array
56
- events.push(event);
57
- };
58
-
59
- const onChunk = getLines(
60
- getMessages(
61
- () => {},
62
- () => {},
63
- onEvent
64
- )
16
+ console.warn(
17
+ "The streamingRequest method is deprecated and will be removed in a future version of huggingface.js. Use specific task functions instead."
65
18
  );
66
-
67
- try {
68
- while (true) {
69
- const { done, value } = await reader.read();
70
- if (done) {
71
- return;
72
- }
73
- onChunk(value);
74
- for (const event of events) {
75
- if (event.data.length > 0) {
76
- if (event.data === "[DONE]") {
77
- return;
78
- }
79
- const data = JSON.parse(event.data);
80
- if (typeof data === "object" && data !== null && "error" in data) {
81
- const errorStr =
82
- typeof data.error === "string"
83
- ? data.error
84
- : typeof data.error === "object" &&
85
- data.error &&
86
- "message" in data.error &&
87
- typeof data.error.message === "string"
88
- ? data.error.message
89
- : JSON.stringify(data.error);
90
- throw new Error(`Error forwarded from backend: ` + errorStr);
91
- }
92
- yield data as T;
93
- }
94
- }
95
- events = [];
96
- }
97
- } finally {
98
- reader.releaseLock();
99
- }
19
+ yield* innerStreamingRequest(args, options);
100
20
  }
@@ -1,7 +1,7 @@
1
1
  import type { ImageClassificationInput, ImageClassificationOutput } from "@huggingface/tasks";
2
2
  import { InferenceOutputError } from "../../lib/InferenceOutputError";
3
3
  import type { BaseArgs, Options } from "../../types";
4
- import { request } from "../custom/request";
4
+ import { innerRequest } from "../../utils/request";
5
5
  import { preparePayload, type LegacyImageInput } from "./utils";
6
6
 
7
7
  export type ImageClassificationArgs = BaseArgs & (ImageClassificationInput | LegacyImageInput);
@@ -15,7 +15,7 @@ export async function imageClassification(
15
15
  options?: Options
16
16
  ): Promise<ImageClassificationOutput> {
17
17
  const payload = preparePayload(args);
18
- const res = await request<ImageClassificationOutput>(payload, {
18
+ const { data: res } = await innerRequest<ImageClassificationOutput>(payload, {
19
19
  ...options,
20
20
  task: "image-classification",
21
21
  });
@@ -1,7 +1,7 @@
1
1
  import type { ImageSegmentationInput, ImageSegmentationOutput } from "@huggingface/tasks";
2
2
  import { InferenceOutputError } from "../../lib/InferenceOutputError";
3
3
  import type { BaseArgs, Options } from "../../types";
4
- import { request } from "../custom/request";
4
+ import { innerRequest } from "../../utils/request";
5
5
  import { preparePayload, type LegacyImageInput } from "./utils";
6
6
 
7
7
  export type ImageSegmentationArgs = BaseArgs & (ImageSegmentationInput | LegacyImageInput);
@@ -15,7 +15,7 @@ export async function imageSegmentation(
15
15
  options?: Options
16
16
  ): Promise<ImageSegmentationOutput> {
17
17
  const payload = preparePayload(args);
18
- const res = await request<ImageSegmentationOutput>(payload, {
18
+ const { data: res } = await innerRequest<ImageSegmentationOutput>(payload, {
19
19
  ...options,
20
20
  task: "image-segmentation",
21
21
  });
@@ -2,7 +2,7 @@ import type { ImageToImageInput } from "@huggingface/tasks";
2
2
  import { InferenceOutputError } from "../../lib/InferenceOutputError";
3
3
  import type { BaseArgs, Options, RequestArgs } from "../../types";
4
4
  import { base64FromBytes } from "../../utils/base64FromBytes";
5
- import { request } from "../custom/request";
5
+ import { innerRequest } from "../../utils/request";
6
6
 
7
7
  export type ImageToImageArgs = BaseArgs & ImageToImageInput;
8
8
 
@@ -26,7 +26,7 @@ export async function imageToImage(args: ImageToImageArgs, options?: Options): P
26
26
  ),
27
27
  };
28
28
  }
29
- const res = await request<Blob>(reqArgs, {
29
+ const { data: res } = await innerRequest<Blob>(reqArgs, {
30
30
  ...options,
31
31
  task: "image-to-image",
32
32
  });