@huggingface/inference 2.6.4 → 2.6.6

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.
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@huggingface/inference",
3
- "version": "2.6.4",
4
- "packageManager": "pnpm@8.3.1",
3
+ "version": "2.6.6",
4
+ "packageManager": "pnpm@8.10.5",
5
5
  "license": "MIT",
6
6
  "author": "Tim Mikeladze <tim.mikeladze@gmail.com>",
7
- "description": "Typescript wrapper for the Hugging Face Inference API",
7
+ "description": "Typescript wrapper for the Hugging Face Inference Endpoints & Inference API",
8
8
  "repository": {
9
9
  "type": "git",
10
10
  "url": "https://github.com/huggingface/huggingface.js.git"
@@ -30,30 +30,28 @@
30
30
  ],
31
31
  "source": "src/index.ts",
32
32
  "types": "./dist/index.d.ts",
33
- "main": "./dist/index.js",
34
- "module": "./dist/index.mjs",
33
+ "main": "./dist/index.cjs",
34
+ "module": "./dist/index.js",
35
35
  "exports": {
36
36
  "types": "./dist/index.d.ts",
37
- "require": "./dist/index.js",
38
- "import": "./dist/index.mjs"
37
+ "require": "./dist/index.cjs",
38
+ "import": "./dist/index.js"
39
39
  },
40
+ "type": "module",
40
41
  "devDependencies": {
41
42
  "@types/node": "18.13.0",
42
- "ts-node": "^10.9.1",
43
- "typescript": "^5.0.4",
44
- "vite": "^4.1.4",
45
- "vitest": "^0.29.8"
43
+ "@huggingface/tasks": "^0.6.0"
46
44
  },
47
45
  "resolutions": {},
48
46
  "scripts": {
49
47
  "build": "tsup src/index.ts --format cjs,esm --clean && pnpm run dts",
50
- "dts": "ts-node scripts/generate-dts.ts",
48
+ "dts": "tsx scripts/generate-dts.ts",
51
49
  "lint": "eslint --quiet --fix --ext .cjs,.ts .",
52
50
  "lint:check": "eslint --ext .cjs,.ts .",
53
51
  "format": "prettier --write .",
54
52
  "format:check": "prettier --check .",
55
- "test": "vitest run --config vitest.config.ts",
56
- "test:browser": "vitest run --browser.name=chrome --browser.headless --config vitest.config.ts",
57
- "type-check": "tsc"
53
+ "test": "vitest run --config vitest.config.mts",
54
+ "test:browser": "vitest run --browser.name=chrome --browser.headless --config vitest.config.mts",
55
+ "check": "tsc"
58
56
  }
59
57
  }
@@ -2,7 +2,7 @@ import { isUrl } from "./isUrl";
2
2
 
3
3
  /**
4
4
  * We want to make calls to the huggingface hub the least possible, eg if
5
- * someone is calling the inference API 1000 times per second, we don't want
5
+ * someone is calling Inference Endpoints 1000 times per second, we don't want
6
6
  * to make 1000 calls to the hub to get the task name.
7
7
  */
8
8
  const taskCache = new Map<string, { task: string; date: Date }>();
@@ -27,7 +27,15 @@ export async function makeRequestOptions(
27
27
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
28
28
  const { accessToken, model: _model, ...otherArgs } = args;
29
29
  let { model } = args;
30
- const { forceTask: task, includeCredentials, taskHint, ...otherOptions } = options ?? {};
30
+ const {
31
+ forceTask: task,
32
+ includeCredentials,
33
+ taskHint,
34
+ wait_for_model,
35
+ use_cache,
36
+ dont_load_model,
37
+ ...otherOptions
38
+ } = options ?? {};
31
39
 
32
40
  const headers: Record<string, string> = {};
33
41
  if (accessToken) {
@@ -57,16 +65,16 @@ export async function makeRequestOptions(
57
65
 
58
66
  if (!binary) {
59
67
  headers["Content-Type"] = "application/json";
60
- } else {
61
- if (options?.wait_for_model) {
62
- headers["X-Wait-For-Model"] = "true";
63
- }
64
- if (options?.use_cache === false) {
65
- headers["X-Use-Cache"] = "false";
66
- }
67
- if (options?.dont_load_model) {
68
- headers["X-Load-Model"] = "0";
69
- }
68
+ }
69
+
70
+ if (wait_for_model) {
71
+ headers["X-Wait-For-Model"] = "true";
72
+ }
73
+ if (use_cache === false) {
74
+ headers["X-Use-Cache"] = "false";
75
+ }
76
+ if (dont_load_model) {
77
+ headers["X-Load-Model"] = "0";
70
78
  }
71
79
 
72
80
  const url = (() => {
@@ -2,7 +2,7 @@ import type { InferenceTask, Options, RequestArgs } from "../../types";
2
2
  import { makeRequestOptions } from "../../lib/makeRequestOptions";
3
3
 
4
4
  /**
5
- * Primitive to make custom calls to the inference API
5
+ * Primitive to make custom calls to Inference Endpoints
6
6
  */
7
7
  export async function request<T>(
8
8
  args: RequestArgs,
@@ -19,7 +19,7 @@ export async function* streamingRequest<T>(
19
19
  const response = await (options?.fetch ?? fetch)(url, info);
20
20
 
21
21
  if (options?.retry_on_error !== false && response.status === 503 && !options?.wait_for_model) {
22
- return streamingRequest(args, {
22
+ return yield* streamingRequest(args, {
23
23
  ...options,
24
24
  wait_for_model: true,
25
25
  });
@@ -18,7 +18,6 @@ export * from "./cv/imageToImage";
18
18
  export * from "./cv/zeroShotImageClassification";
19
19
 
20
20
  // Natural Language Processing tasks
21
- export * from "./nlp/conversational";
22
21
  export * from "./nlp/featureExtraction";
23
22
  export * from "./nlp/fillMask";
24
23
  export * from "./nlp/questionAnswering";
@@ -1,71 +1,15 @@
1
+ import type { TextGenerationInput, TextGenerationOutput } from "@huggingface/tasks/src/tasks/text-generation/inference";
1
2
  import { InferenceOutputError } from "../../lib/InferenceOutputError";
2
3
  import type { BaseArgs, Options } from "../../types";
3
4
  import { request } from "../custom/request";
4
5
 
5
- export type TextGenerationArgs = BaseArgs & {
6
- /**
7
- * A string to be generated from
8
- */
9
- inputs: string;
10
- parameters?: {
11
- /**
12
- * (Optional: True). Bool. Whether or not to use sampling, use greedy decoding otherwise.
13
- */
14
- do_sample?: boolean;
15
- /**
16
- * (Default: None). Int (0-250). The amount of new tokens to be generated, this does not include the input length it is a estimate of the size of generated text you want. Each new tokens slows down the request, so look for balance between response times and length of text generated.
17
- */
18
- max_new_tokens?: number;
19
- /**
20
- * (Default: None). Float (0-120.0). The amount of time in seconds that the query should take maximum. Network can cause some overhead so it will be a soft limit. Use that in combination with max_new_tokens for best results.
21
- */
22
- max_time?: number;
23
- /**
24
- * (Default: 1). Integer. The number of proposition you want to be returned.
25
- */
26
- num_return_sequences?: number;
27
- /**
28
- * (Default: None). Float (0.0-100.0). The more a token is used within generation the more it is penalized to not be picked in successive generation passes.
29
- */
30
- repetition_penalty?: number;
31
- /**
32
- * (Default: True). Bool. If set to False, the return results will not contain the original query making it easier for prompting.
33
- */
34
- return_full_text?: boolean;
35
- /**
36
- * (Default: 1.0). Float (0.0-100.0). The temperature of the sampling operation. 1 means regular sampling, 0 means always take the highest score, 100.0 is getting closer to uniform probability.
37
- */
38
- temperature?: number;
39
- /**
40
- * (Default: None). Integer to define the top tokens considered within the sample operation to create new text.
41
- */
42
- top_k?: number;
43
- /**
44
- * (Default: None). Float to define the tokens that are within the sample operation of text generation. Add tokens in the sample for more probable to least probable until the sum of the probabilities is greater than top_p.
45
- */
46
- top_p?: number;
47
- /**
48
- * (Default: None). Integer. The maximum number of tokens from the input.
49
- */
50
- truncate?: number;
51
- /**
52
- * (Default: []) List of strings. The model will stop generating text when one of the strings in the list is generated.
53
- * **/
54
- stop_sequences?: string[];
55
- };
56
- };
57
-
58
- export interface TextGenerationOutput {
59
- /**
60
- * The continuated string
61
- */
62
- generated_text: string;
63
- }
64
-
65
6
  /**
66
7
  * Use to continue text from a prompt. This is a very generic task. Recommended model: gpt2 (it’s a simple model, but fun to play with).
67
8
  */
68
- export async function textGeneration(args: TextGenerationArgs, options?: Options): Promise<TextGenerationOutput> {
9
+ export async function textGeneration(
10
+ args: BaseArgs & TextGenerationInput,
11
+ options?: Options
12
+ ): Promise<TextGenerationOutput> {
69
13
  const res = await request<TextGenerationOutput[]>(args, {
70
14
  ...options,
71
15
  taskHint: "text-generation",
@@ -1,6 +1,7 @@
1
- import type { Options } from "../../types";
1
+ import type { BaseArgs, Options } from "../../types";
2
2
  import { streamingRequest } from "../custom/streamingRequest";
3
- import type { TextGenerationArgs } from "./textGeneration";
3
+
4
+ import type { TextGenerationInput } from "@huggingface/tasks/src/tasks/text-generation/inference";
4
5
 
5
6
  export interface TextGenerationStreamToken {
6
7
  /** Token ID from the model tokenizer */
@@ -85,7 +86,7 @@ export interface TextGenerationStreamOutput {
85
86
  * Use to continue text from a prompt. Same as `textGeneration` but returns generator that can be read one token at a time
86
87
  */
87
88
  export async function* textGenerationStream(
88
- args: TextGenerationArgs,
89
+ args: BaseArgs & TextGenerationInput,
89
90
  options?: Options
90
91
  ): AsyncGenerator<TextGenerationStreamOutput> {
91
92
  yield* streamingRequest<TextGenerationStreamOutput>(args, {
@@ -6,21 +6,23 @@ export type TranslationArgs = BaseArgs & {
6
6
  /**
7
7
  * A string to be translated
8
8
  */
9
- inputs: string;
9
+ inputs: string | string[];
10
10
  };
11
11
 
12
- export interface TranslationOutput {
12
+ export interface TranslationOutputValue {
13
13
  /**
14
14
  * The string after translation
15
15
  */
16
16
  translation_text: string;
17
17
  }
18
18
 
19
+ export type TranslationOutput = TranslationOutputValue | TranslationOutputValue[];
20
+
19
21
  /**
20
22
  * This task is well known to translate text from one language to another. Recommended model: Helsinki-NLP/opus-mt-ru-en.
21
23
  */
22
24
  export async function translation(args: TranslationArgs, options?: Options): Promise<TranslationOutput> {
23
- const res = await request<TranslationOutput[]>(args, {
25
+ const res = await request<TranslationOutputValue[]>(args, {
24
26
  ...options,
25
27
  taskHint: "translation",
26
28
  });
@@ -28,5 +30,5 @@ export async function translation(args: TranslationArgs, options?: Options): Pro
28
30
  if (!isValidOutput) {
29
31
  throw new InferenceOutputError("Expected type Array<{translation_text: string}>");
30
32
  }
31
- return res?.[0];
33
+ return res?.length === 1 ? res?.[0] : res;
32
34
  }
package/src/types.ts CHANGED
@@ -1,10 +1,12 @@
1
+ import type { PipelineType } from "@huggingface/tasks";
2
+
1
3
  export interface Options {
2
4
  /**
3
5
  * (Default: true) Boolean. If a request 503s and wait_for_model is set to false, the request will be retried with the same parameters but with wait_for_model set to true.
4
6
  */
5
7
  retry_on_error?: boolean;
6
8
  /**
7
- * (Default: true). Boolean. There is a cache layer on the inference API to speedup requests we have already seen. Most models can use those results as is as models are deterministic (meaning the results will be the same anyway). However if you use a non deterministic model, you can set this parameter to prevent the caching mechanism from being used resulting in a real new query.
9
+ * (Default: true). Boolean. There is a cache layer on Inference API (serverless) to speedup requests we have already seen. Most models can use those results as is as models are deterministic (meaning the results will be the same anyway). However if you use a non deterministic model, you can set this parameter to prevent the caching mechanism from being used resulting in a real new query.
8
10
  */
9
11
  use_cache?: boolean;
10
12
  /**
@@ -35,39 +37,7 @@ export interface Options {
35
37
  includeCredentials?: string | boolean;
36
38
  }
37
39
 
38
- export type InferenceTask =
39
- | "audio-classification"
40
- | "audio-to-audio"
41
- | "automatic-speech-recognition"
42
- | "conversational"
43
- | "depth-estimation"
44
- | "document-question-answering"
45
- | "feature-extraction"
46
- | "fill-mask"
47
- | "image-classification"
48
- | "image-segmentation"
49
- | "image-to-image"
50
- | "image-to-text"
51
- | "object-detection"
52
- | "video-classification"
53
- | "question-answering"
54
- | "reinforcement-learning"
55
- | "sentence-similarity"
56
- | "summarization"
57
- | "table-question-answering"
58
- | "tabular-classification"
59
- | "tabular-regression"
60
- | "text-classification"
61
- | "text-generation"
62
- | "text-to-image"
63
- | "text-to-speech"
64
- | "text-to-video"
65
- | "token-classification"
66
- | "translation"
67
- | "unconditional-image-generation"
68
- | "visual-question-answering"
69
- | "zero-shot-classification"
70
- | "zero-shot-image-classification";
40
+ export type InferenceTask = Exclude<PipelineType, "other">;
71
41
 
72
42
  export interface BaseArgs {
73
43
  /**
@@ -77,7 +47,7 @@ export interface BaseArgs {
77
47
  */
78
48
  accessToken?: string;
79
49
  /**
80
- * The model to use. Can be a full URL for HF inference endpoints.
50
+ * The model to use. Can be a full URL for a dedicated inference endpoint.
81
51
  *
82
52
  * If not specified, will call huggingface.co/api/tasks to get the default model for the task.
83
53
  */
@@ -1,81 +0,0 @@
1
- import { InferenceOutputError } from "../../lib/InferenceOutputError";
2
- import type { BaseArgs, Options } from "../../types";
3
- import { request } from "../custom/request";
4
-
5
- export type ConversationalArgs = BaseArgs & {
6
- inputs: {
7
- /**
8
- * A list of strings corresponding to the earlier replies from the model.
9
- */
10
- generated_responses?: string[];
11
- /**
12
- * A list of strings corresponding to the earlier replies from the user. Should be of the same length of generated_responses.
13
- */
14
- past_user_inputs?: string[];
15
- /**
16
- * The last input from the user in the conversation.
17
- */
18
- text: string;
19
- };
20
- parameters?: {
21
- /**
22
- * (Default: None). Integer to define the maximum length in tokens of the output summary.
23
- */
24
- max_length?: number;
25
- /**
26
- * (Default: None). Float (0-120.0). The amount of time in seconds that the query should take maximum. Network can cause some overhead so it will be a soft limit.
27
- */
28
- max_time?: number;
29
- /**
30
- * (Default: None). Integer to define the minimum length in tokens of the output summary.
31
- */
32
- min_length?: number;
33
- /**
34
- * (Default: None). Float (0.0-100.0). The more a token is used within generation the more it is penalized to not be picked in successive generation passes.
35
- */
36
- repetition_penalty?: number;
37
- /**
38
- * (Default: 1.0). Float (0.0-100.0). The temperature of the sampling operation. 1 means regular sampling, 0 means always take the highest score, 100.0 is getting closer to uniform probability.
39
- */
40
- temperature?: number;
41
- /**
42
- * (Default: None). Integer to define the top tokens considered within the sample operation to create new text.
43
- */
44
- top_k?: number;
45
- /**
46
- * (Default: None). Float to define the tokens that are within the sample operation of text generation. Add tokens in the sample for more probable to least probable until the sum of the probabilities is greater than top_p.
47
- */
48
- top_p?: number;
49
- };
50
- };
51
-
52
- export interface ConversationalOutput {
53
- conversation: {
54
- generated_responses: string[];
55
- past_user_inputs: string[];
56
- };
57
- generated_text: string;
58
- warnings: string[];
59
- }
60
-
61
- /**
62
- * This task corresponds to any chatbot like structure. Models tend to have shorter max_length, so please check with caution when using a given model if you need long range dependency or not. Recommended model: microsoft/DialoGPT-large.
63
- *
64
- */
65
- export async function conversational(args: ConversationalArgs, options?: Options): Promise<ConversationalOutput> {
66
- const res = await request<ConversationalOutput>(args, { ...options, taskHint: "conversational" });
67
- const isValidOutput =
68
- Array.isArray(res.conversation.generated_responses) &&
69
- res.conversation.generated_responses.every((x) => typeof x === "string") &&
70
- Array.isArray(res.conversation.past_user_inputs) &&
71
- res.conversation.past_user_inputs.every((x) => typeof x === "string") &&
72
- typeof res.generated_text === "string" &&
73
- (typeof res.warnings === "undefined" ||
74
- (Array.isArray(res.warnings) && res.warnings.every((x) => typeof x === "string")));
75
- if (!isValidOutput) {
76
- throw new InferenceOutputError(
77
- "Expected {conversation: {generated_responses: string[], past_user_inputs: string[]}, generated_text: string, warnings: string[]}"
78
- );
79
- }
80
- return res;
81
- }