index
int64 0
0
| repo_id
stringclasses 596
values | file_path
stringlengths 31
168
| content
stringlengths 1
6.2M
|
|---|---|---|---|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-azure-dynamic-sessions/jest.config.cjs
|
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: "ts-jest/presets/default-esm",
testEnvironment: "./jest.env.cjs",
modulePathIgnorePatterns: ["dist/", "docs/"],
moduleNameMapper: {
"^(\\.{1,2}/.*)\\.js$": "$1",
},
transform: {
"^.+\\.tsx?$": ["@swc/jest"],
},
transformIgnorePatterns: [
"/node_modules/",
"\\.pnp\\.[^\\/]+$",
"./scripts/jest-setup-after-env.js",
],
setupFiles: ["dotenv/config"],
testTimeout: 20_000,
passWithNoTests: true,
collectCoverageFrom: ["src/**/*.ts"],
};
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-azure-dynamic-sessions/jest.env.cjs
|
const { TestEnvironment } = require("jest-environment-node");
class AdjustedTestEnvironmentToSupportFloat32Array extends TestEnvironment {
constructor(config, context) {
// Make `instanceof Float32Array` return true in tests
// to avoid https://github.com/xenova/transformers.js/issues/57 and https://github.com/jestjs/jest/issues/2549
super(config, context);
this.global.Float32Array = Float32Array;
}
}
module.exports = AdjustedTestEnvironmentToSupportFloat32Array;
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-azure-dynamic-sessions/README.md
|
# @langchain/azure-dynamic-sessions
This package contains the [Azure Container Apps dynamic sessions](https://learn.microsoft.com/azure/container-apps/sessions) tool integration.
Learn more about how to use this tool in the [LangChain documentation](https://js.langchain.com/docs/integrations/tools/azure_dynamic_sessions).
## Installation
```bash npm2yarn
npm install @langchain/azure-dynamic-sessions @langchain/core
```
This package, along with the main LangChain package, depends on [`@langchain/core`](https://npmjs.com/package/@langchain/core/).
If you are using this package with other LangChain packages, you should make sure that all of the packages depend on the same instance of @langchain/core.
You can do so by adding appropriate fields to your project's `package.json` like this:
```json
{
"name": "your-project",
"version": "0.0.0",
"dependencies": {
"@langchain/azure-openai": "^0.0.4",
"@langchain/core": "^0.3.0"
},
"resolutions": {
"@langchain/core": "^0.3.0"
},
"overrides": {
"@langchain/core": "^0.3.0"
},
"pnpm": {
"overrides": {
"@langchain/core": "^0.3.0"
}
}
}
```
The field you need depends on the package manager you're using, but we recommend adding a field for the common `yarn`, `npm`, and `pnpm` to maximize compatibility.
## Tool usage
```typescript
import { SessionsPythonREPLTool } from "@langchain/azure-dynamic-sessions";
const tool = new SessionsPythonREPLTool({
poolManagementEndpoint:
process.env.AZURE_CONTAINER_APP_SESSION_POOL_MANAGEMENT_ENDPOINT || "",
});
const result = await tool.invoke("print('Hello, World!')\n1+2");
console.log(result);
// {
// stdout: "Hello, World!\n",
// stderr: "",
// result: 3,
// }
```
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-azure-dynamic-sessions/.release-it.json
|
{
"github": {
"release": true,
"autoGenerate": true,
"tokenRef": "GITHUB_TOKEN_RELEASE"
},
"npm": {
"versionArgs": ["--workspaces-update=false"]
}
}
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-azure-dynamic-sessions/.eslintrc.cjs
|
module.exports = {
extends: [
"airbnb-base",
"eslint:recommended",
"prettier",
"plugin:@typescript-eslint/recommended",
],
parserOptions: {
ecmaVersion: 12,
parser: "@typescript-eslint/parser",
project: "./tsconfig.json",
sourceType: "module",
},
plugins: ["@typescript-eslint", "no-instanceof"],
ignorePatterns: [
".eslintrc.cjs",
"scripts",
"node_modules",
"dist",
"dist-cjs",
"*.js",
"*.cjs",
"*.d.ts",
],
rules: {
"no-process-env": 2,
"no-instanceof/no-instanceof": 2,
"@typescript-eslint/explicit-module-boundary-types": 0,
"@typescript-eslint/no-empty-function": 0,
"@typescript-eslint/no-shadow": 0,
"@typescript-eslint/no-empty-interface": 0,
"@typescript-eslint/no-use-before-define": ["error", "nofunc"],
"@typescript-eslint/no-unused-vars": ["warn", { args: "none" }],
"@typescript-eslint/no-floating-promises": "error",
"@typescript-eslint/no-misused-promises": "error",
camelcase: 0,
"class-methods-use-this": 0,
"import/extensions": [2, "ignorePackages"],
"import/no-extraneous-dependencies": [
"error",
{ devDependencies: ["**/*.test.ts"] },
],
"import/no-unresolved": 0,
"import/prefer-default-export": 0,
"keyword-spacing": "error",
"max-classes-per-file": 0,
"max-len": 0,
"no-await-in-loop": 0,
"no-bitwise": 0,
"no-console": 0,
"no-restricted-syntax": 0,
"no-shadow": 0,
"no-continue": 0,
"no-void": 0,
"no-underscore-dangle": 0,
"no-use-before-define": 0,
"no-useless-constructor": 0,
"no-return-await": 0,
"consistent-return": 0,
"no-else-return": 0,
"func-names": 0,
"no-lonely-if": 0,
"prefer-rest-params": 0,
"new-cap": ["error", { properties: false, capIsNew: false }],
},
};
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-azure-dynamic-sessions/langchain.config.js
|
import { resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url";
/**
* @param {string} relativePath
* @returns {string}
*/
function abs(relativePath) {
return resolve(dirname(fileURLToPath(import.meta.url)), relativePath);
}
export const config = {
internals: [/node\:/, /@langchain\/core\//],
entrypoints: {
index: "index",
},
requiresOptionalDependency: [],
tsConfigPath: resolve("./tsconfig.json"),
cjsSource: "./dist-cjs",
cjsDestination: "./dist",
abs,
};
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-azure-dynamic-sessions/.env.example
|
# Azure Container App Session Pool Management Endpoint
AZURE_CONTAINER_APP_SESSION_POOL_MANAGEMENT_ENDPOINT=<your-endpoint>
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-azure-dynamic-sessions/package.json
|
{
"name": "@langchain/azure-dynamic-sessions",
"version": "0.2.0",
"description": "Sample integration for LangChain.js",
"type": "module",
"engines": {
"node": ">=18"
},
"main": "./index.js",
"types": "./index.d.ts",
"repository": {
"type": "git",
"url": "git@github.com:langchain-ai/langchainjs.git"
},
"homepage": "https://github.com/langchain-ai/langchainjs/tree/main/libs/langchain-INTEGRATION_NAME/",
"scripts": {
"build": "yarn turbo:command build:internal --filter=@langchain/azure-dynamic-sessions",
"build:internal": "yarn lc_build --create-entrypoints --pre --tree-shaking",
"lint:eslint": "NODE_OPTIONS=--max-old-space-size=4096 eslint --cache --ext .ts,.js src/",
"lint:dpdm": "dpdm --exit-code circular:1 --no-warning --no-tree src/*.ts src/**/*.ts",
"lint": "yarn lint:eslint && yarn lint:dpdm",
"lint:fix": "yarn lint:eslint --fix && yarn lint:dpdm",
"clean": "rm -rf .turbo dist/",
"prepack": "yarn build",
"test": "NODE_OPTIONS=--experimental-vm-modules jest --testPathIgnorePatterns=\\.int\\.test.ts --testTimeout 30000 --maxWorkers=50%",
"test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch --testPathIgnorePatterns=\\.int\\.test.ts",
"test:single": "NODE_OPTIONS=--experimental-vm-modules yarn run jest --config jest.config.cjs --testTimeout 100000",
"test:int": "NODE_OPTIONS=--experimental-vm-modules jest --testPathPattern=\\.int\\.test.ts --testTimeout 100000 --maxWorkers=50%",
"format": "prettier --config .prettierrc --write \"src\"",
"format:check": "prettier --config .prettierrc --check \"src\""
},
"author": "LangChain",
"license": "MIT",
"dependencies": {
"@azure/identity": "^4.2.1",
"uuid": "^10.0.0"
},
"peerDependencies": {
"@langchain/core": ">=0.2.21 <0.4.0"
},
"devDependencies": {
"@jest/globals": "^29.5.0",
"@langchain/core": "workspace:*",
"@langchain/scripts": ">=0.1.0 <0.2.0",
"@swc/core": "^1.3.90",
"@swc/jest": "^0.2.29",
"@tsconfig/recommended": "^1.0.3",
"@types/uuid": "^9",
"@typescript-eslint/eslint-plugin": "^6.12.0",
"@typescript-eslint/parser": "^6.12.0",
"dotenv": "^16.4.5",
"dpdm": "^3.12.0",
"eslint": "^8.33.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-prettier": "^8.6.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-no-instanceof": "^1.0.1",
"eslint-plugin-prettier": "^4.2.1",
"jest": "^29.5.0",
"jest-environment-node": "^29.6.4",
"prettier": "^2.8.3",
"release-it": "^17.6.0",
"rollup": "^4.5.2",
"ts-jest": "^29.1.0",
"typescript": "<5.2.0"
},
"publishConfig": {
"access": "public"
},
"exports": {
".": {
"types": {
"import": "./index.d.ts",
"require": "./index.d.cts",
"default": "./index.d.ts"
},
"import": "./index.js",
"require": "./index.cjs"
},
"./package.json": "./package.json"
},
"files": [
"dist/",
"index.cjs",
"index.js",
"index.d.ts",
"index.d.cts"
]
}
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-azure-dynamic-sessions/tsconfig.cjs.json
|
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs",
"declaration": false
},
"exclude": ["node_modules", "dist", "docs", "**/tests"]
}
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-azure-dynamic-sessions/.prettierrc
|
{
"$schema": "https://json.schemastore.org/prettierrc",
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": false,
"quoteProps": "as-needed",
"jsxSingleQuote": false,
"trailingComma": "es5",
"bracketSpacing": true,
"arrowParens": "always",
"requirePragma": false,
"insertPragma": false,
"proseWrap": "preserve",
"htmlWhitespaceSensitivity": "css",
"vueIndentScriptAndStyle": false,
"endOfLine": "lf"
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-azure-dynamic-sessions
|
lc_public_repos/langchainjs/libs/langchain-azure-dynamic-sessions/src/tools.ts
|
import { Tool } from "@langchain/core/tools";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import {
DefaultAzureCredential,
getBearerTokenProvider,
} from "@azure/identity";
import { v4 as uuidv4 } from "uuid";
const userAgentPrefix = "langchainjs-azure-dynamic-sessions";
let userAgent = "";
async function getUserAgentSuffix(): Promise<string> {
if (!userAgent) {
userAgent = `${userAgentPrefix} (Language=JavaScript; node.js/${process.version}; ${process.platform}; ${process.arch})`;
}
return userAgent;
}
export interface SessionsPythonREPLToolParams {
/**
* The endpoint of the pool management service.
*/
poolManagementEndpoint: string;
/**
* The session ID. If not provided, a new session ID will be generated.
*/
sessionId?: string;
/**
* A function that returns the access token to be used for authentication.
* If not provided, a default implementation that uses the DefaultAzureCredential
* will be used.
*
* @returns The access token to be used for authentication.
*/
azureADTokenProvider?: () => Promise<string>;
}
export interface RemoteFile {
/**
* The filename of the file.
*/
filename: string;
/**
* The size of the file in bytes.
*/
size: number;
/**
* The last modified time of the file.
*/
last_modified_time: string;
/**
* The identifier of the file.
*/
$id: string;
}
export class SessionsPythonREPLTool extends Tool {
static lc_name() {
return "SessionsPythonREPLTool";
}
lc_serializable = true;
get lc_secrets(): { [key: string]: string } | undefined {
return {
poolManagementEndpoint:
"AZURE_CONTAINER_APP_SESSION_POOL_MANAGEMENT_ENDPOINT",
};
}
get lc_aliases(): Record<string, string> {
return {
poolManagementEndpoint: "pool_management_endpoint",
sessionId: "session_id",
};
}
name = "sessions-python-repl-tool";
description =
"A Python shell. Use this to execute python commands " +
"when you need to perform calculations or computations. " +
"Input should be a valid python command. " +
"Returns the result, stdout, and stderr. ";
poolManagementEndpoint: string;
sessionId: string;
azureADTokenProvider: () => Promise<string>;
constructor(params?: SessionsPythonREPLToolParams) {
super();
this.poolManagementEndpoint =
params?.poolManagementEndpoint ??
getEnvironmentVariable(
"AZURE_CONTAINER_APP_SESSION_POOL_MANAGEMENT_ENDPOINT"
) ??
"";
if (!this.poolManagementEndpoint) {
throw new Error("poolManagementEndpoint must be defined.");
}
this.sessionId = params?.sessionId ?? uuidv4();
this.azureADTokenProvider =
params?.azureADTokenProvider ?? defaultAzureADTokenProvider();
}
_buildUrl(path: string) {
let url = `${this.poolManagementEndpoint}${
this.poolManagementEndpoint.endsWith("/") ? "" : "/"
}${path}`;
url += url.includes("?") ? "&" : "?";
url += `identifier=${encodeURIComponent(this.sessionId)}`;
url += `&api-version=2024-02-02-preview`;
return url;
}
async _call(pythonCode: string) {
const token = await this.azureADTokenProvider();
const apiUrl = this._buildUrl("code/execute");
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
"User-Agent": await getUserAgentSuffix(),
};
const body = JSON.stringify({
properties: {
codeInputType: "inline",
executionType: "synchronous",
code: pythonCode,
},
});
const response = await fetch(apiUrl, {
method: "POST",
headers,
body,
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const { properties } = await response.json();
const output = {
result: properties.result,
stdout: properties.stdout,
stderr: properties.stderr,
};
return JSON.stringify(output, null, 2);
}
async uploadFile(params: {
data: Blob;
remoteFilename: string;
}): Promise<RemoteFile> {
const token = await this.azureADTokenProvider();
const apiUrl = this._buildUrl("files/upload");
const headers = {
Authorization: `Bearer ${token}`,
"User-Agent": await getUserAgentSuffix(),
};
const formData = new FormData();
formData.append("file", params.data, params.remoteFilename);
const response = await fetch(apiUrl, {
method: "POST",
headers,
body: formData,
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const json = await response.json();
return json.value[0].properties as RemoteFile;
}
async downloadFile(params: { remoteFilename: string }): Promise<Blob> {
const token = await this.azureADTokenProvider();
const apiUrl = this._buildUrl(`files/content/${params.remoteFilename}`);
const headers = {
Authorization: `Bearer ${token}`,
"User-Agent": await getUserAgentSuffix(),
};
const response = await fetch(apiUrl, {
method: "GET",
headers,
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.blob();
}
async listFiles(): Promise<RemoteFile[]> {
const token = await this.azureADTokenProvider();
const apiUrl = this._buildUrl("files");
const headers = {
Authorization: `Bearer ${token}`,
"User-Agent": await getUserAgentSuffix(),
};
const response = await fetch(apiUrl, {
method: "GET",
headers,
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const json = await response.json();
const list = json.value.map(
(x: { properties: RemoteFile }) => x.properties
);
return list as RemoteFile[];
}
}
function defaultAzureADTokenProvider() {
return getBearerTokenProvider(
new DefaultAzureCredential(),
"https://acasessions.io/.default"
);
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-azure-dynamic-sessions
|
lc_public_repos/langchainjs/libs/langchain-azure-dynamic-sessions/src/index.ts
|
export * from "./tools.js";
|
0
|
lc_public_repos/langchainjs/libs/langchain-azure-dynamic-sessions/src
|
lc_public_repos/langchainjs/libs/langchain-azure-dynamic-sessions/src/tests/tools.int.test.ts
|
/* eslint-disable no-process-env */
import { test } from "@jest/globals";
import { config } from "dotenv";
import { SessionsPythonREPLTool } from "../tools.js";
config();
/*
* To run these tests, you need have an Azure Container Apps dynamic session
* instance running.
* See the following link for more information:
* https://learn.microsoft.com/azure/container-apps/sessions
*
* Once you have the instance running, you need to set the following environment
* variable before running the test:
* - AZURE_CONTAINER_APP_SESSION_POOL_MANAGEMENT_ENDPOINT
*/
test("SessionsPythonREPLTool end-to-end test", async () => {
const tool = new SessionsPythonREPLTool();
const result = await tool.invoke("print('Hello, World!')\n1+1");
expect(JSON.parse(result)).toStrictEqual({
stdout: "Hello, World!\n",
stderr: "",
result: 2,
});
});
test("SessionsPythonREPLTool upload file end-to-end test", async () => {
const tool = new SessionsPythonREPLTool();
const result = await tool.uploadFile({
data: new Blob(["hello world!"], { type: "application/octet-stream" }),
remoteFilename: "test.txt",
});
expect(result.filename).toBe("test.txt");
expect(result.size).toBe(12);
const downloadBlob = await tool.downloadFile({
remoteFilename: "test.txt",
});
const downloadText = await downloadBlob.text();
expect(downloadText).toBe("hello world!");
const listResult = await tool.listFiles();
expect(listResult.length).toBe(1);
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-azure-dynamic-sessions/src
|
lc_public_repos/langchainjs/libs/langchain-azure-dynamic-sessions/src/tests/tools.test.ts
|
import { test, jest, describe, beforeEach } from "@jest/globals";
import { DefaultAzureCredential } from "@azure/identity";
import { SessionsPythonREPLTool } from "../index.js";
describe("SessionsPythonREPLTool", () => {
describe("Default access token provider", () => {
let defaultAzureADTokenProvider: () => Promise<string>;
let getTokenMock: jest.SpiedFunction<DefaultAzureCredential["getToken"]>;
beforeEach(() => {
const tool = new SessionsPythonREPLTool({
poolManagementEndpoint: "https://poolmanagement.com",
sessionId: "session-id",
});
defaultAzureADTokenProvider = tool.azureADTokenProvider;
getTokenMock = jest.spyOn(DefaultAzureCredential.prototype, "getToken");
getTokenMock.mockClear();
});
afterEach(() => {
jest.restoreAllMocks();
jest.useRealTimers();
});
test("Should use cached token when not expiring", async () => {
jest.useFakeTimers();
jest.setSystemTime(new Date("2024-01-01 10:00:00"));
getTokenMock.mockImplementationOnce(async () => ({
token: "test-token",
expiresOnTimestamp: new Date("2024-01-01 11:00:00").getTime(),
}));
let token = await defaultAzureADTokenProvider();
expect(token).toBe("test-token");
expect(getTokenMock).toHaveBeenCalledTimes(1);
expect(getTokenMock.mock.calls[0][0]).toEqual([
"https://acasessions.io/.default",
]);
getTokenMock.mockImplementationOnce(async () => ({
token: "test-token2",
expiresOnTimestamp: new Date("2024-01-01 11:00:00").getTime(),
}));
token = await defaultAzureADTokenProvider();
expect(token).toBe("test-token");
expect(getTokenMock).toHaveBeenCalledTimes(1);
});
test("Should refresh token when expired", async () => {
jest.useFakeTimers();
jest.setSystemTime(new Date("2024-01-01 10:00:00"));
getTokenMock.mockImplementationOnce(async () => ({
token: "test-token1",
expiresOnTimestamp: new Date("2024-01-01 10:30:00").getTime(),
}));
let token = await defaultAzureADTokenProvider();
expect(token).toBe("test-token1");
expect(getTokenMock).toHaveBeenCalledTimes(1);
jest.setSystemTime(new Date("2024-01-01 10:31:00"));
getTokenMock.mockImplementationOnce(async () => ({
token: "test-token2",
expiresOnTimestamp: new Date("2024-01-01 11:00:00").getTime(),
}));
token = await defaultAzureADTokenProvider();
expect(token).toBe("test-token2");
expect(getTokenMock).toHaveBeenCalledTimes(2);
});
});
describe("Invoke with Python code", () => {
test("Should return correct output", async () => {
const tool = new SessionsPythonREPLTool({
poolManagementEndpoint:
"https://acasessions.io/subscriptions/subscription-id/resourceGroups/resource-group/sessionPools/session-pool/",
sessionId: "session-id",
});
const getTokenMock = jest.spyOn(
DefaultAzureCredential.prototype,
"getToken"
);
getTokenMock.mockResolvedValue({
token: "test-token",
expiresOnTimestamp: new Date().getTime() + 1000 * 60 * 60,
});
const fetchMock = jest.spyOn(global, "fetch");
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({
$id: "1",
properties: {
$id: "2",
status: "Success",
stdout: "hello\n",
stderr: "",
result: 2,
executionTimeInMilliseconds: 35,
},
}),
} as Response);
const output = await tool.invoke("print('hello')\n1+1");
expect(JSON.parse(output)).toStrictEqual({
stdout: "hello\n",
stderr: "",
result: 2,
});
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledWith(
"https://acasessions.io/subscriptions/subscription-id/resourceGroups/resource-group/sessionPools/session-pool/code/execute?identifier=session-id&api-version=2024-02-02-preview",
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-token",
"User-Agent": expect.any(String),
},
body: JSON.stringify({
properties: {
codeInputType: "inline",
executionType: "synchronous",
code: "print('hello')\n1+1",
},
}),
}
);
});
});
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-azure-dynamic-sessions
|
lc_public_repos/langchainjs/libs/langchain-azure-dynamic-sessions/scripts/jest-setup-after-env.js
|
import { awaitAllCallbacks } from "@langchain/core/callbacks/promises";
import { afterAll, jest } from "@jest/globals";
afterAll(awaitAllCallbacks);
// Allow console.log to be disabled in tests
if (process.env.DISABLE_CONSOLE_LOGS === "true") {
console.log = jest.fn();
}
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/create-langchain-integration/LICENSE.md
|
The MIT License
Copyright (c) Harrison Chase
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/create-langchain-integration/tsconfig.json
|
{
"extends": "@tsconfig/recommended",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./",
"target": "ES2021",
"lib": ["ES2021", "ES2022.Object", "DOM"],
"module": "ES2020",
"moduleResolution": "nodenext",
"esModuleInterop": true,
"declaration": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"useDefineForClassFields": true,
"strictPropertyInitialization": false,
"allowJs": true,
"strict": true,
"resolveJsonModule": true
},
"exclude": ["node_modules", "dist", "template"]
}
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/create-langchain-integration/.eslintrc.cjs
|
module.exports = {
extends: [
"airbnb-base",
"eslint:recommended",
"prettier",
"plugin:@typescript-eslint/recommended",
],
parserOptions: {
ecmaVersion: 12,
parser: "@typescript-eslint/parser",
project: "./tsconfig.json",
sourceType: "module",
},
plugins: ["@typescript-eslint", "no-instanceof", "eslint-plugin-jest"],
ignorePatterns: [
"src/utils/@cfworker",
"src/utils/fast-json-patch",
"src/utils/js-sha1",
".eslintrc.cjs",
"scripts",
"node_modules",
"dist",
"dist-cjs",
"*.js",
"*.cjs",
"*.d.ts",
],
rules: {
"no-process-env": 2,
"no-instanceof/no-instanceof": 2,
"@typescript-eslint/explicit-module-boundary-types": 0,
"@typescript-eslint/no-explicit-any": "warn",
"@typescript-eslint/no-empty-function": 0,
"@typescript-eslint/no-shadow": 0,
"@typescript-eslint/no-empty-interface": 0,
"@typescript-eslint/no-use-before-define": ["error", "nofunc"],
"@typescript-eslint/no-unused-vars": ["warn", { args: "none" }],
"@typescript-eslint/no-floating-promises": "error",
"@typescript-eslint/no-misused-promises": "error",
camelcase: 0,
"class-methods-use-this": 0,
"import/extensions": [2, "ignorePackages"],
"import/no-extraneous-dependencies": [
"error",
{ devDependencies: ["**/*.test.ts"] },
],
"import/no-unresolved": 0,
"import/prefer-default-export": 0,
"keyword-spacing": "error",
"max-classes-per-file": 0,
"max-len": 0,
"no-await-in-loop": 0,
"no-bitwise": 0,
"no-console": 0,
"no-restricted-syntax": 0,
"no-shadow": 0,
"no-continue": 0,
"no-void": 0,
"no-underscore-dangle": 0,
"no-use-before-define": 0,
"no-useless-constructor": 0,
"no-return-await": 0,
"consistent-return": 0,
"no-else-return": 0,
"func-names": 0,
"no-lonely-if": 0,
"prefer-rest-params": 0,
"new-cap": ["error", { properties: false, capIsNew: false }],
"jest/no-focused-tests": "error",
},
overrides: [
{
files: ["**/*.test.ts"],
rules: {
"@typescript-eslint/no-unused-vars": "off",
},
},
],
};
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/create-langchain-integration/.prettierignore
|
dist
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/create-langchain-integration/create-app.ts
|
/* eslint-disable import/no-extraneous-dependencies */
import path from "path";
import { green } from "picocolors";
import { tryGitInit } from "./helpers/git";
import { isFolderEmpty } from "./helpers/is-folder-empty";
import { isWriteable } from "./helpers/is-writeable";
import { makeDir } from "./helpers/make-dir";
import { installTemplate } from "./helpers/templates";
export type InstallAppArgs = {
appPath: string;
};
export async function createApp({ appPath }: InstallAppArgs): Promise<void> {
const root = path.resolve(appPath);
if (!(await isWriteable(path.dirname(root)))) {
console.error(
"The application path is not writable, please check folder permissions and try again."
);
console.error(
"It is likely you do not have write permissions for this folder."
);
process.exit(1);
}
const appName = path.basename(root);
await makeDir(root);
if (!isFolderEmpty(root, appName)) {
process.exit(1);
}
console.log(`Creating a new LangChain integration in ${green(root)}.`);
console.log();
await installTemplate({ root, appName });
process.chdir(root);
if (tryGitInit(root)) {
console.log("Initialized a git repository.");
console.log();
}
console.log(`${green("Success!")} Created ${appName} at ${appPath}`);
console.log();
console.log(`Run "cd ${appPath} to see your new integration.`);
console.log();
}
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/create-langchain-integration/index.ts
|
#!/usr/bin/env node
/* eslint-disable import/no-extraneous-dependencies */
import Commander from "commander";
import Conf from "conf";
import fs from "fs";
import path from "path";
import { bold, cyan, green, red, yellow } from "picocolors";
import prompts from "prompts";
import checkForUpdate from "update-check";
import { createApp } from "./create-app";
import { isFolderEmpty } from "./helpers/is-folder-empty";
import { validateNpmName } from "./helpers/validate-pkg";
import packageJson from "./package.json";
let projectPath: string = "";
const handleSigTerm = () => process.exit(0);
process.on("SIGINT", handleSigTerm);
process.on("SIGTERM", handleSigTerm);
const onPromptState = (state: any) => {
if (state.aborted) {
// If we don't re-enable the terminal cursor before exiting
// the program, the cursor will remain hidden
process.stdout.write("\x1B[?25h");
process.stdout.write("\n");
process.exit(1);
}
};
const program = new Commander.Command(packageJson.name)
.version((packageJson as any).version)
.arguments("<project-directory>")
.usage(`${green("<project-directory>")} [options]`)
.action((name) => {
projectPath = name;
})
.allowUnknownOption()
.parse(process.argv);
const packageManager = "yarn";
async function run(): Promise<void> {
const conf = new Conf({ projectName: "create-langchain-integration" });
if (program.resetPreferences) {
conf.clear();
console.log(`Preferences reset successfully`);
return;
}
if (typeof projectPath === "string") {
projectPath = projectPath.trim();
}
if (!projectPath) {
const res = await prompts({
onState: onPromptState,
type: "text",
name: "path",
message: "What is your project named?",
initial: "my-langchain-integration",
validate: (name) => {
const validation = validateNpmName(path.basename(path.resolve(name)));
if (validation.valid) {
return true;
}
return "Invalid project name: " + validation.problems![0];
},
});
if (typeof res.path === "string") {
projectPath = res.path.trim();
}
}
if (!projectPath) {
console.log(
"\nPlease specify the project directory:\n" +
` ${cyan(program.name())} ${green("<project-directory>")}\n` +
"For example:\n" +
` ${cyan(program.name())} ${green("my-langchain-integration")}\n\n` +
`Run ${cyan(`${program.name()} --help`)} to see all options.`
);
process.exit(1);
}
const resolvedProjectPath = path.resolve(projectPath);
const projectName = path.basename(resolvedProjectPath);
const { valid, problems } = validateNpmName(projectName);
if (!valid) {
console.error(
`Could not create a project called ${red(
`"${projectName}"`
)} because of npm naming restrictions:`
);
problems!.forEach((p) => console.error(` ${red(bold("*"))} ${p}`));
process.exit(1);
}
/**
* Verify the project dir is empty or doesn't exist
*/
const root = path.resolve(resolvedProjectPath);
const appName = path.basename(root);
const folderExists = fs.existsSync(root);
if (folderExists && !isFolderEmpty(root, appName)) {
process.exit(1);
}
const preferences = conf.get("preferences") || {};
await createApp({
appPath: resolvedProjectPath,
});
conf.set("preferences", preferences);
}
const update = checkForUpdate(packageJson).catch(() => null);
async function notifyUpdate(): Promise<void> {
try {
const res = await update;
if (res?.latest) {
const updateMessage =
packageManager === "yarn"
? "yarn global add create-langchain-integration@latest"
: packageManager === "pnpm"
? "pnpm add -g create-langchain-integration@latest"
: "npm i -g create-langchain-integration@latest";
console.log(
yellow(
bold("A new version of `create-langchain-integration` is available!")
) +
"\n" +
"You can update by running: " +
cyan(updateMessage) +
"\n"
);
}
process.exit();
} catch {
// ignore error
}
}
run()
.then(notifyUpdate)
.catch(async (reason) => {
console.log();
console.log("Aborting installation.");
if (reason.command) {
console.log(` ${cyan(reason.command)} has failed.`);
} else {
console.log(
red("Unexpected error. Please report it as a bug:") + "\n",
reason
);
}
console.log();
await notifyUpdate();
process.exit(1);
});
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/create-langchain-integration/package.json
|
{
"name": "create-langchain-integration",
"version": "0.0.11",
"repository": {
"type": "git",
"url": "https://github.com/langchain-ai/langchainjs",
"directory": "libs/create-langchain-integration"
},
"bin": "./dist/index.js",
"scripts": {
"dev": "ncc build ./index.ts -w -o dist/",
"build": "ncc build ./index.ts -o ./dist/ --minify --no-cache --no-source-map-register && cp ./template/.eslintrc.cjs ./template/.prettierrc ./template/.release-it.json ./dist/template",
"format": "prettier --config .prettierrc --write \"./helpers\"",
"format:check": "prettier --config .prettierrc --check \"./helpers\"",
"lint:eslint": "NODE_OPTIONS=--max-old-space-size=4096 eslint --cache --ext .ts,.js ./helpers",
"lint": "NODE_OPTIONS=--max-old-space-size=4096 eslint --cache --ext .ts,.js ./helpers",
"lint:fix": "NODE_OPTIONS=--max-old-space-size=4096 eslint --cache --fix --ext .ts,.js ./helpers"
},
"devDependencies": {
"@types/prompts": "^2",
"@types/validate-npm-package-name": "3.0.0",
"@vercel/ncc": "^0.34.0",
"commander": "^2.20.0",
"conf": "^10.2.0",
"dotenv": "^16.3.1",
"eslint": "^8.33.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-prettier": "^8.6.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-jest": "^27.6.0",
"eslint-plugin-no-instanceof": "^1.0.1",
"eslint-plugin-prettier": "^4.2.1",
"fast-glob": "^3.3.2",
"picocolors": "^1.0.0",
"prettier": "^2.8.3",
"prompts": "^2.4.2",
"typescript": "~5.1.6",
"update-check": "^1.5.4",
"validate-npm-package-name": "^5.0.0"
}
}
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/create-langchain-integration/.prettierrc
|
{
"$schema": "https://json.schemastore.org/prettierrc",
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": false,
"quoteProps": "as-needed",
"jsxSingleQuote": false,
"trailingComma": "es5",
"bracketSpacing": true,
"arrowParens": "always",
"requirePragma": false,
"insertPragma": false,
"proseWrap": "preserve",
"htmlWhitespaceSensitivity": "css",
"vueIndentScriptAndStyle": false,
"endOfLine": "lf"
}
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/tsconfig.json
|
{
"extends": "@tsconfig/recommended",
"compilerOptions": {
"outDir": "../dist",
"rootDir": "./src",
"target": "ES2021",
"lib": ["ES2021", "ES2022.Object", "DOM"],
"module": "ES2020",
"moduleResolution": "nodenext",
"esModuleInterop": true,
"declaration": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"useDefineForClassFields": true,
"strictPropertyInitialization": false,
"allowJs": true,
"strict": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "docs"]
}
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/LICENSE
|
The MIT License
Copyright (c) 2023 LangChain
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/jest.config.cjs
|
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: "ts-jest/presets/default-esm",
testEnvironment: "./jest.env.cjs",
modulePathIgnorePatterns: ["dist/", "docs/"],
moduleNameMapper: {
"^(\\.{1,2}/.*)\\.js$": "$1",
},
transform: {
"^.+\\.tsx?$": ["@swc/jest"],
},
transformIgnorePatterns: [
"/node_modules/",
"\\.pnp\\.[^\\/]+$",
"./scripts/jest-setup-after-env.js",
],
setupFiles: ["dotenv/config"],
testTimeout: 20_000,
passWithNoTests: true,
collectCoverageFrom: ["src/**/*.ts"],
};
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/jest.env.cjs
|
const { TestEnvironment } = require("jest-environment-node");
class AdjustedTestEnvironmentToSupportFloat32Array extends TestEnvironment {
constructor(config, context) {
// Make `instanceof Float32Array` return true in tests
// to avoid https://github.com/xenova/transformers.js/issues/57 and https://github.com/jestjs/jest/issues/2549
super(config, context);
this.global.Float32Array = Float32Array;
}
}
module.exports = AdjustedTestEnvironmentToSupportFloat32Array;
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/README.md
|
# @langchain/<ADD_PACKAGE_NAME_HERE>
This package contains the LangChain.js integrations for <ADD_NAME_HERE> through their SDK.
## Installation
```bash npm2yarn
npm install @langchain/<ADD_PACKAGE_NAME_HERE> @langchain/core
```
This package, along with the main LangChain package, depends on [`@langchain/core`](https://npmjs.com/package/@langchain/core/).
If you are using this package with other LangChain packages, you should make sure that all of the packages depend on the same instance of `@langchain/core`.
You can do so by adding appropriate field to your project's `package.json` like this:
```json
{
"name": "your-project",
"version": "0.0.0",
"dependencies": {
"@langchain/<ADD_PACKAGE_NAME_HERE>": "^0.0.0",
"@langchain/core": "^0.3.0"
},
"resolutions": {
"@langchain/core": "^0.3.0"
},
"overrides": {
"@langchain/core": "^0.3.0"
},
"pnpm": {
"overrides": {
"@langchain/core": "^0.3.0"
}
}
}
```
The field you need depends on the package manager you're using, but we recommend adding a field for the common `yarn`, `npm`, and `pnpm` to maximize compatibility.
## Chat Models
This package contains the `<ADD_CLASS_NAME_HERE>` class, which is the recommended way to interface with the <ADD_NAME_HERE> series of models.
To use, install the requirements, and configure your environment.
```bash
export <ADD_ENV_NAME_HERE>=your-api-key
```
Then initialize
```typescript
import { <ADD_CLASS_NAME_HERE> } from "@langchain/<ADD_PACKAGE_NAME_HERE>";
const model = new ExampleChatClass({
apiKey: process.env.EXAMPLE_API_KEY,
});
const response = await model.invoke(new HumanMessage("Hello world!"));
```
### Streaming
```typescript
import { <ADD_CLASS_NAME_HERE> } from "@langchain/<ADD_PACKAGE_NAME_HERE>";
const model = new ExampleChatClass({
apiKey: process.env.EXAMPLE_API_KEY,
});
const response = await model.stream(new HumanMessage("Hello world!"));
```
## Embeddings
This package also adds support for <ADD_NAME_HERE> embeddings model.
```typescript
import { <ADD_CLASS_NAME_HERE> } from "@langchain/<ADD_PACKAGE_NAME_HERE>";
const embeddings = new ExampleEmbeddingClass({
apiKey: process.env.EXAMPLE_API_KEY,
});
const res = await embeddings.embedQuery("Hello world");
```
## Development
To develop the <ADD_NAME_HERE> package, you'll need to follow these instructions:
### Install dependencies
```bash
yarn install
```
### Build the package
```bash
yarn build
```
Or from the repo root:
```bash
yarn build --filter=@langchain/<ADD_PACKAGE_NAME_HERE>
```
### Run tests
Test files should live within a `tests/` file in the `src/` folder. Unit tests should end in `.test.ts` and integration tests should
end in `.int.test.ts`:
```bash
$ yarn test
$ yarn test:int
```
### Lint & Format
Run the linter & formatter to ensure your code is up to standard:
```bash
yarn lint && yarn format
```
### Adding new entrypoints
If you add a new file to be exported, either import & re-export from `src/index.ts`, or add it to the `entrypoints` field in the `config` variable located inside `langchain.config.js` and run `yarn build` to generate the new entrypoint.
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/.release-it.json
|
{
"github": {
"release": true,
"autoGenerate": true,
"tokenRef": "GITHUB_TOKEN_RELEASE"
},
"npm": {
"versionArgs": ["--workspaces-update=false"]
}
}
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/.eslintrc.cjs
|
module.exports = {
extends: [
"airbnb-base",
"eslint:recommended",
"prettier",
"plugin:@typescript-eslint/recommended",
],
parserOptions: {
ecmaVersion: 12,
parser: "@typescript-eslint/parser",
project: "./tsconfig.json",
sourceType: "module",
},
plugins: ["@typescript-eslint", "no-instanceof"],
ignorePatterns: [
".eslintrc.cjs",
"scripts",
"node_modules",
"dist",
"dist-cjs",
"*.js",
"*.cjs",
"*.d.ts",
],
rules: {
"no-process-env": 2,
"no-instanceof/no-instanceof": 2,
"@typescript-eslint/explicit-module-boundary-types": 0,
"@typescript-eslint/no-empty-function": 0,
"@typescript-eslint/no-shadow": 0,
"@typescript-eslint/no-empty-interface": 0,
"@typescript-eslint/no-use-before-define": ["error", "nofunc"],
"@typescript-eslint/no-unused-vars": ["warn", { args: "none" }],
"@typescript-eslint/no-floating-promises": "error",
"@typescript-eslint/no-misused-promises": "error",
camelcase: 0,
"class-methods-use-this": 0,
"import/extensions": [2, "ignorePackages"],
"import/no-extraneous-dependencies": [
"error",
{ devDependencies: ["**/*.test.ts"] },
],
"import/no-unresolved": 0,
"import/prefer-default-export": 0,
"keyword-spacing": "error",
"max-classes-per-file": 0,
"max-len": 0,
"no-await-in-loop": 0,
"no-bitwise": 0,
"no-console": 0,
"no-restricted-syntax": 0,
"no-shadow": 0,
"no-continue": 0,
"no-void": 0,
"no-underscore-dangle": 0,
"no-use-before-define": 0,
"no-useless-constructor": 0,
"no-return-await": 0,
"consistent-return": 0,
"no-else-return": 0,
"func-names": 0,
"no-lonely-if": 0,
"prefer-rest-params": 0,
"new-cap": ["error", { properties: false, capIsNew: false }],
},
overrides: [
{
files: ["**/*.test.ts"],
rules: {
"@typescript-eslint/no-unused-vars": "off",
},
},
],
};
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/langchain.config.js
|
import { resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url";
/**
* @param {string} relativePath
* @returns {string}
*/
function abs(relativePath) {
return resolve(dirname(fileURLToPath(import.meta.url)), relativePath);
}
export const config = {
internals: [/node\:/, /@langchain\/core\//],
entrypoints: {
index: "index",
},
requiresOptionalDependency: [],
tsConfigPath: resolve("./tsconfig.json"),
cjsSource: "./dist-cjs",
cjsDestination: "./dist",
abs,
};
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/package.json
|
{
"name": "langchain-integration",
"version": "0.0.0",
"description": "Sample integration for LangChain.js",
"type": "module",
"engines": {
"node": ">=18"
},
"main": "./index.js",
"types": "./index.d.ts",
"repository": {
"type": "git",
"url": "git@github.com:langchain-ai/langchainjs.git"
},
"homepage": "https://github.com/langchain-ai/langchainjs/tree/main/libs/langchain-INTEGRATION_NAME/",
"scripts": {
"build": "yarn turbo:command build:internal --filter=@langchain/INTEGRATION_NAME",
"build:internal": "yarn lc_build --create-entrypoints --pre --tree-shaking",
"lint:eslint": "NODE_OPTIONS=--max-old-space-size=4096 eslint --cache --ext .ts,.js src/",
"lint:dpdm": "dpdm --exit-code circular:1 --no-warning --no-tree src/*.ts src/**/*.ts",
"lint": "yarn lint:eslint && yarn lint:dpdm",
"lint:fix": "yarn lint:eslint --fix && yarn lint:dpdm",
"clean": "rm -rf .turbo dist/",
"prepack": "yarn build",
"test": "NODE_OPTIONS=--experimental-vm-modules jest --testPathIgnorePatterns=\\.int\\.test.ts --testTimeout 30000 --maxWorkers=50%",
"test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch --testPathIgnorePatterns=\\.int\\.test.ts",
"test:single": "NODE_OPTIONS=--experimental-vm-modules yarn run jest --config jest.config.cjs --testTimeout 100000",
"test:int": "NODE_OPTIONS=--experimental-vm-modules jest --testPathPattern=\\.int\\.test.ts --testTimeout 100000 --maxWorkers=50%",
"format": "prettier --config .prettierrc --write \"src\"",
"format:check": "prettier --config .prettierrc --check \"src\""
},
"author": "LangChain",
"license": "MIT",
"dependencies": {
"@langchain/core": ">=0.3.0 <0.4.0"
},
"devDependencies": {
"@jest/globals": "^29.5.0",
"@swc/core": "^1.3.90",
"@swc/jest": "^0.2.29",
"@langchain/scripts": ">=0.1.0 <0.2.0",
"@tsconfig/recommended": "^1.0.3",
"@typescript-eslint/eslint-plugin": "^6.12.0",
"@typescript-eslint/parser": "^6.12.0",
"dotenv": "^16.3.1",
"dpdm": "^3.12.0",
"release-it": "^15.10.1",
"eslint": "^8.33.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-prettier": "^8.6.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-no-instanceof": "^1.0.1",
"eslint-plugin-prettier": "^4.2.1",
"jest": "^29.5.0",
"jest-environment-node": "^29.6.4",
"prettier": "^2.8.3",
"rollup": "^4.5.2",
"ts-jest": "^29.1.0",
"typescript": "<5.2.0"
},
"publishConfig": {
"access": "public"
},
"exports": {
".": {
"types": "./index.d.ts",
"import": "./index.js",
"require": "./index.cjs"
},
"./package.json": "./package.json"
},
"files": [
"dist/",
"index.cjs",
"index.js",
"index.d.ts"
]
}
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/tsconfig.cjs.json
|
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs",
"declaration": false
},
"exclude": ["node_modules", "dist", "docs", "**/tests"]
}
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/turbo.json
|
{
"extends": ["//"],
"pipeline": {
"build": {
"outputs": ["**/dist/**"]
},
"build:internal": {
"dependsOn": ["^build:internal"]
}
}
}
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/.prettierrc
|
{
"$schema": "https://json.schemastore.org/prettierrc",
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": false,
"quoteProps": "as-needed",
"jsxSingleQuote": false,
"trailingComma": "es5",
"bracketSpacing": true,
"arrowParens": "always",
"requirePragma": false,
"insertPragma": false,
"proseWrap": "preserve",
"htmlWhitespaceSensitivity": "css",
"vueIndentScriptAndStyle": false,
"endOfLine": "lf"
}
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/src/vectorstores.ts
|
import type { EmbeddingsInterface } from "@langchain/core/embeddings";
import { VectorStore } from "@langchain/core/vectorstores";
import { Document } from "@langchain/core/documents";
/**
* Database config for your vectorstore.
*/
export interface VectorstoreIntegrationParams {}
/**
* Class for managing and operating vector search applications with
* Tigris, an open-source Serverless NoSQL Database and Search Platform.
*/
export class VectorstoreIntegration extends VectorStore {
// Replace
_vectorstoreType(): string {
return "vectorstore_integration";
}
constructor(
embeddings: EmbeddingsInterface,
params: VectorstoreIntegrationParams
) {
super(embeddings, params);
this.embeddings = embeddings;
}
/**
* Replace with any secrets this class passes to `super`.
* See {@link ../../langchain-cohere/src/chat_model.ts} for
* an example.
*/
get lc_secrets(): { [key: string]: string } | undefined {
return {
apiKey: "API_KEY_NAME",
};
}
get lc_aliases(): { [key: string]: string } | undefined {
return {
apiKey: "API_KEY_NAME",
};
}
/**
* Method to add an array of documents to the vectorstore.
*
* Useful to override in case your vectorstore doesn't work directly with embeddings.
*/
async addDocuments(
documents: Document[],
options?: { ids?: string[] } | string[]
): Promise<void> {
const texts = documents.map(({ pageContent }) => pageContent);
await this.addVectors(
await this.embeddings.embedDocuments(texts),
documents,
options
);
}
/**
* Method to add raw vectors to the vectorstore.
*/
async addVectors(
_vectors: number[][],
_documents: Document[],
_options?: { ids?: string[] } | string[]
) {
throw new Error("Not implemented.");
}
/**
* Method to perform a similarity search over the vectorstore and return
* the k most similar vectors along with their similarity scores.
*/
async similaritySearchVectorWithScore(
_query: number[],
_k: number,
_filter?: object
): Promise<[Document, number][]> {
throw new Error("Not implemented.");
}
/**
* Static method to create a new instance of the vectorstore from an
* array of Document instances.
*
* Other common static initializer names are fromExistingIndex, initialize, and fromTexts.
*/
static async fromDocuments(
docs: Document[],
embeddings: EmbeddingsInterface,
dbConfig: VectorstoreIntegrationParams
): Promise<VectorstoreIntegration> {
const instance = new this(embeddings, dbConfig);
await instance.addDocuments(docs);
return instance;
}
}
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/src/llms.ts
|
import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";
import { LLM, type BaseLLMParams } from "@langchain/core/language_models/llms";
import { type BaseLanguageModelCallOptions } from "@langchain/core/language_models/base";
// Uncomment if implementing streaming
// import {
// GenerationChunk,
// } from "@langchain/core/outputs";
/**
* Input to LLM class.
*/
export interface LLMIntegrationInput extends BaseLLMParams {}
/**
* Integration with an LLM.
*/
export class LLMIntegration
extends LLM<BaseLanguageModelCallOptions>
implements LLMIntegrationInput
{
// Used for tracing, replace with the same name as your class
static lc_name() {
return "LLMIntegration";
}
lc_serializable = true;
constructor(fields: LLMIntegrationInput) {
super(fields);
}
// Replace
_llmType() {
return "llm_integration";
}
/**
* Replace with any secrets this class passes to `super`.
* See {@link ../../langchain-cohere/src/chat_model.ts} for
* an example.
*/
get lc_secrets(): { [key: string]: string } | undefined {
return {
apiKey: "API_KEY_NAME",
};
}
get lc_aliases(): { [key: string]: string } | undefined {
return {
apiKey: "API_KEY_NAME",
};
}
/**
* For some given input string and options, return a string output.
*/
async _call(
_prompt: string,
_options: this["ParsedCallOptions"],
_runManager?: CallbackManagerForLLMRun
): Promise<string> {
throw new Error("Not implemented.");
}
/**
* Implement to support streaming.
* Should yield chunks iteratively.
*/
// async *_streamResponseChunks(
// prompt: string,
// options: this["ParsedCallOptions"],
// runManager?: CallbackManagerForLLMRun
// ): AsyncGenerator<GenerationChunk> {
// const stream = await this.caller.call(async () =>
// createStream()
// );
// for await (const chunk of stream) {
// yield new GenerationChunk({
// text: chunk.response,
// generationInfo: {
// ...chunk,
// response: undefined,
// },
// });
// await runManager?.handleLLMNewToken(chunk.response ?? "");
// }
// }
}
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/src/index.ts
|
export * from "./chat_models.js";
export * from "./llms.js";
export * from "./vectorstores.js";
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/src/chat_models.ts
|
import { type BaseMessage } from "@langchain/core/messages";
import { type BaseLanguageModelCallOptions } from "@langchain/core/language_models/base";
import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";
import {
type BaseChatModelParams,
SimpleChatModel,
} from "@langchain/core/language_models/chat_models";
// Uncomment if implementing streaming
// import {
// ChatGenerationChunk,
// } from "@langchain/core/outputs";
// import {
// AIMessageChunk,
// } from "@langchain/core/messages";
/**
* Input to chat model class.
*/
export interface ChatIntegrationInput extends BaseChatModelParams {}
/**
* Integration with a chat model.
*/
export class ChatIntegration<
CallOptions extends BaseLanguageModelCallOptions = BaseLanguageModelCallOptions
>
extends SimpleChatModel<CallOptions>
implements ChatIntegrationInput
{
// Used for tracing, replace with the same name as your class
static lc_name() {
return "ChatIntegration";
}
lc_serializable = true;
/**
* Replace with any secrets this class passes to `super`.
* See {@link ../../langchain-cohere/src/chat_model.ts} for
* an example.
*/
get lc_secrets(): { [key: string]: string } | undefined {
return {
apiKey: "API_KEY_NAME",
};
}
get lc_aliases(): { [key: string]: string } | undefined {
return {
apiKey: "API_KEY_NAME",
};
}
constructor(fields?: ChatIntegrationInput) {
super(fields ?? {});
}
// Replace
_llmType() {
return "chat_integration";
}
/**
* For some given input messages and options, return a string output.
*/
_call(
_messages: BaseMessage[],
_options: this["ParsedCallOptions"],
_runManager?: CallbackManagerForLLMRun
): Promise<string> {
throw new Error("Not implemented.");
}
/**
* Implement to support streaming.
* Should yield chunks iteratively.
*/
// async *_streamResponseChunks(
// messages: BaseMessage[],
// options: this["ParsedCallOptions"],
// runManager?: CallbackManagerForLLMRun
// ): AsyncGenerator<ChatGenerationChunk> {
// // All models have a built in `this.caller` property for retries
// const stream = await this.caller.call(async () =>
// createStreamMethod()
// );
// for await (const chunk of stream) {
// if (!chunk.done) {
// yield new ChatGenerationChunk({
// text: chunk.response,
// message: new AIMessageChunk({ content: chunk.response }),
// });
// await runManager?.handleLLMNewToken(chunk.response ?? "");
// }
// }
// }
/** @ignore */
_combineLLMOutput() {
return [];
}
}
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/src
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/src/tests/llms.test.ts
|
import { test } from "@jest/globals";
test("Test LLM", async () => {
// Your test here
});
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/src
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/src/tests/integration.int.test.ts
|
import { test } from "@jest/globals";
test("Test chat model", async () => {
// Your integration test here
});
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/src
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/src/tests/vectorstores.test.ts
|
import { test } from "@jest/globals";
test("Test vectorstore", async () => {
// Your test here
});
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/src
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/src/tests/chat_models.test.ts
|
import { test } from "@jest/globals";
test("Test chat model", async () => {
// Your test here
});
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template
|
lc_public_repos/langchainjs/libs/create-langchain-integration/template/scripts/jest-setup-after-env.js
|
import { awaitAllCallbacks } from "@langchain/core/callbacks/promises";
import { afterAll, jest } from "@jest/globals";
afterAll(awaitAllCallbacks);
// Allow console.log to be disabled in tests
if (process.env.DISABLE_CONSOLE_LOGS === "true") {
console.log = jest.fn();
}
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration
|
lc_public_repos/langchainjs/libs/create-langchain-integration/helpers/is-folder-empty.ts
|
/* eslint-disable import/no-extraneous-dependencies */
import fs from "fs";
import path from "path";
import { blue, green } from "picocolors";
export function isFolderEmpty(root: string, name: string): boolean {
const validFiles = [
".DS_Store",
".git",
".gitattributes",
".gitignore",
".gitlab-ci.yml",
".hg",
".hgcheck",
".hgignore",
".idea",
".npmignore",
".travis.yml",
"LICENSE",
"Thumbs.db",
"docs",
"mkdocs.yml",
"npm-debug.log",
"yarn-debug.log",
"yarn-error.log",
"yarnrc.yml",
".yarn",
];
const conflicts = fs
.readdirSync(root)
.filter((file) => !validFiles.includes(file))
// Support IntelliJ IDEA-based editors
.filter((file) => !/\.iml$/.test(file));
if (conflicts.length > 0) {
console.log(
`The directory ${green(name)} contains files that could conflict:`
);
console.log();
for (const file of conflicts) {
try {
const stats = fs.lstatSync(path.join(root, file));
if (stats.isDirectory()) {
console.log(` ${blue(file)}/`);
} else {
console.log(` ${file}`);
}
} catch {
console.log(` ${file}`);
}
}
console.log();
console.log(
"Either try using a new directory name, or remove the files listed above."
);
console.log();
return false;
}
return true;
}
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration
|
lc_public_repos/langchainjs/libs/create-langchain-integration/helpers/is-writeable.ts
|
import fs from "fs";
export async function isWriteable(directory: string): Promise<boolean> {
try {
await fs.promises.access(directory, (fs.constants || fs).W_OK);
return true;
} catch (err) {
return false;
}
}
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration
|
lc_public_repos/langchainjs/libs/create-langchain-integration/helpers/validate-pkg.ts
|
// eslint-disable-next-line import/no-extraneous-dependencies
import validateProjectName from "validate-npm-package-name";
export function validateNpmName(name: string): {
valid: boolean;
problems?: string[];
} {
const nameValidation = validateProjectName(name);
if (nameValidation.validForNewPackages) {
return { valid: true };
}
return {
valid: false,
problems: [
...(nameValidation.errors || []),
...(nameValidation.warnings || []),
],
};
}
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration
|
lc_public_repos/langchainjs/libs/create-langchain-integration/helpers/make-dir.ts
|
import fs from "fs";
export function makeDir(
root: string,
options = { recursive: true }
): Promise<string | undefined> {
return fs.promises.mkdir(root, options);
}
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration
|
lc_public_repos/langchainjs/libs/create-langchain-integration/helpers/git.ts
|
/* eslint-disable import/no-extraneous-dependencies */
import { execSync } from "child_process";
import fs from "fs";
import path from "path";
function isInGitRepository(): boolean {
try {
execSync("git rev-parse --is-inside-work-tree", { stdio: "ignore" });
return true;
} catch (_) {
// no-op
}
return false;
}
function isInMercurialRepository(): boolean {
try {
execSync("hg --cwd . root", { stdio: "ignore" });
return true;
} catch (_) {
// no-op
}
return false;
}
function isDefaultBranchSet(): boolean {
try {
execSync("git config init.defaultBranch", { stdio: "ignore" });
return true;
} catch (_) {
// no-op
}
return false;
}
export function tryGitInit(root: string): boolean {
let didInit = false;
try {
execSync("git --version", { stdio: "ignore" });
if (isInGitRepository() || isInMercurialRepository()) {
return false;
}
execSync("git init", { stdio: "ignore" });
didInit = true;
if (!isDefaultBranchSet()) {
execSync("git checkout -b main", { stdio: "ignore" });
}
execSync("git add -A", { stdio: "ignore" });
execSync(
'git commit -m "Initial commit from create-langchain-integration"',
{
stdio: "ignore",
}
);
return true;
} catch (e) {
if (didInit) {
try {
fs.rmSync(path.join(root, ".git"), { recursive: true, force: true });
} catch (_) {
// no-op
}
}
return false;
}
}
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration
|
lc_public_repos/langchainjs/libs/create-langchain-integration/helpers/copy.ts
|
/* eslint-disable import/no-extraneous-dependencies */
import { async as glob } from "fast-glob";
import fs from "fs";
import path from "path";
interface CopyOption {
cwd?: string;
rename?: (basename: string) => string;
parents?: boolean;
}
const identity = (x: string) => x;
export const copy = async (
src: string | string[],
dest: string,
{ cwd, rename = identity, parents = true }: CopyOption = {}
) => {
const source = typeof src === "string" ? [src] : src;
if (source.length === 0 || !dest) {
throw new TypeError("`src` and `dest` are required");
}
const sourceFiles = await glob(source, {
cwd,
dot: true,
absolute: false,
stats: false,
});
const destRelativeToCwd = cwd ? path.resolve(cwd, dest) : dest;
return Promise.all(
sourceFiles.map(async (p) => {
const dirname = path.dirname(p);
const basename = rename(path.basename(p));
const from = cwd ? path.resolve(cwd, p) : p;
const to = parents
? path.join(destRelativeToCwd, dirname, basename)
: path.join(destRelativeToCwd, basename);
// Ensure the destination directory exists
await fs.promises.mkdir(path.dirname(to), { recursive: true });
return fs.promises.copyFile(from, to);
})
);
};
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration
|
lc_public_repos/langchainjs/libs/create-langchain-integration/helpers/is-url.ts
|
export function isUrl(url: string): boolean {
try {
const newUrl = new URL(url);
return Boolean(newUrl);
} catch (error) {
return false;
}
}
|
0
|
lc_public_repos/langchainjs/libs/create-langchain-integration
|
lc_public_repos/langchainjs/libs/create-langchain-integration/helpers/templates.ts
|
import path from "path";
import fs from "fs/promises";
import os from "os";
import { copy } from "./copy.js";
/**
* Install a internal template to a given `root` directory.
*/
export async function installTemplate({ appName, root }: any) {
/**
* Copy the template files to the target directory.
*/
const templatePath = path.join(__dirname, "..", "template");
const copySource = ["**"];
console.log(`Initializing project...`);
await copy(copySource, root, {
parents: true,
cwd: templatePath,
});
/**
* Update the package.json scripts.
*/
const packageJsonFile = path.join(root, "package.json");
const packageJson: any = JSON.parse(
await fs.readFile(packageJsonFile, "utf8")
);
packageJson.name = appName;
if (appName.startsWith("@langchain/")) {
const integrationName = appName.replace("@langchain/", "");
packageJson.description = `Integration for LangChain ${integrationName}`;
packageJson.homepage = `https://github.com/langchain-ai/langchainjs/tree/main/libs/langchain-${integrationName}/`;
packageJson.scripts.build = `yarn turbo:command build:internal --filter=${appName}`;
}
await fs.writeFile(
packageJsonFile,
JSON.stringify(packageJson, null, 2) + os.EOL
);
await fs.writeFile(
path.join(root, ".gitignore"),
["node_modules", "dist", ".yarn"].join("\n") + os.EOL
);
console.log("\nDone!\n");
}
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/tsconfig.json
|
{
"extends": "@tsconfig/recommended",
"compilerOptions": {
"outDir": "../dist",
"rootDir": "./src",
"target": "ES2021",
"lib": ["ES2021", "ES2022.Object", "DOM"],
"module": "ES2020",
"moduleResolution": "nodenext",
"esModuleInterop": true,
"declaration": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"useDefineForClassFields": true,
"strictPropertyInitialization": false,
"allowJs": true,
"strict": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "docs"]
}
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/LICENSE
|
The MIT License
Copyright (c) 2023 LangChain
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/jest.config.cjs
|
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: "ts-jest/presets/default-esm",
testEnvironment: "./jest.env.cjs",
modulePathIgnorePatterns: ["dist/", "docs/"],
moduleNameMapper: {
"^(\\.{1,2}/.*)\\.js$": "$1",
},
transform: {
"^.+\\.tsx?$": ["@swc/jest"],
},
transformIgnorePatterns: [
"/node_modules/",
"\\.pnp\\.[^\\/]+$",
"./scripts/jest-setup-after-env.js",
],
setupFiles: ["dotenv/config"],
testTimeout: 20_000,
passWithNoTests: true,
};
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/jest.env.cjs
|
const { TestEnvironment } = require("jest-environment-node");
class AdjustedTestEnvironmentToSupportFloat32Array extends TestEnvironment {
constructor(config, context) {
// Make `instanceof Float32Array` return true in tests
// to avoid https://github.com/xenova/transformers.js/issues/57 and https://github.com/jestjs/jest/issues/2549
super(config, context);
this.global.Float32Array = Float32Array;
}
}
module.exports = AdjustedTestEnvironmentToSupportFloat32Array;
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/README.md
|
# LangChain google-vertexai
This package contains resources to access Google AI/ML models
and other Google services via Vertex AI. Authorization to these
services use service account credentials stored on the local
file system or provided through the Google Cloud Platform
environment it is running on.
If you are running this on a platform where the credentials cannot
be provided this way, consider using the @langchain/google-vertexai-web
package *instead*. You do not need to use both packages. See the
section on **Authorization** below.
## Installation
```bash
$ yarn add @langchain/google-vertexai
```
## Authorization
Authorization is done through a Google Cloud Service Account.
To handle service accounts, this package uses the `google-auth-library`
package, and you may wish to consult the documentation for that library
about how it does so. But in short, classes in this package will use
credentials from the first of the following that apply:
1. An API Key that is passed to the constructor using the `apiKey` attribute
2. Credentials that are passed to the constructor using the `authInfo` attribute
3. An API Key that is set in the environment variable `API_KEY`
4. The Service Account credentials that are saved in a file. The path to
this file is set in the `GOOGLE_APPLICATION_CREDENTIALS` environment
variable.
5. If you are running on a Google Cloud Platform resource, or if you have
logged in using `gcloud auth application-default login`, then the
default credentials.
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/.release-it.json
|
{
"github": {
"release": true,
"autoGenerate": true,
"tokenRef": "GITHUB_TOKEN_RELEASE"
},
"npm": {
"versionArgs": [
"--workspaces-update=false"
]
}
}
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/.eslintrc.cjs
|
module.exports = {
extends: [
"airbnb-base",
"eslint:recommended",
"prettier",
"plugin:@typescript-eslint/recommended",
],
parserOptions: {
ecmaVersion: 12,
parser: "@typescript-eslint/parser",
project: "./tsconfig.json",
sourceType: "module",
},
plugins: ["@typescript-eslint", "no-instanceof"],
ignorePatterns: [
".eslintrc.cjs",
"scripts",
"node_modules",
"dist",
"dist-cjs",
"*.js",
"*.cjs",
"*.d.ts",
],
rules: {
"no-process-env": 2,
"no-instanceof/no-instanceof": 2,
"@typescript-eslint/explicit-module-boundary-types": 0,
"@typescript-eslint/no-empty-function": 0,
"@typescript-eslint/no-shadow": 0,
"@typescript-eslint/no-empty-interface": 0,
"@typescript-eslint/no-use-before-define": ["error", "nofunc"],
"@typescript-eslint/no-unused-vars": ["warn", { args: "none" }],
"@typescript-eslint/no-floating-promises": "error",
"@typescript-eslint/no-misused-promises": "error",
camelcase: 0,
"class-methods-use-this": 0,
"import/extensions": [2, "ignorePackages"],
"import/no-extraneous-dependencies": [
"error",
{ devDependencies: ["**/*.test.ts"] },
],
"import/no-unresolved": 0,
"import/prefer-default-export": 0,
"keyword-spacing": "error",
"max-classes-per-file": 0,
"max-len": 0,
"no-await-in-loop": 0,
"no-bitwise": 0,
"no-console": 0,
"no-restricted-syntax": 0,
"no-shadow": 0,
"no-continue": 0,
"no-void": 0,
"no-underscore-dangle": 0,
"no-use-before-define": 0,
"no-useless-constructor": 0,
"no-return-await": 0,
"consistent-return": 0,
"no-else-return": 0,
"func-names": 0,
"no-lonely-if": 0,
"prefer-rest-params": 0,
"new-cap": ["error", { properties: false, capIsNew: false }],
},
overrides: [
{
files: ['**/*.test.ts'],
rules: {
'@typescript-eslint/no-unused-vars': 'off'
}
}
]
};
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/langchain.config.js
|
import { resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url";
/**
* @param {string} relativePath
* @returns {string}
*/
function abs(relativePath) {
return resolve(dirname(fileURLToPath(import.meta.url)), relativePath);
}
export const config = {
internals: [/node\:/, /@langchain\/core\//, /@langchain\/google-gauth/],
entrypoints: {
index: "index",
utils: "utils",
types: "types",
},
tsConfigPath: resolve("./tsconfig.json"),
cjsSource: "./dist-cjs",
cjsDestination: "./dist",
abs,
}
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/package.json
|
{
"name": "@langchain/google-vertexai",
"version": "0.1.3",
"description": "LangChain.js support for Google Vertex AI",
"type": "module",
"engines": {
"node": ">=18"
},
"main": "./index.js",
"types": "./index.d.ts",
"repository": {
"type": "git",
"url": "git@github.com:langchain-ai/langchainjs.git"
},
"homepage": "https://github.com/langchain-ai/langchainjs/tree/main/libs/langchain-google-vertexai/",
"scripts": {
"build": "yarn turbo:command build:internal --filter=@langchain/google-vertexai",
"build:internal": "yarn lc_build --create-entrypoints --pre --tree-shaking",
"lint:eslint": "NODE_OPTIONS=--max-old-space-size=4096 eslint --cache --ext .ts,.js src/",
"lint:dpdm": "dpdm --exit-code circular:1 --no-warning --no-tree src/*.ts src/**/*.ts",
"lint": "yarn lint:eslint && yarn lint:dpdm",
"lint:fix": "yarn lint:eslint --fix && yarn lint:dpdm",
"clean": "rm -rf .turbo dist/",
"prepack": "yarn build",
"test": "NODE_OPTIONS=--experimental-vm-modules jest --testPathIgnorePatterns=\\.int\\.test.ts --testTimeout 30000 --maxWorkers=50%",
"test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch --testPathIgnorePatterns=\\.int\\.test.ts",
"test:single": "NODE_OPTIONS=--experimental-vm-modules yarn run jest --config jest.config.cjs --testTimeout 100000",
"test:int": "NODE_OPTIONS=--experimental-vm-modules jest --testPathPattern=\\.int\\.test.ts --testTimeout 100000 --maxWorkers=50%",
"format": "prettier --config .prettierrc --write \"src\"",
"format:check": "prettier --config .prettierrc --check \"src\""
},
"author": "LangChain",
"license": "MIT",
"dependencies": {
"@langchain/google-gauth": "~0.1.3"
},
"peerDependencies": {
"@langchain/core": ">=0.2.21 <0.4.0"
},
"devDependencies": {
"@jest/globals": "^29.5.0",
"@langchain/core": "workspace:*",
"@langchain/google-common": "^0.1.0",
"@langchain/scripts": ">=0.1.0 <0.2.0",
"@langchain/standard-tests": "0.0.0",
"@swc/core": "^1.3.90",
"@swc/jest": "^0.2.29",
"@tsconfig/recommended": "^1.0.3",
"@typescript-eslint/eslint-plugin": "^6.12.0",
"@typescript-eslint/parser": "^6.12.0",
"dotenv": "^16.3.1",
"dpdm": "^3.12.0",
"eslint": "^8.33.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-prettier": "^8.6.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-no-instanceof": "^1.0.1",
"eslint-plugin-prettier": "^4.2.1",
"jest": "^29.5.0",
"jest-environment-node": "^29.6.4",
"prettier": "^2.8.3",
"release-it": "^17.6.0",
"rollup": "^4.5.2",
"ts-jest": "^29.1.0",
"typescript": "<5.2.0",
"zod": "^3.22.4"
},
"publishConfig": {
"access": "public"
},
"exports": {
".": {
"types": {
"import": "./index.d.ts",
"require": "./index.d.cts",
"default": "./index.d.ts"
},
"import": "./index.js",
"require": "./index.cjs"
},
"./utils": {
"types": {
"import": "./utils.d.ts",
"require": "./utils.d.cts",
"default": "./utils.d.ts"
},
"import": "./utils.js",
"require": "./utils.cjs"
},
"./types": {
"types": {
"import": "./types.d.ts",
"require": "./types.d.cts",
"default": "./types.d.ts"
},
"import": "./types.js",
"require": "./types.cjs"
},
"./package.json": "./package.json"
},
"files": [
"dist/",
"index.cjs",
"index.js",
"index.d.ts",
"index.d.cts",
"utils.cjs",
"utils.js",
"utils.d.ts",
"utils.d.cts",
"types.cjs",
"types.js",
"types.d.ts",
"types.d.cts"
]
}
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/tsconfig.cjs.json
|
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs",
"declaration": false
},
"exclude": ["node_modules", "dist", "docs", "**/tests"]
}
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/turbo.json
|
{
"extends": ["//"],
"pipeline": {
"build": {
"outputs": ["**/dist/**"]
},
"build:internal": {
"dependsOn": ["^build:internal"]
}
}
}
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/.prettierrc
|
{
"$schema": "https://json.schemastore.org/prettierrc",
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": false,
"quoteProps": "as-needed",
"jsxSingleQuote": false,
"trailingComma": "es5",
"bracketSpacing": true,
"arrowParens": "always",
"requirePragma": false,
"insertPragma": false,
"proseWrap": "preserve",
"htmlWhitespaceSensitivity": "css",
"vueIndentScriptAndStyle": false,
"endOfLine": "lf"
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/src/types.ts
|
export * from "@langchain/google-gauth/types";
|
0
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/src/llms.ts
|
import { type GoogleLLMInput, GoogleLLM } from "@langchain/google-gauth";
/**
* Input to a Google Vertex AI LLM class.
*/
export interface VertexAIInput extends GoogleLLMInput {}
/**
* Integration with a Google Vertex AI LLM using
* the "@langchain/google-gauth" package for auth.
*/
export class VertexAI extends GoogleLLM {
lc_namespace = ["langchain", "llms", "vertexai"];
static lc_name() {
return "VertexAI";
}
constructor(fields?: VertexAIInput) {
super({
...fields,
platformType: "gcp",
});
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/src/index.ts
|
export * from "./chat_models.js";
export * from "./llms.js";
export * from "./embeddings.js";
|
0
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/src/chat_models.ts
|
import { type ChatGoogleInput, ChatGoogle } from "@langchain/google-gauth";
/**
* Input to a Google Vertex AI chat model class.
*/
export interface ChatVertexAIInput extends ChatGoogleInput {}
/**
* Integration with Google Vertex AI chat models.
*
* Setup:
* Install `@langchain/google-vertexai` and set your stringified
* Vertex AI credentials as an environment variable named `GOOGLE_APPLICATION_CREDENTIALS`.
*
* ```bash
* npm install @langchain/google-vertexai
* export GOOGLE_APPLICATION_CREDENTIALS="path/to/credentials"
* ```
*
* ## [Constructor args](https://api.js.langchain.com/classes/langchain_community_chat_models_googlevertexai_web.ChatGoogleVertexAI.html#constructor)
*
* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_google_common_types.GoogleAIBaseLanguageModelCallOptions.html)
*
* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.
* They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below:
*
* ```typescript
* // When calling `.bind`, call options should be passed via the first argument
* const llmWithArgsBound = llm.bind({
* stop: ["\n"],
* tools: [...],
* });
*
* // When calling `.bindTools`, call options should be passed via the second argument
* const llmWithTools = llm.bindTools(
* [...],
* {
* tool_choice: "auto",
* }
* );
* ```
*
* ## Examples
*
* <details open>
* <summary><strong>Instantiate</strong></summary>
*
* ```typescript
* import { ChatVertexAI } from '@langchain/google-vertexai';
*
* const llm = new ChatVertexAI({
* model: "gemini-1.5-pro",
* temperature: 0,
* // other params...
* });
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Invoking</strong></summary>
*
* ```typescript
* const input = `Translate "I love programming" into French.`;
*
* // Models also accept a list of chat messages or a formatted prompt
* const result = await llm.invoke(input);
* console.log(result);
* ```
*
* ```txt
* AIMessageChunk {
* "content": "\"J'adore programmer\" \n\nHere's why this is the best translation:\n\n* **J'adore** means \"I love\" and conveys a strong passion.\n* **Programmer** is the French verb for \"to program.\"\n\nThis translation is natural and idiomatic in French. \n",
* "additional_kwargs": {},
* "response_metadata": {},
* "tool_calls": [],
* "tool_call_chunks": [],
* "invalid_tool_calls": [],
* "usage_metadata": {
* "input_tokens": 9,
* "output_tokens": 63,
* "total_tokens": 72
* }
* }
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Streaming Chunks</strong></summary>
*
* ```typescript
* for await (const chunk of await llm.stream(input)) {
* console.log(chunk);
* }
* ```
*
* ```txt
* AIMessageChunk {
* "content": "\"",
* "additional_kwargs": {},
* "response_metadata": {},
* "tool_calls": [],
* "tool_call_chunks": [],
* "invalid_tool_calls": []
* }
* AIMessageChunk {
* "content": "J'adore programmer\" \n",
* "additional_kwargs": {},
* "response_metadata": {},
* "tool_calls": [],
* "tool_call_chunks": [],
* "invalid_tool_calls": []
* }
* AIMessageChunk {
* "content": "",
* "additional_kwargs": {},
* "response_metadata": {},
* "tool_calls": [],
* "tool_call_chunks": [],
* "invalid_tool_calls": []
* }
* AIMessageChunk {
* "content": "",
* "additional_kwargs": {},
* "response_metadata": {
* "finishReason": "stop"
* },
* "tool_calls": [],
* "tool_call_chunks": [],
* "invalid_tool_calls": [],
* "usage_metadata": {
* "input_tokens": 9,
* "output_tokens": 8,
* "total_tokens": 17
* }
* }
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Aggregate Streamed Chunks</strong></summary>
*
* ```typescript
* import { AIMessageChunk } from '@langchain/core/messages';
* import { concat } from '@langchain/core/utils/stream';
*
* const stream = await llm.stream(input);
* let full: AIMessageChunk | undefined;
* for await (const chunk of stream) {
* full = !full ? chunk : concat(full, chunk);
* }
* console.log(full);
* ```
*
* ```txt
* AIMessageChunk {
* "content": "\"J'adore programmer\" \n",
* "additional_kwargs": {},
* "response_metadata": {
* "finishReason": "stop"
* },
* "tool_calls": [],
* "tool_call_chunks": [],
* "invalid_tool_calls": [],
* "usage_metadata": {
* "input_tokens": 9,
* "output_tokens": 8,
* "total_tokens": 17
* }
* }
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Bind tools</strong></summary>
*
* ```typescript
* import { z } from 'zod';
*
* const GetWeather = {
* name: "GetWeather",
* description: "Get the current weather in a given location",
* schema: z.object({
* location: z.string().describe("The city and state, e.g. San Francisco, CA")
* }),
* }
*
* const GetPopulation = {
* name: "GetPopulation",
* description: "Get the current population in a given location",
* schema: z.object({
* location: z.string().describe("The city and state, e.g. San Francisco, CA")
* }),
* }
*
* const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);
* const aiMsg = await llmWithTools.invoke(
* "Which city is hotter today and which is bigger: LA or NY?"
* );
* console.log(aiMsg.tool_calls);
* ```
*
* ```txt
* [
* {
* name: 'GetPopulation',
* args: { location: 'New York City, NY' },
* id: '33c1c1f47e2f492799c77d2800a43912',
* type: 'tool_call'
* }
* ]
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Structured Output</strong></summary>
*
* ```typescript
* import { z } from 'zod';
*
* const Joke = z.object({
* setup: z.string().describe("The setup of the joke"),
* punchline: z.string().describe("The punchline to the joke"),
* rating: z.number().optional().describe("How funny the joke is, from 1 to 10")
* }).describe('Joke to tell user.');
*
* const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" });
* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats");
* console.log(jokeResult);
* ```
*
* ```txt
* {
* setup: 'What do you call a cat that loves to bowl?',
* punchline: 'An alley cat!'
* }
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Usage Metadata</strong></summary>
*
* ```typescript
* const aiMsgForMetadata = await llm.invoke(input);
* console.log(aiMsgForMetadata.usage_metadata);
* ```
*
* ```txt
* { input_tokens: 9, output_tokens: 8, total_tokens: 17 }
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Stream Usage Metadata</strong></summary>
*
* ```typescript
* const streamForMetadata = await llm.stream(
* input,
* {
* streamUsage: true
* }
* );
* let fullForMetadata: AIMessageChunk | undefined;
* for await (const chunk of streamForMetadata) {
* fullForMetadata = !fullForMetadata ? chunk : concat(fullForMetadata, chunk);
* }
* console.log(fullForMetadata?.usage_metadata);
* ```
*
* ```txt
* { input_tokens: 9, output_tokens: 8, total_tokens: 17 }
* ```
* </details>
*
* <br />
*/
export class ChatVertexAI extends ChatGoogle {
lc_namespace = ["langchain", "chat_models", "vertexai"];
static lc_name() {
return "ChatVertexAI";
}
constructor(fields?: ChatVertexAIInput) {
super({
...fields,
platformType: "gcp",
});
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/src/embeddings.ts
|
import {
type GoogleEmbeddingsInput,
GoogleEmbeddings,
} from "@langchain/google-gauth";
/**
* Input to a Google Vertex AI embeddings class.
*/
export interface GoogleVertexAIEmbeddingsInput extends GoogleEmbeddingsInput {}
/**
* Integration with a Google Vertex AI embeddings model using
* the "@langchain/google-gauth" package for auth.
*/
export class VertexAIEmbeddings extends GoogleEmbeddings {
static lc_name() {
return "VertexAIEmbeddings";
}
constructor(fields: GoogleVertexAIEmbeddingsInput) {
super({
...fields,
platformType: "gcp",
});
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/src/utils.ts
|
export * from "@langchain/google-gauth/utils";
|
0
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/src
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/src/tests/llms.test.ts
|
/* eslint-disable no-process-env */
import { test, expect } from "@jest/globals";
import { VertexAI } from "../llms.js";
test("Serialization", () => {
const model = new VertexAI();
expect(JSON.stringify(model)).toEqual(
`{"lc":1,"type":"constructor","id":["langchain","llms","vertexai","VertexAI"],"kwargs":{"platform_type":"gcp"}}`
);
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/src
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/src/tests/chat_models.standard.int.test.ts
|
/* eslint-disable no-process-env */
import { test, expect } from "@jest/globals";
import { ChatModelIntegrationTests } from "@langchain/standard-tests";
import { AIMessageChunk } from "@langchain/core/messages";
import { GoogleAIBaseLanguageModelCallOptions } from "@langchain/google-common";
import { ChatVertexAI } from "../chat_models.js";
class ChatVertexAIStandardIntegrationTests extends ChatModelIntegrationTests<
GoogleAIBaseLanguageModelCallOptions,
AIMessageChunk
> {
constructor() {
if (!process.env.GOOGLE_APPLICATION_CREDENTIALS) {
throw new Error(
"GOOGLE_APPLICATION_CREDENTIALS must be set to run standard integration tests."
);
}
super({
Cls: ChatVertexAI,
chatModelHasToolCalling: true,
chatModelHasStructuredOutput: true,
supportsParallelToolCalls: true,
invokeResponseType: AIMessageChunk,
constructorArgs: {
model: "gemini-1.5-pro",
},
});
}
async testToolMessageHistoriesListContent() {
this.skipTestMessage(
"testToolMessageHistoriesListContent",
"ChatVertexAI",
"Not implemented."
);
}
async testInvokeMoreComplexTools() {
this.skipTestMessage(
"testInvokeMoreComplexTools",
"ChatVertexAI",
"Google VertexAI does not support tool schemas which contain object with unknown/any parameters." +
"Google VertexAI only supports objects in schemas when the parameters are defined."
);
}
async testParallelToolCalling() {
// Pass `true` in the second argument to only verify it can support parallel tool calls in the message history.
// This is because the model struggles to actually call parallel tools.
await super.testParallelToolCalling(undefined, true);
}
}
const testClass = new ChatVertexAIStandardIntegrationTests();
test("ChatVertexAIStandardIntegrationTests", async () => {
const testResults = await testClass.runTests();
expect(testResults).toBe(true);
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/src
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/src/tests/llms.int.test.ts
|
import { test } from "@jest/globals";
import {
AIMessage,
BaseMessage,
HumanMessageChunk,
MessageContentComplex,
} from "@langchain/core/messages";
import { ChatPromptValue } from "@langchain/core/prompt_values";
import { VertexAI } from "../llms.js";
const imgData = {
blueSquare:
"iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAIAAAACUFjqAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH6AIbFwQSRaexCAAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAAJklEQVQY02P8//8/A27AxIAXsEAor31f0CS2OfEQ1j2Q0owU+RsAGNUJD2/04PgAAAAASUVORK5CYII=",
};
describe("GAuth LLM", () => {
test("platform", async () => {
const model = new VertexAI();
expect(model.platform).toEqual("gcp");
});
test("call", async () => {
const model = new VertexAI();
const res = await model.invoke("1 + 1 = ");
if (res.length === 1) {
expect(res).toBe("2");
} else {
expect(res.length).toBeGreaterThan(0);
// console.log("call result:", res);
}
});
test("generate", async () => {
const model = new VertexAI();
const res = await model.generate(["Print hello world."]);
expect(res).toHaveProperty("generations");
expect(res.generations.length).toBeGreaterThan(0);
expect(res.generations[0].length).toBeGreaterThan(0);
expect(res.generations[0][0]).toHaveProperty("text");
// console.log("generate result:", JSON.stringify(res, null, 2));
});
test("stream", async () => {
const model = new VertexAI();
const stream = await model.stream(
"What is the answer to live, the universe, and everything? Be verbose."
);
const chunks = [];
for await (const chunk of stream) {
chunks.push(chunk);
}
expect(chunks.length).toBeGreaterThan(1);
});
test("predictMessage image", async () => {
const model = new VertexAI({
modelName: "gemini-pro-vision",
});
const message: MessageContentComplex[] = [
{
type: "text",
text: "What is in this image?",
},
{
type: "image_url",
image_url: `data:image/png;base64,${imgData.blueSquare}`,
},
];
const messages: BaseMessage[] = [
new HumanMessageChunk({ content: message }),
];
const res = await model.predictMessages(messages);
expect(res).toBeInstanceOf(AIMessage);
expect(Array.isArray(res.content)).toEqual(true);
expect(res.content[0]).toHaveProperty("text");
// console.log("res", res);
});
test("invoke image", async () => {
const model = new VertexAI({
modelName: "gemini-pro-vision",
});
const message: MessageContentComplex[] = [
{
type: "text",
text: "What is in this image?",
},
{
type: "image_url",
image_url: `data:image/png;base64,${imgData.blueSquare}`,
},
];
const messages: BaseMessage[] = [
new HumanMessageChunk({ content: message }),
];
const input = new ChatPromptValue(messages);
const res = await model.invoke(input);
expect(res).toBeDefined();
expect(res.length).toBeGreaterThan(0);
// console.log("res", res);
});
});
describe("GAuth LLM gai", () => {
test("platform", async () => {
const model = new VertexAI({
platformType: "gai",
});
expect(model.platform).toEqual("gai");
});
/*
* This test currently fails in AI Studio due to zealous safety systems
*/
test.skip("call", async () => {
const model = new VertexAI({
platformType: "gai",
});
const res = await model.invoke("1 + 1 = ");
if (res.length === 1) {
expect(res).toBe("2");
} else {
// console.log("call result:", res);
expect(res.length).toBeGreaterThan(0);
}
});
test("call", async () => {
const model = new VertexAI({
platformType: "gai",
});
const res = await model.invoke("If the time is 1:00, what time is it?");
expect(res.length).toBeGreaterThan(0);
expect(res.substring(0, 4)).toEqual("1:00");
});
test("generate", async () => {
const model = new VertexAI({
platformType: "gai",
});
const res = await model.generate(["Print hello world."]);
expect(res).toHaveProperty("generations");
expect(res.generations.length).toBeGreaterThan(0);
expect(res.generations[0].length).toBeGreaterThan(0);
expect(res.generations[0][0]).toHaveProperty("text");
// console.log("generate result:", JSON.stringify(res, null, 2));
});
test("stream", async () => {
const model = new VertexAI({
platformType: "gai",
});
const stream = await model.stream(
"What is the answer to live, the universe, and everything? Be verbose."
);
const chunks = [];
try {
for await (const chunk of stream) {
chunks.push(chunk);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (xx: any) {
expect(xx?.message).toEqual("Finish reason: RECITATION");
}
expect(chunks.length).toBeGreaterThan(1);
});
test("predictMessage image", async () => {
const model = new VertexAI({
platformType: "gai",
modelName: "gemini-pro-vision",
});
const message: MessageContentComplex[] = [
{
type: "text",
text: "What is in this image?",
},
{
type: "image_url",
image_url: `data:image/png;base64,${imgData.blueSquare}`,
},
];
const messages: BaseMessage[] = [
new HumanMessageChunk({ content: message }),
];
const res = await model.predictMessages(messages);
expect(res).toBeInstanceOf(AIMessage);
expect(Array.isArray(res.content)).toEqual(true);
expect(res.content[0]).toHaveProperty("text");
// console.log("res", res);
});
test("invoke image", async () => {
const model = new VertexAI({
platformType: "gai",
modelName: "gemini-pro-vision",
});
const message: MessageContentComplex[] = [
{
type: "text",
text: "What is in this image?",
},
{
type: "image_url",
image_url: `data:image/png;base64,${imgData.blueSquare}`,
},
];
const messages: BaseMessage[] = [
new HumanMessageChunk({ content: message }),
];
const input = new ChatPromptValue(messages);
const res = await model.invoke(input);
expect(res).toBeDefined();
expect(res.length).toBeGreaterThan(0);
// console.log("res", res);
});
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/src
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/src/tests/chat_models.standard.test.ts
|
/* eslint-disable no-process-env */
import { test, expect } from "@jest/globals";
import { ChatModelUnitTests } from "@langchain/standard-tests";
import { AIMessageChunk } from "@langchain/core/messages";
import { GoogleAIBaseLanguageModelCallOptions } from "@langchain/google-common";
import { ChatVertexAI } from "../chat_models.js";
class ChatVertexAIStandardUnitTests extends ChatModelUnitTests<
GoogleAIBaseLanguageModelCallOptions,
AIMessageChunk
> {
constructor() {
super({
Cls: ChatVertexAI,
chatModelHasToolCalling: true,
chatModelHasStructuredOutput: true,
constructorArgs: {},
});
// This must be set so method like `.bindTools` or `.withStructuredOutput`
// which we call after instantiating the model will work.
// (constructor will throw if API key is not set)
process.env.GOOGLE_APPLICATION_CREDENTIALS = "test";
}
testChatModelInitApiKey() {
this.skipTestMessage(
"testChatModelInitApiKey",
"ChatVertexAI (gauth)",
this.multipleApiKeysRequiredMessage
);
}
}
const testClass = new ChatVertexAIStandardUnitTests();
test("ChatVertexAIStandardUnitTests", () => {
const testResults = testClass.runTests();
expect(testResults).toBe(true);
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/src
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/src/tests/chat_models.int.test.ts
|
import { expect, test } from "@jest/globals";
import fs from "fs/promises";
import { BaseLanguageModelInput } from "@langchain/core/language_models/base";
import { ChatPromptValue } from "@langchain/core/prompt_values";
import {
AIMessage,
AIMessageChunk,
BaseMessage,
BaseMessageChunk,
BaseMessageLike,
HumanMessage,
HumanMessageChunk,
MessageContentComplex,
SystemMessage,
ToolMessage,
} from "@langchain/core/messages";
import {
BlobStoreGoogleCloudStorage,
ChatGoogle,
} from "@langchain/google-gauth";
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { concat } from "@langchain/core/utils/stream";
import {
BackedBlobStore,
MediaBlob,
MediaManager,
ReadThroughBlobStore,
SimpleWebBlobStore,
} from "@langchain/google-common/experimental/utils/media_core";
import { GoogleCloudStorageUri } from "@langchain/google-common/experimental/media";
import {
ChatPromptTemplate,
MessagesPlaceholder,
} from "@langchain/core/prompts";
import { InMemoryStore } from "@langchain/core/stores";
import { BaseCallbackHandler } from "@langchain/core/callbacks/base";
import {
GoogleRequestLogger,
GoogleRequestRecorder,
} from "@langchain/google-common";
import { GeminiTool } from "../types.js";
import { ChatVertexAI } from "../chat_models.js";
const weatherTool = tool((_) => "no-op", {
name: "get_weather",
description:
"Get the weather of a specific location and return the temperature in Celsius.",
schema: z.object({
location: z.string().describe("The name of city to get the weather for."),
}),
});
const calculatorTool = tool((_) => "no-op", {
name: "calculator",
description: "Calculate the result of a math expression.",
schema: z.object({
expression: z.string().describe("The math expression to calculate."),
}),
});
describe("GAuth Gemini Chat", () => {
let recorder: GoogleRequestRecorder;
let callbacks: BaseCallbackHandler[];
beforeEach(() => {
recorder = new GoogleRequestRecorder();
callbacks = [recorder, new GoogleRequestLogger()];
});
test("invoke", async () => {
const model = new ChatVertexAI({
callbacks,
});
const res = await model.invoke("What is 1 + 1?");
expect(res).toBeDefined();
expect(res._getType()).toEqual("ai");
const aiMessage = res as AIMessageChunk;
expect(aiMessage.content).toBeDefined();
expect(typeof aiMessage.content).toBe("string");
const text = aiMessage.content as string;
expect(text).toMatch(/(1 + 1 (equals|is|=) )?2.? ?/);
});
test("generate", async () => {
const model = new ChatVertexAI();
const messages: BaseMessage[] = [
new SystemMessage(
"You will reply to all requests to flip a coin with either H, indicating heads, or T, indicating tails."
),
new HumanMessage("Flip it"),
new AIMessage("T"),
new HumanMessage("Flip the coin again"),
];
const res = await model.predictMessages(messages);
expect(res).toBeDefined();
expect(res._getType()).toEqual("ai");
const aiMessage = res as AIMessageChunk;
expect(aiMessage.content).toBeDefined();
expect(typeof aiMessage.content).toBe("string");
const text = aiMessage.content as string;
expect(["H", "T"]).toContainEqual(text);
});
test("stream", async () => {
const model = new ChatVertexAI({
callbacks,
});
const input: BaseLanguageModelInput = new ChatPromptValue([
new SystemMessage(
"You will reply to all requests to flip a coin with either H, indicating heads, or T, indicating tails."
),
new HumanMessage("Flip it"),
new AIMessage("T"),
new HumanMessage("Flip the coin again"),
]);
const res = await model.stream(input);
const resArray: BaseMessageChunk[] = [];
for await (const chunk of res) {
resArray.push(chunk);
}
expect(resArray).toBeDefined();
expect(resArray.length).toBeGreaterThanOrEqual(1);
const lastChunk = resArray[resArray.length - 1];
expect(lastChunk).toBeDefined();
expect(lastChunk._getType()).toEqual("ai");
});
test("function", async () => {
const tools: GeminiTool[] = [
{
functionDeclarations: [
{
name: "test",
description:
"Run a test with a specific name and get if it passed or failed",
parameters: {
type: "object",
properties: {
testName: {
type: "string",
description: "The name of the test that should be run.",
},
},
required: ["testName"],
},
},
],
},
];
const model = new ChatVertexAI().bind({ tools });
const result = await model.invoke("Run a test on the cobalt project");
expect(result).toHaveProperty("content");
expect(result.content).toBe("");
const args = result?.lc_kwargs?.additional_kwargs;
expect(args).toBeDefined();
expect(args).toHaveProperty("tool_calls");
expect(Array.isArray(args.tool_calls)).toBeTruthy();
expect(args.tool_calls).toHaveLength(1);
const call = args.tool_calls[0];
expect(call).toHaveProperty("type");
expect(call.type).toBe("function");
expect(call).toHaveProperty("function");
const func = call.function;
expect(func).toBeDefined();
expect(func).toHaveProperty("name");
expect(func.name).toBe("test");
expect(func).toHaveProperty("arguments");
expect(typeof func.arguments).toBe("string");
expect(func.arguments.replaceAll("\n", "")).toBe('{"testName":"cobalt"}');
});
test("function reply", async () => {
const tools: GeminiTool[] = [
{
functionDeclarations: [
{
name: "test",
description:
"Run a test with a specific name and get if it passed or failed",
parameters: {
type: "object",
properties: {
testName: {
type: "string",
description: "The name of the test that should be run.",
},
},
required: ["testName"],
},
},
],
},
];
const model = new ChatVertexAI().bind({ tools });
const toolResult = {
testPassed: true,
};
const messages: BaseMessageLike[] = [
new HumanMessage("Run a test on the cobalt project."),
new AIMessage("", {
tool_calls: [
{
id: "test",
type: "function",
function: {
name: "test",
arguments: '{"testName":"cobalt"}',
},
},
],
}),
new ToolMessage(JSON.stringify(toolResult), "test"),
];
const res = await model.stream(messages);
const resArray: BaseMessageChunk[] = [];
for await (const chunk of res) {
resArray.push(chunk);
}
// console.log(JSON.stringify(resArray, null, 2));
});
test("withStructuredOutput", async () => {
const tool = {
name: "get_weather",
description:
"Get the weather of a specific location and return the temperature in Celsius.",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "The name of city to get the weather for.",
},
},
required: ["location"],
},
};
const model = new ChatVertexAI().withStructuredOutput(tool);
const result = await model.invoke("What is the weather in Paris?");
expect(result).toHaveProperty("location");
});
test("media - fileData", async () => {
class MemStore extends InMemoryStore<MediaBlob> {
get length() {
return Object.keys(this.store).length;
}
}
const aliasMemory = new MemStore();
const aliasStore = new BackedBlobStore({
backingStore: aliasMemory,
defaultFetchOptions: {
actionIfBlobMissing: undefined,
},
});
const backingStore = new BlobStoreGoogleCloudStorage({
uriPrefix: new GoogleCloudStorageUri("gs://test-langchainjs/mediatest/"),
defaultStoreOptions: {
actionIfInvalid: "prefixPath",
},
});
const blobStore = new ReadThroughBlobStore({
baseStore: aliasStore,
backingStore,
});
const resolver = new SimpleWebBlobStore();
const mediaManager = new MediaManager({
store: blobStore,
resolvers: [resolver],
});
const model = new ChatGoogle({
modelName: "gemini-1.5-flash",
apiConfig: {
mediaManager,
},
});
const message: MessageContentComplex[] = [
{
type: "text",
text: "What is in this image?",
},
{
type: "media",
fileUri: "https://js.langchain.com/v0.2/img/brand/wordmark.png",
},
];
const messages: BaseMessage[] = [
new HumanMessageChunk({ content: message }),
];
try {
const res = await model.invoke(messages);
console.log(res);
expect(res).toBeDefined();
expect(res._getType()).toEqual("ai");
const aiMessage = res as AIMessageChunk;
expect(aiMessage.content).toBeDefined();
expect(typeof aiMessage.content).toBe("string");
const text = aiMessage.content as string;
expect(text).toMatch(/LangChain/);
} catch (e) {
console.error(e);
throw e;
}
});
test("Stream token count usage_metadata", async () => {
const model = new ChatVertexAI({
temperature: 0,
maxOutputTokens: 10,
});
let res: AIMessageChunk | null = null;
for await (const chunk of await model.stream(
"Why is the sky blue? Be concise."
)) {
if (!res) {
res = chunk;
} else {
res = res.concat(chunk);
}
}
// console.log(res);
expect(res?.usage_metadata).toBeDefined();
if (!res?.usage_metadata) {
return;
}
expect(res.usage_metadata.input_tokens).toBeGreaterThan(1);
expect(res.usage_metadata.output_tokens).toBeGreaterThan(1);
expect(res.usage_metadata.total_tokens).toBe(
res.usage_metadata.input_tokens + res.usage_metadata.output_tokens
);
});
test("streamUsage excludes token usage", async () => {
const model = new ChatVertexAI({
temperature: 0,
streamUsage: false,
});
let res: AIMessageChunk | null = null;
for await (const chunk of await model.stream(
"Why is the sky blue? Be concise."
)) {
if (!res) {
res = chunk;
} else {
res = res.concat(chunk);
}
}
// console.log(res);
expect(res?.usage_metadata).not.toBeDefined();
});
test("Invoke token count usage_metadata", async () => {
const model = new ChatVertexAI({
temperature: 0,
maxOutputTokens: 10,
});
const res = await model.invoke("Why is the sky blue? Be concise.");
// console.log(res);
expect(res?.usage_metadata).toBeDefined();
if (!res?.usage_metadata) {
return;
}
expect(res.usage_metadata.input_tokens).toBeGreaterThan(1);
expect(res.usage_metadata.output_tokens).toBeGreaterThan(1);
expect(res.usage_metadata.total_tokens).toBe(
res.usage_metadata.input_tokens + res.usage_metadata.output_tokens
);
});
test("Streaming true constructor param will stream", async () => {
const modelWithStreaming = new ChatVertexAI({
maxOutputTokens: 50,
streaming: true,
});
let totalTokenCount = 0;
let tokensString = "";
const result = await modelWithStreaming.invoke("What is 1 + 1?", {
callbacks: [
{
handleLLMNewToken: (tok) => {
totalTokenCount += 1;
tokensString += tok;
},
},
],
});
expect(result).toBeDefined();
expect(result.content).toBe(tokensString);
expect(totalTokenCount).toBeGreaterThan(1);
});
test("Can force a model to invoke a tool", async () => {
const model = new ChatVertexAI({
model: "gemini-1.5-pro",
});
const modelWithTools = model.bind({
tools: [calculatorTool, weatherTool],
tool_choice: "calculator",
});
const result = await modelWithTools.invoke(
"Whats the weather like in paris today? What's 1836 plus 7262?"
);
expect(result.tool_calls).toHaveLength(1);
expect(result.tool_calls?.[0]).toBeDefined();
if (!result.tool_calls?.[0]) return;
expect(result.tool_calls?.[0].name).toBe("calculator");
expect(result.tool_calls?.[0].args).toHaveProperty("expression");
});
test("ChatGoogleGenerativeAI can stream tools", async () => {
const model = new ChatVertexAI({});
const weatherTool = tool(
(_) => "The weather in San Francisco today is 18 degrees and sunny.",
{
name: "current_weather_tool",
description: "Get the current weather for a given location.",
schema: z.object({
location: z.string().describe("The location to get the weather for."),
}),
}
);
const modelWithTools = model.bindTools([weatherTool]);
const stream = await modelWithTools.stream(
"Whats the weather like today in San Francisco?"
);
let finalChunk: AIMessageChunk | undefined;
for await (const chunk of stream) {
finalChunk = !finalChunk ? chunk : concat(finalChunk, chunk);
}
expect(finalChunk).toBeDefined();
if (!finalChunk) return;
const toolCalls = finalChunk.tool_calls;
expect(toolCalls).toBeDefined();
if (!toolCalls) {
throw new Error("tool_calls not in response");
}
expect(toolCalls.length).toBe(1);
expect(toolCalls[0].name).toBe("current_weather_tool");
expect(toolCalls[0].args).toHaveProperty("location");
});
async function fileToBase64(filePath: string): Promise<string> {
const fileData = await fs.readFile(filePath);
const base64String = Buffer.from(fileData).toString("base64");
return base64String;
}
test("Gemini can understand audio", async () => {
// Update this with the correct path to an audio file on your machine.
const audioPath =
"../langchain-google-genai/src/tests/data/gettysburg10.wav";
const audioMimeType = "audio/wav";
const model = new ChatVertexAI({
model: "gemini-1.5-flash",
temperature: 0,
maxRetries: 0,
});
const audioBase64 = await fileToBase64(audioPath);
const prompt = ChatPromptTemplate.fromMessages([
new MessagesPlaceholder("audio"),
]);
const chain = prompt.pipe(model);
const response = await chain.invoke({
audio: new HumanMessage({
content: [
{
type: "media",
mimeType: audioMimeType,
data: audioBase64,
},
{
type: "text",
text: "Summarize the content in this audio. ALso, what is the speaker's tone?",
},
],
}),
});
expect(typeof response.content).toBe("string");
expect((response.content as string).length).toBeGreaterThan(15);
});
});
describe("GAuth Anthropic Chat", () => {
let recorder: GoogleRequestRecorder;
let callbacks: BaseCallbackHandler[];
// const modelName: string = "claude-3-5-sonnet@20240620";
// const modelName: string = "claude-3-sonnet@20240229";
const modelName: string = "claude-3-5-sonnet-v2@20241022";
beforeEach(() => {
recorder = new GoogleRequestRecorder();
callbacks = [recorder, new GoogleRequestLogger()];
});
test("invoke", async () => {
const model = new ChatVertexAI({
modelName,
callbacks,
});
const res = await model.invoke("What is 1 + 1?");
expect(res).toBeDefined();
expect(res._getType()).toEqual("ai");
const aiMessage = res as AIMessageChunk;
expect(aiMessage.content).toBeDefined();
expect(typeof aiMessage.content).toBe("string");
const text = aiMessage.content as string;
expect(text).toMatch(/(1 + 1 (equals|is|=) )?2.? ?/);
const connection = recorder?.request?.connection;
expect(connection?.url).toEqual(
`https://us-east5-aiplatform.googleapis.com/v1/projects/test-vertex-ai-382612/locations/us-east5/publishers/anthropic/models/${modelName}:rawPredict`
);
console.log(JSON.stringify(aiMessage, null, 1));
console.log(aiMessage.lc_kwargs);
});
test("stream", async () => {
const model = new ChatVertexAI({
modelName,
callbacks,
});
const stream = await model.stream("How are you today? Be verbose.");
const chunks = [];
for await (const chunk of stream) {
console.log(chunk);
chunks.push(chunk);
}
expect(chunks.length).toBeGreaterThan(1);
});
test("tool invocation", async () => {
const model = new ChatVertexAI({
modelName,
callbacks,
});
const modelWithTools = model.bind({
tools: [weatherTool],
});
const result = await modelWithTools.invoke(
"Whats the weather like in paris today?"
);
const request = recorder?.request ?? {};
const data = request?.data;
expect(data).toHaveProperty("tools");
expect(data.tools).toHaveLength(1);
expect(result.tool_calls).toHaveLength(1);
expect(result.tool_calls?.[0]).toBeDefined();
expect(result.tool_calls?.[0].name).toBe("get_weather");
expect(result.tool_calls?.[0].args).toHaveProperty("location");
});
test("stream tools", async () => {
const model = new ChatVertexAI({
modelName,
callbacks,
});
const weatherTool = tool(
(_) => "The weather in San Francisco today is 18 degrees and sunny.",
{
name: "current_weather_tool",
description: "Get the current weather for a given location.",
schema: z.object({
location: z.string().describe("The location to get the weather for."),
}),
}
);
const modelWithTools = model.bindTools([weatherTool]);
const stream = await modelWithTools.stream(
"Whats the weather like today in San Francisco?"
);
let finalChunk: AIMessageChunk | undefined;
for await (const chunk of stream) {
finalChunk = !finalChunk ? chunk : concat(finalChunk, chunk);
}
expect(finalChunk).toBeDefined();
const toolCalls = finalChunk?.tool_calls;
expect(toolCalls).toBeDefined();
expect(toolCalls?.length).toBe(1);
expect(toolCalls?.[0].name).toBe("current_weather_tool");
expect(toolCalls?.[0].args).toHaveProperty("location");
});
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/src
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/src/tests/embeddings.int.test.ts
|
import { test, expect } from "@jest/globals";
import { VertexAIEmbeddings } from "../embeddings.js";
test("Test VertexAIEmbeddings.embedQuery", async () => {
const embeddings = new VertexAIEmbeddings({
model: "textembedding-gecko",
});
const res = await embeddings.embedQuery("Hello world");
expect(typeof res[0]).toBe("number");
});
test("Test VertexAIEmbeddings.embedDocuments", async () => {
const embeddings = new VertexAIEmbeddings({
model: "text-embedding-004",
});
const res = await embeddings.embedDocuments([
"Hello world",
"Bye bye",
"we need",
"at least",
"six documents",
"to test pagination",
]);
// console.log(res);
expect(res).toHaveLength(6);
res.forEach((r) => {
expect(typeof r[0]).toBe("number");
});
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/src
|
lc_public_repos/langchainjs/libs/langchain-google-vertexai/src/tests/chat_models.test.ts
|
/* eslint-disable no-process-env */
import { test, expect } from "@jest/globals";
import { ChatVertexAI } from "../chat_models.js";
test("Serialization", () => {
const model = new ChatVertexAI();
expect(JSON.stringify(model)).toEqual(
`{"lc":1,"type":"constructor","id":["langchain","chat_models","vertexai","ChatVertexAI"],"kwargs":{"platform_type":"gcp"}}`
);
});
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-qdrant/tsconfig.json
|
{
"extends": "@tsconfig/recommended",
"compilerOptions": {
"outDir": "../dist",
"rootDir": "./src",
"target": "ES2021",
"lib": ["ES2021", "ES2022.Object", "DOM"],
"module": "ES2020",
"moduleResolution": "nodenext",
"esModuleInterop": true,
"declaration": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"useDefineForClassFields": true,
"strictPropertyInitialization": false,
"allowJs": true,
"strict": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "docs"]
}
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-qdrant/LICENSE
|
The MIT License
Copyright (c) 2023 LangChain
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-qdrant/jest.config.cjs
|
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: "ts-jest/presets/default-esm",
testEnvironment: "./jest.env.cjs",
modulePathIgnorePatterns: ["dist/", "docs/"],
moduleNameMapper: {
"^(\\.{1,2}/.*)\\.js$": "$1",
},
transform: {
"^.+\\.tsx?$": ["@swc/jest"],
},
transformIgnorePatterns: [
"/node_modules/",
"\\.pnp\\.[^\\/]+$",
"./scripts/jest-setup-after-env.js",
],
setupFiles: ["dotenv/config"],
testTimeout: 20_000,
passWithNoTests: true,
collectCoverageFrom: ["src/**/*.ts"],
};
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-qdrant/jest.env.cjs
|
const { TestEnvironment } = require("jest-environment-node");
class AdjustedTestEnvironmentToSupportFloat32Array extends TestEnvironment {
constructor(config, context) {
// Make `instanceof Float32Array` return true in tests
// to avoid https://github.com/xenova/transformers.js/issues/57 and https://github.com/jestjs/jest/issues/2549
super(config, context);
this.global.Float32Array = Float32Array;
}
}
module.exports = AdjustedTestEnvironmentToSupportFloat32Array;
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-qdrant/README.md
|
# @langchain/qdrant
This package contains the LangChain.js integration for the [Qdrant](https://qdrant.tech/) vector database.
## Installation
```bash
npm install @langchain/qdrant
```
## Development
To develop the this package, you'll need to follow these instructions:
### Install dependencies
```bash
yarn install
```
### Build the package
```bash
yarn build
```
Or from the repo root:
```bash
yarn build --filter=@langchain/qdrant
```
### Run tests
Test files should live within a `tests/` file in the `src/` folder. Unit tests should end in `.test.ts` and integration tests should
end in `.int.test.ts`:
```bash
$ yarn test
$ yarn test:int
```
### Lint & Format
Run the linter & formatter to ensure your code is up to standard:
```bash
yarn lint && yarn format
```
### Adding new entrypoints
If you add a new file to be exported, either import & re-export from `src/index.ts`, or add it to the `entrypoints` field in the `config` variable located inside `langchain.config.js` and run `yarn build` to generate the new entrypoint.
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-qdrant/.release-it.json
|
{
"github": {
"release": true,
"autoGenerate": true,
"tokenRef": "GITHUB_TOKEN_RELEASE"
},
"npm": {
"versionArgs": ["--workspaces-update=false"]
}
}
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-qdrant/.eslintrc.cjs
|
module.exports = {
extends: [
"airbnb-base",
"eslint:recommended",
"prettier",
"plugin:@typescript-eslint/recommended",
],
parserOptions: {
ecmaVersion: 12,
parser: "@typescript-eslint/parser",
project: "./tsconfig.json",
sourceType: "module",
},
plugins: ["@typescript-eslint", "no-instanceof"],
ignorePatterns: [
".eslintrc.cjs",
"scripts",
"node_modules",
"dist",
"dist-cjs",
"*.js",
"*.cjs",
"*.d.ts",
],
rules: {
"no-process-env": 2,
"no-instanceof/no-instanceof": 2,
"@typescript-eslint/explicit-module-boundary-types": 0,
"@typescript-eslint/no-empty-function": 0,
"@typescript-eslint/no-shadow": 0,
"@typescript-eslint/no-empty-interface": 0,
"@typescript-eslint/no-use-before-define": ["error", "nofunc"],
"@typescript-eslint/no-unused-vars": ["warn", { args: "none" }],
"@typescript-eslint/no-floating-promises": "error",
"@typescript-eslint/no-misused-promises": "error",
camelcase: 0,
"class-methods-use-this": 0,
"import/extensions": [2, "ignorePackages"],
"import/no-extraneous-dependencies": [
"error",
{ devDependencies: ["**/*.test.ts"] },
],
"import/no-unresolved": 0,
"import/prefer-default-export": 0,
"keyword-spacing": "error",
"max-classes-per-file": 0,
"max-len": 0,
"no-await-in-loop": 0,
"no-bitwise": 0,
"no-console": 0,
"no-restricted-syntax": 0,
"no-shadow": 0,
"no-continue": 0,
"no-void": 0,
"no-underscore-dangle": 0,
"no-use-before-define": 0,
"no-useless-constructor": 0,
"no-return-await": 0,
"consistent-return": 0,
"no-else-return": 0,
"func-names": 0,
"no-lonely-if": 0,
"prefer-rest-params": 0,
"new-cap": ["error", { properties: false, capIsNew: false }],
},
overrides: [
{
files: ['**/*.test.ts'],
rules: {
'@typescript-eslint/no-unused-vars': 'off'
}
}
]
};
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-qdrant/langchain.config.js
|
import { resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url";
/**
* @param {string} relativePath
* @returns {string}
*/
function abs(relativePath) {
return resolve(dirname(fileURLToPath(import.meta.url)), relativePath);
}
export const config = {
internals: [/node\:/, /@langchain\/core\//],
entrypoints: {
index: "index",
},
requiresOptionalDependency: [],
tsConfigPath: resolve("./tsconfig.json"),
cjsSource: "./dist-cjs",
cjsDestination: "./dist",
abs,
};
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-qdrant/package.json
|
{
"name": "@langchain/qdrant",
"version": "0.1.1",
"description": "LangChain.js integration for the Qdrant vector database",
"type": "module",
"engines": {
"node": ">=18"
},
"main": "./index.js",
"types": "./index.d.ts",
"repository": {
"type": "git",
"url": "git@github.com:langchain-ai/langchainjs.git"
},
"homepage": "https://github.com/langchain-ai/langchainjs/tree/main/libs/langchain-qdrant",
"scripts": {
"build": "yarn turbo:command build:internal --filter=@langchain/qdrant",
"build:internal": "yarn lc_build --create-entrypoints --pre --tree-shaking",
"lint:eslint": "NODE_OPTIONS=--max-old-space-size=4096 eslint --cache --ext .ts,.js src/",
"lint:dpdm": "dpdm --exit-code circular:1 --no-warning --no-tree src/*.ts src/**/*.ts",
"lint": "yarn lint:eslint && yarn lint:dpdm",
"lint:fix": "yarn lint:eslint --fix && yarn lint:dpdm",
"clean": "rm -rf .turbo dist/",
"prepack": "yarn build",
"test": "NODE_OPTIONS=--experimental-vm-modules jest --testPathIgnorePatterns=\\.int\\.test.ts --testTimeout 30000 --maxWorkers=50%",
"test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch --testPathIgnorePatterns=\\.int\\.test.ts",
"test:single": "NODE_OPTIONS=--experimental-vm-modules yarn run jest --config jest.config.cjs --testTimeout 100000",
"test:int": "NODE_OPTIONS=--experimental-vm-modules jest --testPathPattern=\\.int\\.test.ts --testTimeout 100000 --maxWorkers=50%",
"format": "prettier --config .prettierrc --write \"src\"",
"format:check": "prettier --config .prettierrc --check \"src\""
},
"author": "LangChain",
"license": "MIT",
"dependencies": {
"@qdrant/js-client-rest": "^1.9.0",
"uuid": "^10.0.0"
},
"peerDependencies": {
"@langchain/core": ">=0.2.21 <0.4.0"
},
"devDependencies": {
"@faker-js/faker": "^8.4.1",
"@jest/globals": "^29.5.0",
"@langchain/core": "workspace:*",
"@langchain/scripts": ">=0.1.0 <0.2.0",
"@swc/core": "^1.3.90",
"@swc/jest": "^0.2.29",
"@tsconfig/recommended": "^1.0.3",
"@types/uuid": "^9",
"@typescript-eslint/eslint-plugin": "^6.12.0",
"@typescript-eslint/parser": "^6.12.0",
"dotenv": "^16.3.1",
"dpdm": "^3.12.0",
"eslint": "^8.33.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-prettier": "^8.6.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-no-instanceof": "^1.0.1",
"eslint-plugin-prettier": "^4.2.1",
"jest": "^29.5.0",
"jest-environment-node": "^29.6.4",
"prettier": "^2.8.3",
"release-it": "^17.6.0",
"rollup": "^4.5.2",
"ts-jest": "^29.1.0",
"typescript": "<5.2.0"
},
"publishConfig": {
"access": "public"
},
"exports": {
".": {
"types": {
"import": "./index.d.ts",
"require": "./index.d.cts",
"default": "./index.d.ts"
},
"import": "./index.js",
"require": "./index.cjs"
},
"./package.json": "./package.json"
},
"files": [
"dist/",
"index.cjs",
"index.js",
"index.d.ts",
"index.d.cts"
]
}
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-qdrant/tsconfig.cjs.json
|
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs",
"declaration": false
},
"exclude": ["node_modules", "dist", "docs", "**/tests"]
}
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-qdrant/turbo.json
|
{
"extends": ["//"],
"pipeline": {
"build": {
"outputs": ["**/dist/**"]
},
"build:internal": {
"dependsOn": ["^build:internal"]
}
}
}
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-qdrant/.prettierrc
|
{
"$schema": "https://json.schemastore.org/prettierrc",
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": false,
"quoteProps": "as-needed",
"jsxSingleQuote": false,
"trailingComma": "es5",
"bracketSpacing": true,
"arrowParens": "always",
"requirePragma": false,
"insertPragma": false,
"proseWrap": "preserve",
"htmlWhitespaceSensitivity": "css",
"vueIndentScriptAndStyle": false,
"endOfLine": "lf"
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-qdrant
|
lc_public_repos/langchainjs/libs/langchain-qdrant/src/vectorstores.ts
|
import { QdrantClient } from "@qdrant/js-client-rest";
import type { Schemas as QdrantSchemas } from "@qdrant/js-client-rest";
import { v4 as uuid } from "uuid";
import type { EmbeddingsInterface } from "@langchain/core/embeddings";
import {
type MaxMarginalRelevanceSearchOptions,
VectorStore,
} from "@langchain/core/vectorstores";
import { Document } from "@langchain/core/documents";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { maximalMarginalRelevance } from "@langchain/core/utils/math";
const CONTENT_KEY = "content";
const METADATA_KEY = "metadata";
/**
* Interface for the arguments that can be passed to the
* `QdrantVectorStore` constructor. It includes options for specifying a
* `QdrantClient` instance, the URL and API key for a Qdrant database, and
* the name and configuration for a collection.
*/
export interface QdrantLibArgs {
client?: QdrantClient;
url?: string;
apiKey?: string;
collectionName?: string;
collectionConfig?: QdrantSchemas["CreateCollection"];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
customPayload?: Record<string, any>[];
contentPayloadKey?: string;
metadataPayloadKey?: string;
}
export type QdrantAddDocumentOptions = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
customPayload: Record<string, any>[];
};
/**
* Type that defines the parameters for the delete operation in the
* QdrantStore class. It includes ids, filter and shard key.
*/
export type QdrantDeleteParams =
| { ids: string[]; shardKey?: string; filter?: never }
| { filter: object; shardKey?: string; ids?: never };
export type QdrantFilter = QdrantSchemas["Filter"];
export type QdrantCondition = QdrantSchemas["FieldCondition"];
/**
* Type for the response returned by a search operation in the Qdrant
* database. It includes the score and payload (metadata and content) for
* each point (document) in the search results.
*/
type QdrantSearchResponse = QdrantSchemas["ScoredPoint"] & {
payload: {
metadata: object;
content: string;
};
};
/**
* Class that extends the `VectorStore` base class to interact with a
* Qdrant database. It includes methods for adding documents and vectors
* to the Qdrant database, searching for similar vectors, and ensuring the
* existence of a collection in the database.
*/
export class QdrantVectorStore extends VectorStore {
declare FilterType: QdrantFilter;
get lc_secrets(): { [key: string]: string } {
return {
apiKey: "QDRANT_API_KEY",
url: "QDRANT_URL",
};
}
client: QdrantClient;
collectionName: string;
collectionConfig?: QdrantSchemas["CreateCollection"];
contentPayloadKey: string;
metadataPayloadKey: string;
_vectorstoreType(): string {
return "qdrant";
}
constructor(embeddings: EmbeddingsInterface, args: QdrantLibArgs) {
super(embeddings, args);
const url = args.url ?? getEnvironmentVariable("QDRANT_URL");
const apiKey = args.apiKey ?? getEnvironmentVariable("QDRANT_API_KEY");
if (!args.client && !url) {
throw new Error("Qdrant client or url address must be set.");
}
this.client =
args.client ||
new QdrantClient({
url,
apiKey,
});
this.collectionName = args.collectionName ?? "documents";
this.collectionConfig = args.collectionConfig;
this.contentPayloadKey = args.contentPayloadKey ?? CONTENT_KEY;
this.metadataPayloadKey = args.metadataPayloadKey ?? METADATA_KEY;
}
/**
* Method to add documents to the Qdrant database. It generates vectors
* from the documents using the `Embeddings` instance and then adds the
* vectors to the database.
* @param documents Array of `Document` instances to be added to the Qdrant database.
* @param documentOptions Optional `QdrantAddDocumentOptions` which has a list of JSON objects for extra querying
* @returns Promise that resolves when the documents have been added to the database.
*/
async addDocuments(
documents: Document[],
documentOptions?: QdrantAddDocumentOptions
): Promise<void> {
const texts = documents.map(({ pageContent }) => pageContent);
await this.addVectors(
await this.embeddings.embedDocuments(texts),
documents,
documentOptions
);
}
/**
* Method to add vectors to the Qdrant database. Each vector is associated
* with a document, which is stored as the payload for a point in the
* database.
* @param vectors Array of vectors to be added to the Qdrant database.
* @param documents Array of `Document` instances associated with the vectors.
* @param documentOptions Optional `QdrantAddDocumentOptions` which has a list of JSON objects for extra querying
* @returns Promise that resolves when the vectors have been added to the database.
*/
async addVectors(
vectors: number[][],
documents: Document[],
documentOptions?: QdrantAddDocumentOptions
): Promise<void> {
if (vectors.length === 0) {
return;
}
await this.ensureCollection();
const points = vectors.map((embedding, idx) => ({
id: documents[idx].id ?? uuid(),
vector: embedding,
payload: {
[this.contentPayloadKey]: documents[idx].pageContent,
[this.metadataPayloadKey]: documents[idx].metadata,
customPayload: documentOptions?.customPayload[idx],
},
}));
try {
await this.client.upsert(this.collectionName, {
wait: true,
points,
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
const error = new Error(
`${e?.status ?? "Undefined error code"} ${e?.message}: ${
e?.data?.status?.error
}`
);
throw error;
}
}
/**
* Method that deletes points from the Qdrant database.
* @param params Parameters for the delete operation.
* @returns Promise that resolves when the delete operation is complete.
*/
async delete(params: QdrantDeleteParams): Promise<void> {
const { ids, filter, shardKey } = params;
if (ids) {
const batchSize = 1000;
for (let i = 0; i < ids.length; i += batchSize) {
const batchIds = ids.slice(i, i + batchSize);
await this.client.delete(this.collectionName, {
wait: true,
ordering: "weak",
points: batchIds,
shard_key: shardKey,
});
}
} else if (filter) {
await this.client.delete(this.collectionName, {
wait: true,
ordering: "weak",
filter,
shard_key: shardKey,
});
} else {
throw new Error("Either ids or filter must be provided.");
}
}
/**
* Method to search for vectors in the Qdrant database that are similar to
* a given query vector. The search results include the score and payload
* (metadata and content) for each similar vector.
* @param query Query vector to search for similar vectors in the Qdrant database.
* @param k Optional number of similar vectors to return. If not specified, all similar vectors are returned.
* @param filter Optional filter to apply to the search results.
* @returns Promise that resolves with an array of tuples, where each tuple includes a `Document` instance and a score for a similar vector.
*/
async similaritySearchVectorWithScore(
query: number[],
k?: number,
filter?: this["FilterType"]
): Promise<[Document, number][]> {
if (!query) {
return [];
}
await this.ensureCollection();
const results = await this.client.search(this.collectionName, {
vector: query,
limit: k,
filter,
with_payload: [this.metadataPayloadKey, this.contentPayloadKey],
with_vector: false,
});
const result: [Document, number][] = (
results as QdrantSearchResponse[]
).map((res) => [
new Document({
id: res.id as string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
metadata: res.payload[this.metadataPayloadKey] as Record<string, any>,
pageContent: res.payload[this.contentPayloadKey] as string,
}),
res.score,
]);
return result;
}
/**
* Return documents selected using the maximal marginal relevance.
* Maximal marginal relevance optimizes for similarity to the query AND diversity
* among selected documents.
*
* @param {string} query - Text to look up documents similar to.
* @param {number} options.k - Number of documents to return.
* @param {number} options.fetchK - Number of documents to fetch before passing to the MMR algorithm. Defaults to 20.
* @param {number} options.lambda - Number between 0 and 1 that determines the degree of diversity among the results,
* where 0 corresponds to maximum diversity and 1 to minimum diversity.
* @param {this["FilterType"]} options.filter - Optional filter to apply to the search results.
*
* @returns {Promise<Document[]>} - List of documents selected by maximal marginal relevance.
*/
async maxMarginalRelevanceSearch(
query: string,
options: MaxMarginalRelevanceSearchOptions<this["FilterType"]>
): Promise<Document[]> {
if (!query) {
return [];
}
const queryEmbedding = await this.embeddings.embedQuery(query);
await this.ensureCollection();
const results = await this.client.search(this.collectionName, {
vector: queryEmbedding,
limit: options?.fetchK ?? 20,
filter: options?.filter,
with_payload: [this.metadataPayloadKey, this.contentPayloadKey],
with_vector: true,
});
const embeddingList = results.map((res) => res.vector) as number[][];
const mmrIndexes = maximalMarginalRelevance(
queryEmbedding,
embeddingList,
options?.lambda,
options.k
);
const topMmrMatches = mmrIndexes.map((idx) => results[idx]);
const result = (topMmrMatches as QdrantSearchResponse[]).map(
(res) =>
new Document({
id: res.id as string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
metadata: res.payload[this.metadataPayloadKey] as Record<string, any>,
pageContent: res.payload[this.contentPayloadKey] as string,
})
);
return result;
}
/**
* Method to ensure the existence of a collection in the Qdrant database.
* If the collection does not exist, it is created.
* @returns Promise that resolves when the existence of the collection has been ensured.
*/
async ensureCollection() {
const response = await this.client.getCollections();
const collectionNames = response.collections.map(
(collection) => collection.name
);
if (!collectionNames.includes(this.collectionName)) {
const collectionConfig = this.collectionConfig ?? {
vectors: {
size: (await this.embeddings.embedQuery("test")).length,
distance: "Cosine",
},
};
await this.client.createCollection(this.collectionName, collectionConfig);
}
}
/**
* Static method to create a `QdrantVectorStore` instance from texts. Each
* text is associated with metadata and converted to a `Document`
* instance, which is then added to the Qdrant database.
* @param texts Array of texts to be converted to `Document` instances and added to the Qdrant database.
* @param metadatas Array or single object of metadata to be associated with the texts.
* @param embeddings `Embeddings` instance used to generate vectors from the texts.
* @param dbConfig `QdrantLibArgs` instance specifying the configuration for the Qdrant database.
* @returns Promise that resolves with a new `QdrantVectorStore` instance.
*/
static async fromTexts(
texts: string[],
metadatas: object[] | object,
embeddings: EmbeddingsInterface,
dbConfig: QdrantLibArgs
): Promise<QdrantVectorStore> {
const docs = [];
for (let i = 0; i < texts.length; i += 1) {
const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas;
const newDoc = new Document({
pageContent: texts[i],
metadata,
});
docs.push(newDoc);
}
return QdrantVectorStore.fromDocuments(docs, embeddings, dbConfig);
}
/**
* Static method to create a `QdrantVectorStore` instance from `Document`
* instances. The documents are added to the Qdrant database.
* @param docs Array of `Document` instances to be added to the Qdrant database.
* @param embeddings `Embeddings` instance used to generate vectors from the documents.
* @param dbConfig `QdrantLibArgs` instance specifying the configuration for the Qdrant database.
* @returns Promise that resolves with a new `QdrantVectorStore` instance.
*/
static async fromDocuments(
docs: Document[],
embeddings: EmbeddingsInterface,
dbConfig: QdrantLibArgs
): Promise<QdrantVectorStore> {
const instance = new this(embeddings, dbConfig);
if (dbConfig.customPayload) {
const documentOptions = {
customPayload: dbConfig?.customPayload,
};
await instance.addDocuments(docs, documentOptions);
} else {
await instance.addDocuments(docs);
}
return instance;
}
/**
* Static method to create a `QdrantVectorStore` instance from an existing
* collection in the Qdrant database.
* @param embeddings `Embeddings` instance used to generate vectors from the documents in the collection.
* @param dbConfig `QdrantLibArgs` instance specifying the configuration for the Qdrant database.
* @returns Promise that resolves with a new `QdrantVectorStore` instance.
*/
static async fromExistingCollection(
embeddings: EmbeddingsInterface,
dbConfig: QdrantLibArgs
): Promise<QdrantVectorStore> {
const instance = new this(embeddings, dbConfig);
await instance.ensureCollection();
return instance;
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-qdrant
|
lc_public_repos/langchainjs/libs/langchain-qdrant/src/index.ts
|
export * from "./vectorstores.js";
|
0
|
lc_public_repos/langchainjs/libs/langchain-qdrant/src
|
lc_public_repos/langchainjs/libs/langchain-qdrant/src/tests/vectorstores.test.ts
|
/* eslint-disable @typescript-eslint/no-explicit-any */
import { jest, test, expect } from "@jest/globals";
import { FakeEmbeddings } from "@langchain/core/utils/testing";
import { QdrantVectorStore } from "../vectorstores.js";
test("QdrantVectorStore works", async () => {
const client = {
upsert: jest.fn(),
search: jest.fn<any>().mockResolvedValue([]),
getCollections: jest.fn<any>().mockResolvedValue({ collections: [] }),
createCollection: jest.fn(),
};
const embeddings = new FakeEmbeddings();
const store = new QdrantVectorStore(embeddings, {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
client: client as any,
});
expect(store).toBeDefined();
await store.addDocuments([
{
pageContent: "hello",
metadata: {},
},
]);
expect(client.upsert).toHaveBeenCalledTimes(1);
const results = await store.similaritySearch("hello", 1);
expect(results).toHaveLength(0);
});
test("QdrantVectorStore adds vectors with custom payload", async () => {
// Mock Qdrant client
const client = {
upsert: jest.fn(),
search: jest.fn<any>().mockResolvedValue([]),
getCollections: jest.fn<any>().mockResolvedValue({ collections: [] }),
createCollection: jest.fn(),
};
// Mock embeddings
const embeddings = new FakeEmbeddings();
// Create QdrantVectorStore instance with the mock client
const qdrantVectorStore = new QdrantVectorStore(embeddings, {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
client: client as any,
});
// Define a custom payload
const customPayload = {
customPayload: [
{
customField1: "value1",
customField2: "value2",
},
],
};
// Add documents with custom payload
await qdrantVectorStore.addDocuments(
[
{
pageContent: "hello",
metadata: {},
},
],
customPayload
);
// Verify that the Qdrant client's upsert method was called with the correct arguments
expect(client.upsert).toHaveBeenCalledTimes(1);
expect(client.upsert).toHaveBeenCalledWith("documents", {
wait: true,
points: [
expect.objectContaining({
payload: expect.objectContaining({
content: "hello",
metadata: {},
customPayload: customPayload.customPayload[0],
}),
}),
],
});
});
test("QdrantVectorStore adds vectors with multiple custom payload", async () => {
// Mock Qdrant client
const client = {
upsert: jest.fn(),
search: jest.fn<any>().mockResolvedValue([]),
getCollections: jest.fn<any>().mockResolvedValue({ collections: [] }),
createCollection: jest.fn(),
};
// Mock embeddings
const embeddings = new FakeEmbeddings();
// Create QdrantVectorStore instance with the mock client
const qdrantVectorStore = new QdrantVectorStore(embeddings, {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
client: client as any,
});
// Define a custom payload
const customPayload = {
customPayload: [
{
customField1: "value1",
customField2: "value2",
},
{
customField3: "value3",
},
],
};
// Add documents with custom payload
await qdrantVectorStore.addDocuments(
[
{
pageContent: "hello",
metadata: {},
},
{
pageContent: "Goodbye",
metadata: {},
},
{
pageContent: "D01",
metadata: {},
},
],
customPayload
);
// Verify that the Qdrant client's upsert method was called with the correct arguments
expect(client.upsert).toHaveBeenCalledTimes(1);
expect(client.upsert).toHaveBeenCalledWith("documents", {
wait: true,
points: [
expect.objectContaining({
payload: expect.objectContaining({
content: "hello",
metadata: {},
customPayload: customPayload.customPayload[0],
}),
}),
expect.objectContaining({
payload: expect.objectContaining({
content: "Goodbye",
metadata: {},
customPayload: customPayload.customPayload[1],
}),
}),
expect.objectContaining({
payload: expect.objectContaining({
content: "D01",
metadata: {},
}),
}),
],
});
});
test("QdrantVectorStore adds vectors with no custom payload", async () => {
// Mock Qdrant client
const client = {
upsert: jest.fn(),
search: jest.fn<any>().mockResolvedValue([]),
getCollections: jest.fn<any>().mockResolvedValue({ collections: [] }),
createCollection: jest.fn(),
};
// Mock embeddings
const embeddings = new FakeEmbeddings();
// Create QdrantVectorStore instance with the mock client
const qdrantVectorStore = new QdrantVectorStore(embeddings, {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
client: client as any,
});
// Add documents with custom payload
await qdrantVectorStore.addDocuments([
{
pageContent: "hello",
metadata: {},
},
]);
// Verify that the Qdrant client's upsert method was called with the correct arguments
expect(client.upsert).toHaveBeenCalledTimes(1);
expect(client.upsert).toHaveBeenCalledWith("documents", {
wait: true,
points: [
expect.objectContaining({
payload: expect.objectContaining({
content: "hello",
metadata: {},
}),
}),
],
});
});
test("QdrantVectorStore MMR works", async () => {
const client = {
upsert: jest.fn(),
search: jest.fn<any>().mockResolvedValue([]),
getCollections: jest.fn<any>().mockResolvedValue({ collections: [] }),
createCollection: jest.fn(),
};
const embeddings = new FakeEmbeddings();
const store = new QdrantVectorStore(embeddings, {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
client: client as any,
});
expect(store).toBeDefined();
await store.addDocuments([
{
pageContent: "hello",
metadata: {},
},
]);
expect(client.upsert).toHaveBeenCalledTimes(1);
expect(store.maxMarginalRelevanceSearch).toBeDefined();
await store.maxMarginalRelevanceSearch("hello", {
k: 10,
fetchK: 7,
});
expect(client.search).toHaveBeenCalledTimes(1);
expect(client.search).toHaveBeenCalledWith("documents", {
filter: undefined,
limit: 7,
vector: [0.1, 0.2, 0.3, 0.4],
with_payload: ["metadata", "content"],
with_vector: true,
});
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-qdrant/src
|
lc_public_repos/langchainjs/libs/langchain-qdrant/src/tests/vectorstores.int.test.ts
|
/* eslint-disable no-process-env */
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { describe, expect, test } from "@jest/globals";
import { QdrantClient } from "@qdrant/js-client-rest";
import { faker } from "@faker-js/faker";
import { Document } from "@langchain/core/documents";
import { SyntheticEmbeddings } from "@langchain/core/utils/testing";
import { v4 } from "uuid";
import { QdrantVectorStore } from "../vectorstores.js";
describe("QdrantVectorStore testcase", () => {
test("base usage", async () => {
const embeddings = new SyntheticEmbeddings({
vectorSize: 1536,
});
const qdrantVectorStore = new QdrantVectorStore(embeddings, {
url: process.env.QDRANT_URL || "http://localhost:6333",
collectionName: process.env.QDRANT_COLLECTION || "documents",
});
const pageContent = faker.lorem.sentence(5);
const id = v4();
await qdrantVectorStore.addDocuments([{ pageContent, metadata: {}, id }]);
const results = await qdrantVectorStore.similaritySearch(pageContent, 1);
expect(results[0]).toEqual(new Document({ metadata: {}, pageContent, id }));
expect(qdrantVectorStore.maxMarginalRelevanceSearch).toBeDefined();
const mmrResults = await qdrantVectorStore.maxMarginalRelevanceSearch(
pageContent,
{
k: 1,
}
);
expect(mmrResults.length).toBe(1);
expect(mmrResults[0]).toEqual(
new Document({ metadata: {}, pageContent, id })
);
});
test("passing client directly with a model that creates embeddings with a different number of dimensions", async () => {
const embeddings = new SyntheticEmbeddings({
vectorSize: 384,
});
const pageContent = faker.lorem.sentence(5);
const qdrantVectorStore = await QdrantVectorStore.fromDocuments(
[{ pageContent, metadata: {} }],
embeddings,
{
collectionName: "different_dimensions",
client: new QdrantClient({
url: process.env.QDRANT_URL,
apiKey: process.env.QDRANT_API_KEY,
}),
}
);
const results = await qdrantVectorStore.similaritySearch(pageContent, 1);
expect(results[0].metadata).toEqual({});
expect(results[0].pageContent).toEqual(pageContent);
});
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-qdrant
|
lc_public_repos/langchainjs/libs/langchain-qdrant/scripts/jest-setup-after-env.js
|
import { awaitAllCallbacks } from "@langchain/core/callbacks/promises";
import { afterAll, jest } from "@jest/globals";
afterAll(awaitAllCallbacks);
// Allow console.log to be disabled in tests
if (process.env.DISABLE_CONSOLE_LOGS === "true") {
console.log = jest.fn();
}
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-redis/tsconfig.json
|
{
"extends": "@tsconfig/recommended",
"compilerOptions": {
"outDir": "../dist",
"rootDir": "./src",
"target": "ES2021",
"lib": ["ES2021", "ES2022.Object", "DOM"],
"module": "ES2020",
"moduleResolution": "nodenext",
"esModuleInterop": true,
"declaration": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"useDefineForClassFields": true,
"strictPropertyInitialization": false,
"allowJs": true,
"strict": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "docs"]
}
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-redis/LICENSE
|
The MIT License
Copyright (c) 2023 LangChain
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-redis/jest.config.cjs
|
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: "ts-jest/presets/default-esm",
testEnvironment: "./jest.env.cjs",
modulePathIgnorePatterns: ["dist/", "docs/"],
moduleNameMapper: {
"^(\\.{1,2}/.*)\\.js$": "$1",
},
transform: {
"^.+\\.tsx?$": ["@swc/jest"],
},
transformIgnorePatterns: [
"/node_modules/",
"\\.pnp\\.[^\\/]+$",
"./scripts/jest-setup-after-env.js",
],
setupFiles: ["dotenv/config"],
testTimeout: 20_000,
passWithNoTests: true,
collectCoverageFrom: ["src/**/*.ts"],
};
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-redis/jest.env.cjs
|
const { TestEnvironment } = require("jest-environment-node");
class AdjustedTestEnvironmentToSupportFloat32Array extends TestEnvironment {
constructor(config, context) {
// Make `instanceof Float32Array` return true in tests
// to avoid https://github.com/xenova/transformers.js/issues/57 and https://github.com/jestjs/jest/issues/2549
super(config, context);
this.global.Float32Array = Float32Array;
}
}
module.exports = AdjustedTestEnvironmentToSupportFloat32Array;
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-redis/README.md
|
# @langchain/redis
This package contains the LangChain.js integrations for Redis through their SDK.
## Installation
```bash npm2yarn
npm install @langchain/redis @langchain/core
```
## Development
To develop the Redis package, you'll need to follow these instructions:
### Install dependencies
```bash
yarn install
```
### Build the package
```bash
yarn build
```
Or from the repo root:
```bash
yarn build --filter=@langchain/redis
```
### Run tests
Test files should live within a `tests/` file in the `src/` folder. Unit tests should end in `.test.ts` and integration tests should
end in `.int.test.ts`:
```bash
$ yarn test
$ yarn test:int
```
### Lint & Format
Run the linter & formatter to ensure your code is up to standard:
```bash
yarn lint && yarn format
```
### Adding new entrypoints
If you add a new file to be exported, either import & re-export from `src/index.ts`, or add it to the `entrypoints` field in the `config` variable located inside `langchain.config.js` and run `yarn build` to generate the new entrypoint.
|
0
|
lc_public_repos/langchainjs/libs
|
lc_public_repos/langchainjs/libs/langchain-redis/.release-it.json
|
{
"github": {
"release": true,
"autoGenerate": true,
"tokenRef": "GITHUB_TOKEN_RELEASE"
},
"npm": {
"versionArgs": ["--workspaces-update=false"]
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.