Skip to main content
本示例介绍如何从 GitHub 仓库加载数据。 您可以将 GITHUB_ACCESS_TOKEN 环境变量设置为 GitHub 访问令牌,以提高速率限制并访问私有仓库。

设置

GitHub 加载器需要 ignore npm 包 作为对等依赖项。安装方法如下:
npm
npm install @langchain/community @langchain/core ignore

用法

import { GithubRepoLoader } from "@langchain/community/document_loaders/web/github";

export const run = async () => {
  const loader = new GithubRepoLoader(
    "https://github.com/langchain-ai/langchainjs",
    {
      branch: "main",
      recursive: false,
      unknown: "warn",
      maxConcurrency: 5, // 默认为 2
    }
  );
  const docs = await loader.load();
  console.log({ docs });
};
加载器将忽略二进制文件,如图像。

使用 .gitignore 语法

要忽略特定文件,可以将 ignorePaths 数组传递给构造函数:
import { GithubRepoLoader } from "@langchain/community/document_loaders/web/github";

export const run = async () => {
  const loader = new GithubRepoLoader(
    "https://github.com/langchain-ai/langchainjs",
    { branch: "main", recursive: false, unknown: "warn", ignorePaths: ["*.md"] }
  );
  const docs = await loader.load();
  console.log({ docs });
  // 将不包含任何 .md 文件
};

使用不同的 GitHub 实例

您可能希望针对与 github.com 不同的 GitHub 实例,例如,如果您的公司有 GitHub Enterprise 实例。 为此,您需要两个额外的参数:
  • baseUrl - 您的 GitHub 实例的基本 URL,因此 githubUrl 匹配 <baseUrl>/<owner>/<repo>/...
  • apiUrl - 您的 GitHub 实例的 API 端点 URL
import { GithubRepoLoader } from "@langchain/community/document_loaders/web/github";

export const run = async () => {
  const loader = new GithubRepoLoader(
    "https://github.your.company/org/repo-name",
    {
      baseUrl: "https://github.your.company",
      apiUrl: "https://github.your.company/api/v3",
      accessToken: "ghp_A1B2C3D4E5F6a7b8c9d0",
      branch: "main",
      recursive: true,
      unknown: "warn",
    }
  );
  const docs = await loader.load();
  console.log({ docs });
};

处理子模块

如果您的仓库有子模块,您必须决定加载器是否应跟随它们。您可以使用布尔值 processSubmodules 参数进行控制。默认情况下,子模块不会被处理。 请注意,处理子模块仅在与将 recursive 参数设置为 true 时结合使用才有效。
import { GithubRepoLoader } from "@langchain/community/document_loaders/web/github";

export const run = async () => {
  const loader = new GithubRepoLoader(
    "https://github.com/langchain-ai/langchainjs",
    {
      branch: "main",
      recursive: true,
      processSubmodules: true,
      unknown: "warn",
    }
  );
  const docs = await loader.load();
  console.log({ docs });
};
请注意,加载器不会跟随位于与当前仓库不同的 GitHub 实例上的子模块。

流式处理大型仓库

在需要以内存高效的方式处理大型仓库的情况下。您可以使用 loadAsStream 方法异步流式传输整个 GitHub 仓库的文档。
import { GithubRepoLoader } from "@langchain/community/document_loaders/web/github";

export const run = async () => {
  const loader = new GithubRepoLoader(
    "https://github.com/langchain-ai/langchainjs",
    {
      branch: "main",
      recursive: false,
      unknown: "warn",
      maxConcurrency: 3, // 默认为 2
    }
  );

  const docs = [];
  for await (const doc of loader.loadAsStream()) {
    docs.push(doc);
  }

  console.log({ docs });
};