Huggingface.js 文档

🤗 Hugging Face Agents.js

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

🤗 Hugging Face Agents.js

一种使用 LLM 从自然语言调用 Hugging Face 模型和 Inference Endpoints 的方法。

安装

pnpm add @huggingface/agents

npm add @huggingface/agents

yarn add @huggingface/agents

Deno

// esm.sh
import { HfAgent } from "https://esm.sh/@huggingface/agent"
// or npm:
import { HfAgent } from "npm:@huggingface/agent"

使用方法

Agents.js 利用 HF 上托管为 Inference Endpoints 的 LLM,因此你需要创建一个帐户并生成一个 访问令牌

import { HfAgent } from "@huggingface/agents";

const agent = new HfAgent("hf_...");

const code = await agent.generateCode("Draw a picture of a cat, wearing a top hat.")
console.log(code) // always good to check the generated code before running it
const outputs = await agent.evaluateCode(code);
console.log(outputs) 

选择你的 LLM

你也可以通过调用 LLMFrom* 函数之一来使用你自己的 LLM。

从 Hub 中获取

你可以指定 Hub 上的任何有效模型,只要它们有 API 即可。

import { HfAgent, LLMFromHub } from "@huggingface/agents";

const agent = new HfAgent(
  "hf_...",
  LLMFromHub("hf_...", "OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5")
);

从你自己的端点获取

你也可以指定你自己的端点,只要它实现了相同的 API,例如使用 text generation inferenceInference Endpoints

import { HfAgent, LLMFromEndpoint } from "@huggingface/agents";

const agent = new HfAgent(
  "hf_...",
  LLMFromEndpoint("hf_...", "http://...")
);

自定义 LLM

在这种上下文中,LLM 被定义为任何接受字符串输入并返回字符串的异步函数。例如,如果你想使用 OpenAI API,你可以这样做:

import { HfAgent } from "@huggingface/agents";
import { Configuration, OpenAIApi } from "openai";

const api = new OpenAIApi(new Configuration({ apiKey: "sk-..." }));

const llmOpenAI = async (prompt: string): Promise<string> => {
  return (
    (
      await api.createCompletion({
        model: "text-davinci-003",
        prompt: prompt,
        max_tokens: 1000,
      })
    ).data.choices[0].text ?? ""
  );
};

const agent = new HfAgent(
  "hf_...",
  llmOpenAI
);

// do anything you want with the agent here

工具

默认情况下,agents 附带 4 个工具。(textToImage、textToSpeech、imageToText、speechToText)

但是你可以通过创建新工具并在初始化时传递它们来轻松扩展工具列表。

import { HfAgent, defaultTools, LLMFromHub } from "@huggingface/agents";
import type { Tool } from "@huggingface/agents/src/types";

// define the tool
const uppercaseTool: Tool = {
    name: "uppercase",
    description: "uppercase the input string and returns it ",
    examples: [
        {
            prompt: "uppercase the string: hello world",
            code: `const output = uppercase("hello world")`,
            tools: ["uppercase"],
        },
    ],
    call: async (input) => {
        const data = await input;
        if (typeof data !== "string") {
            throw new Error("Input must be a string");
        }
        return data.toUpperCase();
    },
};

// pass it in the agent
const agent = new HfAgent(process.env.HF_TOKEN,
                LLMFromHub("hf_...", "OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5"),
                [uppercaseTool, ...defaultTools]);

依赖项

  • @huggingface/inference:调用推理端点本身所必需。
< > 在 GitHub 上更新