@langchain/langgraph-cli 0.0.0-preview.5 → 0.0.0-preview.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,6 +8,7 @@ import { $ } from "execa";
8
8
  import * as path from "node:path";
9
9
  import * as fs from "node:fs/promises";
10
10
  import { logger } from "../logging.mjs";
11
+ import { withAnalytics } from "./utils/analytics.mjs";
11
12
  const stream = (proc) => {
12
13
  logger.info(`Running "${proc.spawnargs.join(" ")}"`);
13
14
  return proc;
@@ -20,6 +21,10 @@ builder
20
21
  .option("--no-pull", "Running the server with locally-built images. By default LangGraph will pull the latest images from the registry")
21
22
  .argument("[args...]")
22
23
  .passThroughOptions()
24
+ .hook("preAction", withAnalytics((command) => ({
25
+ config: command.opts().config !== process.cwd(),
26
+ pull: command.opts().pull,
27
+ })))
23
28
  .action(async (pass, params) => {
24
29
  const configPath = await getProjectPath(params.config);
25
30
  await getDockerCapabilities();
package/dist/cli/cli.mjs CHANGED
@@ -1,7 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import { builder } from "./utils/builder.mjs";
3
+ import { flushAnalytics } from "./utils/analytics.mjs";
4
+ import { asyncExitHook, gracefulExit } from "exit-hook";
3
5
  import "./dev.mjs";
4
6
  import "./docker.mjs";
5
7
  import "./build.mjs";
6
8
  import "./up.mjs";
9
+ builder.exitOverride((error) => gracefulExit(error.exitCode));
10
+ asyncExitHook(() => flushAnalytics(), { wait: 2000 });
7
11
  builder.parse();
package/dist/cli/dev.mjs CHANGED
@@ -1,18 +1,15 @@
1
1
  import * as path from "node:path";
2
2
  import * as fs from "node:fs/promises";
3
- import { fileURLToPath } from "node:url";
4
- import { spawn } from "node:child_process";
3
+ import { parse, populate } from "dotenv";
4
+ import { watch } from "chokidar";
5
+ import { z } from "zod";
5
6
  import open from "open";
6
- import * as dotenv from "dotenv";
7
- import { logger } from "../logging.mjs";
8
- import { getConfig } from "../utils/config.mjs";
9
7
  import { createIpcServer } from "./utils/ipc/server.mjs";
10
- import { z } from "zod";
11
- import { watch } from "chokidar";
12
- import { builder } from "./utils/builder.mjs";
13
8
  import { getProjectPath } from "./utils/project.mjs";
14
- const tsxTarget = new URL("../../cli.mjs", import.meta.resolve("tsx/esm/api"));
15
- const entrypointTarget = new URL(import.meta.resolve("./dev.entrypoint.mjs"));
9
+ import { getConfig } from "../utils/config.mjs";
10
+ import { builder } from "./utils/builder.mjs";
11
+ import { logger } from "../logging.mjs";
12
+ import { withAnalytics } from "./utils/analytics.mjs";
16
13
  builder
17
14
  .command("dev")
18
15
  .description("Run LangGraph API server in development mode with hot reloading.")
@@ -21,7 +18,15 @@ builder
21
18
  .option("--no-browser", "disable auto-opening the browser")
22
19
  .option("-n, --n-jobs-per-worker <number>", "number of workers to run", "10")
23
20
  .option("-c, --config <path>", "path to configuration file", process.cwd())
24
- .action(async (options) => {
21
+ .allowExcessArguments()
22
+ .allowUnknownOption()
23
+ .hook("preAction", withAnalytics((command) => ({
24
+ config: command.opts().config !== process.cwd(),
25
+ port: command.opts().port !== "2024",
26
+ host: command.opts().host !== "localhost",
27
+ n_jobs_per_worker: command.opts().nJobsPerWorker !== "10",
28
+ })))
29
+ .action(async (options, { args }) => {
25
30
  try {
26
31
  const configPath = await getProjectPath(options.config);
27
32
  const projectCwd = path.dirname(configPath);
@@ -32,32 +37,11 @@ builder
32
37
  });
33
38
  let hasOpenedFlag = false;
34
39
  let child = undefined;
35
- const localUrl = `http://${options.host}:${options.port}`;
36
- const studioUrl = `https://smith.langchain.com/studio?baseUrl=${localUrl}`;
37
- console.log(`
38
- Welcome to
39
-
40
- ╦ ┌─┐┌┐┌┌─┐╔═╗┬─┐┌─┐┌─┐┬ ┬
41
- ║ ├─┤││││ ┬║ ╦├┬┘├─┤├─┘├─┤
42
- ╩═╝┴ ┴┘└┘└─┘╚═╝┴└─┴ ┴┴ ┴ ┴.js
43
-
44
- - 🚀 API: \x1b[36m${localUrl}\x1b[0m
45
- - 🎨 Studio UI: \x1b[36m${studioUrl}\x1b[0m
46
-
47
- This in-memory server is designed for development and testing.
48
- For production use, please use LangGraph Cloud.
49
-
50
- `);
51
40
  server.on("data", (data) => {
52
- const { host, organizationId } = z
53
- .object({ host: z.string(), organizationId: z.string().nullish() })
54
- .parse(data);
55
- logger.info(`Server running at ${host}`);
41
+ const response = z.object({ queryParams: z.string() }).parse(data);
56
42
  if (options.browser && !hasOpenedFlag) {
57
43
  hasOpenedFlag = true;
58
- open(organizationId
59
- ? `${studioUrl}&organizationId=${organizationId}`
60
- : studioUrl);
44
+ open(`https://smith.langchain.com/studio${response.queryParams}`);
61
45
  }
62
46
  });
63
47
  // check if .gitignore already contains .langgraph-api
@@ -79,7 +63,7 @@ For production use, please use LangGraph Cloud.
79
63
  const envPath = path.resolve(projectCwd, configEnv);
80
64
  newWatch.push(envPath);
81
65
  const envData = await fs.readFile(envPath, "utf-8");
82
- dotenv.populate(env, dotenv.parse(envData));
66
+ populate(env, parse(envData));
83
67
  }
84
68
  else if (Array.isArray(configEnv)) {
85
69
  throw new Error("Env storage is not supported by CLI.");
@@ -87,7 +71,7 @@ For production use, please use LangGraph Cloud.
87
71
  else if (typeof configEnv === "object") {
88
72
  if (!process.env)
89
73
  throw new Error("process.env is not defined");
90
- dotenv.populate(env, configEnv);
74
+ populate(env, configEnv);
91
75
  }
92
76
  }
93
77
  const oldWatch = Object.entries(watcher.getWatched()).flatMap(([dir, files]) => files.map((file) => path.resolve(projectCwd, dir, file)));
@@ -96,31 +80,27 @@ For production use, please use LangGraph Cloud.
96
80
  watcher.unwatch(removedTarget).add(addedTarget);
97
81
  return { config, env };
98
82
  };
99
- const launchTsx = async () => {
83
+ const launchServer = async () => {
100
84
  const { config, env } = await prepareContext();
101
85
  if (child != null)
102
86
  child.kill();
103
- child = spawn(process.execPath, [
104
- fileURLToPath(tsxTarget),
105
- "watch",
106
- "--clear-screen=false",
107
- fileURLToPath(entrypointTarget),
108
- pid.toString(),
109
- JSON.stringify({
110
- port: Number.parseInt(options.port, 10),
111
- nWorkers: Number.parseInt(options.nJobsPerWorker, 10),
112
- host: options.host,
113
- graphs: config.graphs,
114
- cwd: projectCwd,
115
- }),
116
- ], { stdio: ["inherit", "inherit", "inherit", "ipc"], env });
87
+ if ("python_version" in config) {
88
+ logger.warn("Launching Python server from @langchain/langgraph-cli is experimental. Please use the `langgraph-cli` package from PyPi instead.");
89
+ const { spawnPythonServer } = await import("./dev.python.mjs");
90
+ child = await spawnPythonServer({ ...options, rest: args }, { configPath, config, env }, { pid, projectCwd });
91
+ }
92
+ else {
93
+ const { spawnNodeServer } = await import("./dev.node.mjs");
94
+ child = await spawnNodeServer({ ...options, rest: args }, { configPath, config, env }, { pid, projectCwd });
95
+ }
117
96
  };
118
97
  watcher.on("all", async (_name, path) => {
119
98
  logger.warn(`Detected changes in ${path}, restarting server`);
120
- launchTsx();
99
+ launchServer();
121
100
  });
122
- // TODO: handle errors
123
- launchTsx();
101
+ // TODO: sometimes the server keeps sending stuff
102
+ // while gracefully exiting
103
+ launchServer();
124
104
  process.on("exit", () => {
125
105
  watcher.close();
126
106
  server.close();
@@ -16,8 +16,9 @@ const isTracingEnabled = () => {
16
16
  process.env?.LANGCHAIN_TRACING;
17
17
  return value === "true";
18
18
  };
19
+ const options = StartServerSchema.parse(JSON.parse(payload));
19
20
  const [{ host, cleanup }, organizationId] = await Promise.all([
20
- startServer(StartServerSchema.parse(JSON.parse(payload))),
21
+ startServer(options),
21
22
  (async () => {
22
23
  if (isTracingEnabled()) {
23
24
  try {
@@ -31,5 +32,9 @@ const [{ host, cleanup }, organizationId] = await Promise.all([
31
32
  return null;
32
33
  })(),
33
34
  ]);
35
+ logger.info(`Server running at ${host}`);
36
+ let queryParams = `?baseUrl=http://${options.host}:${options.port}`;
37
+ if (organizationId)
38
+ queryParams += `&organizationId=${organizationId}`;
34
39
  asyncExitHook(cleanup, { wait: 1000 });
35
- sendToParent?.({ host, organizationId });
40
+ sendToParent?.({ queryParams });
@@ -0,0 +1,35 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { spawn } from "node:child_process";
3
+ import {} from "../utils/config.mjs";
4
+ export async function spawnNodeServer(args, context, options) {
5
+ const localUrl = `http://${args.host}:${args.port}`;
6
+ const studioUrl = `https://smith.langchain.com/studio?baseUrl=${localUrl}`;
7
+ console.log(`
8
+ Welcome to
9
+
10
+ ╦ ┌─┐┌┐┌┌─┐╔═╗┬─┐┌─┐┌─┐┬ ┬
11
+ ║ ├─┤││││ ┬║ ╦├┬┘├─┤├─┘├─┤
12
+ ╩═╝┴ ┴┘└┘└─┘╚═╝┴└─┴ ┴┴ ┴ ┴.js
13
+
14
+ - 🚀 API: \x1b[36m${localUrl}\x1b[0m
15
+ - 🎨 Studio UI: \x1b[36m${studioUrl}\x1b[0m
16
+
17
+ This in-memory server is designed for development and testing.
18
+ For production use, please use LangGraph Cloud.
19
+
20
+ `);
21
+ return spawn(process.execPath, [
22
+ fileURLToPath(new URL("../../cli.mjs", import.meta.resolve("tsx/esm/api"))),
23
+ "watch",
24
+ "--clear-screen=false",
25
+ fileURLToPath(new URL(import.meta.resolve("./dev.node.entrypoint.mjs"))),
26
+ options.pid.toString(),
27
+ JSON.stringify({
28
+ port: Number.parseInt(args.port, 10),
29
+ nWorkers: Number.parseInt(args.nJobsPerWorker, 10),
30
+ host: args.host,
31
+ graphs: context.config.graphs,
32
+ cwd: options.projectCwd,
33
+ }),
34
+ ], { stdio: ["inherit", "inherit", "inherit", "ipc"], env: context.env });
35
+ }
@@ -0,0 +1,128 @@
1
+ import { spawn } from "node:child_process";
2
+ import { fileURLToPath } from "node:url";
3
+ import { Readable } from "node:stream";
4
+ import fs from "node:fs/promises";
5
+ import path from "node:path";
6
+ import os from "node:os";
7
+ import { extract as tarExtract } from "tar";
8
+ import zipExtract from "extract-zip";
9
+ import { logger } from "../logging.mjs";
10
+ import { assembleLocalDeps } from "../docker/docker.mjs";
11
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
12
+ const UV_VERSION = "0.5.20";
13
+ const UV_BINARY_CACHE = path.join(__dirname, ".uv", UV_VERSION);
14
+ function getPlatformInfo() {
15
+ const platform = os.platform();
16
+ const arch = os.arch();
17
+ let binaryName = "uv";
18
+ let extension = "";
19
+ if (platform === "win32") {
20
+ extension = ".exe";
21
+ }
22
+ return {
23
+ platform,
24
+ arch,
25
+ extension,
26
+ binaryName: binaryName + extension,
27
+ };
28
+ }
29
+ function getDownloadUrl(info) {
30
+ let platformStr;
31
+ switch (info.platform) {
32
+ case "darwin":
33
+ platformStr = "apple-darwin";
34
+ break;
35
+ case "win32":
36
+ platformStr = "pc-windows-msvc";
37
+ break;
38
+ case "linux":
39
+ platformStr = "unknown-linux-gnu";
40
+ break;
41
+ default:
42
+ throw new Error(`Unsupported platform: ${info.platform}`);
43
+ }
44
+ let archStr;
45
+ switch (info.arch) {
46
+ case "x64":
47
+ archStr = "x86_64";
48
+ break;
49
+ case "arm64":
50
+ archStr = "aarch64";
51
+ break;
52
+ default:
53
+ throw new Error(`Unsupported architecture: ${info.arch}`);
54
+ }
55
+ const fileName = `uv-${archStr}-${platformStr}${info.platform === "win32" ? ".zip" : ".tar.gz"}`;
56
+ return `https://github.com/astral-sh/uv/releases/download/${UV_VERSION}/${fileName}`;
57
+ }
58
+ async function downloadAndExtract(url, destPath, info) {
59
+ const response = await fetch(url);
60
+ if (!response.ok)
61
+ throw new Error(`Failed to download uv: ${response.statusText}`);
62
+ if (!response.body)
63
+ throw new Error("No response body");
64
+ const tempDirPath = await fs.mkdtemp(path.join(os.tmpdir(), "uv-"));
65
+ const tempFilePath = path.join(tempDirPath, path.basename(url));
66
+ try {
67
+ // @ts-expect-error invalid types for response.body
68
+ await fs.writeFile(tempFilePath, Readable.fromWeb(response.body));
69
+ let sourceBinaryPath = tempDirPath;
70
+ if (url.endsWith(".zip")) {
71
+ await zipExtract(tempFilePath, { dir: tempDirPath });
72
+ }
73
+ else {
74
+ await tarExtract({ file: tempFilePath, cwd: tempDirPath });
75
+ sourceBinaryPath = path.resolve(sourceBinaryPath, path.basename(tempFilePath).slice(0, ".tar.gz".length * -1));
76
+ }
77
+ sourceBinaryPath = path.resolve(sourceBinaryPath, info.binaryName);
78
+ // Move binary to cache directory
79
+ const targetBinaryPath = path.join(destPath, info.binaryName);
80
+ await fs.rename(sourceBinaryPath, targetBinaryPath);
81
+ await fs.chmod(targetBinaryPath, 0o755);
82
+ return targetBinaryPath;
83
+ }
84
+ finally {
85
+ await fs.rm(tempDirPath, { recursive: true, force: true });
86
+ }
87
+ }
88
+ export async function getUvBinary() {
89
+ await fs.mkdir(UV_BINARY_CACHE, { recursive: true });
90
+ const info = getPlatformInfo();
91
+ const cachedBinaryPath = path.join(UV_BINARY_CACHE, info.binaryName);
92
+ try {
93
+ await fs.access(cachedBinaryPath);
94
+ return cachedBinaryPath;
95
+ }
96
+ catch {
97
+ // Binary not found in cache, download it
98
+ logger.info(`Downloading uv ${UV_VERSION} for ${info.platform}...`);
99
+ const url = getDownloadUrl(info);
100
+ return await downloadAndExtract(url, UV_BINARY_CACHE, info);
101
+ }
102
+ }
103
+ export async function spawnPythonServer(args, context, options) {
104
+ const deps = await assembleLocalDeps(context.configPath, context.config);
105
+ const requirements = deps.rebuildFiles.filter((i) => i.endsWith(".txt"));
106
+ return spawn(await getUvBinary(), [
107
+ "run",
108
+ "--with",
109
+ "langgraph-cli[inmem]",
110
+ ...requirements?.flatMap((i) => ["--with-requirements", i]),
111
+ "langgraph",
112
+ "dev",
113
+ "--port",
114
+ args.port,
115
+ "--host",
116
+ args.host,
117
+ "--n-jobs-per-worker",
118
+ args.nJobsPerWorker,
119
+ "--config",
120
+ context.configPath,
121
+ ...(args.browser ? [] : ["--no-browser"]),
122
+ ...args.rest,
123
+ ], {
124
+ stdio: ["inherit", "inherit", "inherit"],
125
+ env: context.env,
126
+ cwd: options.projectCwd,
127
+ });
128
+ }
@@ -7,6 +7,7 @@ import * as fs from "node:fs/promises";
7
7
  import * as path from "node:path";
8
8
  import dedent from "dedent";
9
9
  import { logger } from "../logging.mjs";
10
+ import { withAnalytics } from "./utils/analytics.mjs";
10
11
  const fileExists = async (path) => {
11
12
  try {
12
13
  await fs.access(path);
@@ -22,6 +23,10 @@ builder
22
23
  .argument("<save-path>", "Path to save the Dockerfile")
23
24
  .option("--add-docker-compose", "Add additional files for running the LangGraph API server with docker-compose. These files include a docker-compose.yml, .env file, and a .dockerignore file.")
24
25
  .option("-c, --config <path>", "Path to configuration file", process.cwd())
26
+ .hook("preAction", withAnalytics((command) => ({
27
+ config: command.opts().config !== process.cwd(),
28
+ add_docker_compose: !!command.opts().addDockerCompose,
29
+ })))
25
30
  .action(async (savePath, options) => {
26
31
  const configPath = await getProjectPath(options.config);
27
32
  const config = getConfig(await fs.readFile(configPath, "utf-8"));
package/dist/cli/up.mjs CHANGED
@@ -10,6 +10,7 @@ import { getExecaOptions } from "../docker/shell.mjs";
10
10
  import { $ } from "execa";
11
11
  import { createHash } from "node:crypto";
12
12
  import dedent from "dedent";
13
+ import { withAnalytics } from "./utils/analytics.mjs";
13
14
  const sha256 = (input) => createHash("sha256").update(input).digest("hex");
14
15
  const getProjectName = (configPath) => {
15
16
  const cwd = path.dirname(configPath).toLocaleLowerCase();
@@ -34,12 +35,22 @@ builder
34
35
  .description("Launch LangGraph API server.")
35
36
  .option("-c, --config <path>", "Path to configuration file", process.cwd())
36
37
  .option("-d, --docker-compose <path>", "Advanced: Path to docker-compose.yml file with additional services to launch")
37
- .option("-p, --port <port>", "Port to run the server on", "8000")
38
+ .option("-p, --port <port>", "Port to run the server on", "8123")
38
39
  .option("--recreate", "Force recreate containers and volumes", false)
39
40
  .option("--no-pull", "Running the server with locally-built images. By default LangGraph will pull the latest images from the registry")
40
41
  .option("--watch", "Restart on file changes", false)
41
42
  .option("--wait", "Wait for services to start before returning. Implies --detach", false)
42
43
  .option("--postgres-uri <uri>", "Postgres URI to use for the database. Defaults to launching a local database")
44
+ .hook("preAction", withAnalytics((command) => ({
45
+ config: command.opts().config !== process.cwd(),
46
+ port: command.opts().port !== "8123",
47
+ postgres_uri: !!command.opts().postgresUri,
48
+ docker_compose: !!command.opts().dockerCompose,
49
+ recreate: command.opts().recreate,
50
+ pull: command.opts().pull,
51
+ watch: command.opts().watch,
52
+ wait: command.opts().wait,
53
+ })))
43
54
  .action(async (params) => {
44
55
  logger.info("Starting LangGraph API server...");
45
56
  logger.warn(dedent `
@@ -0,0 +1,39 @@
1
+ import os from "node:os";
2
+ import { version } from "./version.mjs";
3
+ const SUPABASE_PUBLIC_API_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imt6cmxwcG9qaW5wY3l5YWlweG5iIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTkyNTc1NzksImV4cCI6MjAzNDgzMzU3OX0.kkVOlLz3BxemA5nP-vat3K4qRtrDuO4SwZSR_htcX9c";
4
+ const SUPABASE_URL = "https://kzrlppojinpcyyaipxnb.supabase.co";
5
+ async function logData(data) {
6
+ try {
7
+ await fetch(`${SUPABASE_URL}/rest/v1/js_logs`, {
8
+ method: "POST",
9
+ headers: {
10
+ "Content-Type": "application/json",
11
+ apikey: SUPABASE_PUBLIC_API_KEY,
12
+ "User-Agent": "Mozilla/5.0",
13
+ },
14
+ body: JSON.stringify(data),
15
+ });
16
+ }
17
+ catch (error) {
18
+ // pass
19
+ }
20
+ }
21
+ let analyticsPromise = Promise.resolve();
22
+ export function withAnalytics(fn) {
23
+ if (process.env.LANGGRAPH_CLI_NO_ANALYTICS === "1") {
24
+ return () => void 0;
25
+ }
26
+ return function (actionCommand) {
27
+ analyticsPromise = analyticsPromise.then(() => logData({
28
+ os: os.platform(),
29
+ os_version: os.release(),
30
+ node_version: process.version,
31
+ cli_version: version,
32
+ cli_command: actionCommand.name(),
33
+ params: fn?.(actionCommand) ?? {},
34
+ }).catch(() => { }));
35
+ };
36
+ }
37
+ export async function flushAnalytics() {
38
+ await analyticsPromise;
39
+ }
@@ -1,16 +1,7 @@
1
1
  import { Command } from "@commander-js/extra-typings";
2
- import * as fs from "node:fs/promises";
3
- import * as url from "node:url";
2
+ import { version } from "./version.mjs";
4
3
  export const builder = new Command()
5
4
  .name("langgraph")
6
5
  .description("LangGraph.js CLI")
6
+ .version(version)
7
7
  .enablePositionalOptions();
8
- try {
9
- const packageJson = url.fileURLToPath(new URL("../../../package.json", import.meta.url));
10
- const { version } = JSON.parse(await fs.readFile(packageJson, "utf-8"));
11
- builder.version(version);
12
- }
13
- catch (error) {
14
- console.error(error);
15
- // pass
16
- }
@@ -0,0 +1,13 @@
1
+ import * as fs from "node:fs/promises";
2
+ import * as url from "node:url";
3
+ async function getVersion() {
4
+ try {
5
+ const packageJson = url.fileURLToPath(new URL("../../../package.json", import.meta.url));
6
+ const { version } = JSON.parse(await fs.readFile(packageJson, "utf-8"));
7
+ return version + "+js";
8
+ }
9
+ catch {
10
+ return "0.0.0-unknown";
11
+ }
12
+ }
13
+ export const version = await getVersion();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@langchain/langgraph-cli",
3
- "version": "0.0.0-preview.5",
3
+ "version": "0.0.0-preview.7",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=18"
@@ -35,10 +35,12 @@
35
35
  "dotenv": "^16.4.7",
36
36
  "execa": "^9.5.2",
37
37
  "exit-hook": "^4.0.0",
38
+ "extract-zip": "^2.0.1",
38
39
  "hono": "^4.5.4",
39
40
  "langsmith": "^0.2.15",
40
41
  "open": "^10.1.0",
41
42
  "superjson": "^2.2.2",
43
+ "tar": "^7.4.3",
42
44
  "tsx": "^4.19.2",
43
45
  "uuid": "^10.0.0",
44
46
  "winston": "^3.17.0",