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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/dev.mjs CHANGED
@@ -1,18 +1,14 @@
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";
16
12
  builder
17
13
  .command("dev")
18
14
  .description("Run LangGraph API server in development mode with hot reloading.")
@@ -21,7 +17,9 @@ builder
21
17
  .option("--no-browser", "disable auto-opening the browser")
22
18
  .option("-n, --n-jobs-per-worker <number>", "number of workers to run", "10")
23
19
  .option("-c, --config <path>", "path to configuration file", process.cwd())
24
- .action(async (options) => {
20
+ .allowExcessArguments()
21
+ .allowUnknownOption()
22
+ .action(async (options, { args }) => {
25
23
  try {
26
24
  const configPath = await getProjectPath(options.config);
27
25
  const projectCwd = path.dirname(configPath);
@@ -32,32 +30,11 @@ builder
32
30
  });
33
31
  let hasOpenedFlag = false;
34
32
  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
33
  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}`);
34
+ const response = z.object({ queryParams: z.string() }).parse(data);
56
35
  if (options.browser && !hasOpenedFlag) {
57
36
  hasOpenedFlag = true;
58
- open(organizationId
59
- ? `${studioUrl}&organizationId=${organizationId}`
60
- : studioUrl);
37
+ open(`https://smith.langchain.com/studio${response.queryParams}`);
61
38
  }
62
39
  });
63
40
  // check if .gitignore already contains .langgraph-api
@@ -79,7 +56,7 @@ For production use, please use LangGraph Cloud.
79
56
  const envPath = path.resolve(projectCwd, configEnv);
80
57
  newWatch.push(envPath);
81
58
  const envData = await fs.readFile(envPath, "utf-8");
82
- dotenv.populate(env, dotenv.parse(envData));
59
+ populate(env, parse(envData));
83
60
  }
84
61
  else if (Array.isArray(configEnv)) {
85
62
  throw new Error("Env storage is not supported by CLI.");
@@ -87,7 +64,7 @@ For production use, please use LangGraph Cloud.
87
64
  else if (typeof configEnv === "object") {
88
65
  if (!process.env)
89
66
  throw new Error("process.env is not defined");
90
- dotenv.populate(env, configEnv);
67
+ populate(env, configEnv);
91
68
  }
92
69
  }
93
70
  const oldWatch = Object.entries(watcher.getWatched()).flatMap(([dir, files]) => files.map((file) => path.resolve(projectCwd, dir, file)));
@@ -96,31 +73,27 @@ For production use, please use LangGraph Cloud.
96
73
  watcher.unwatch(removedTarget).add(addedTarget);
97
74
  return { config, env };
98
75
  };
99
- const launchTsx = async () => {
76
+ const launchServer = async () => {
100
77
  const { config, env } = await prepareContext();
101
78
  if (child != null)
102
79
  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 });
80
+ if ("python_version" in config) {
81
+ logger.warn("Launching Python server from @langchain/langgraph-cli is experimental. Please use the `langgraph-cli` package from PyPi instead.");
82
+ const { spawnPythonServer } = await import("./dev.python.mjs");
83
+ child = await spawnPythonServer({ ...options, rest: args }, { configPath, config, env }, { pid, projectCwd });
84
+ }
85
+ else {
86
+ const { spawnNodeServer } = await import("./dev.node.mjs");
87
+ child = await spawnNodeServer({ ...options, rest: args }, { configPath, config, env }, { pid, projectCwd });
88
+ }
117
89
  };
118
90
  watcher.on("all", async (_name, path) => {
119
91
  logger.warn(`Detected changes in ${path}, restarting server`);
120
- launchTsx();
92
+ launchServer();
121
93
  });
122
- // TODO: handle errors
123
- launchTsx();
94
+ // TODO: sometimes the server keeps sending stuff
95
+ // while gracefully exiting
96
+ launchServer();
124
97
  process.on("exit", () => {
125
98
  watcher.close();
126
99
  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
+ }
package/dist/cli/up.mjs CHANGED
@@ -34,7 +34,7 @@ builder
34
34
  .description("Launch LangGraph API server.")
35
35
  .option("-c, --config <path>", "Path to configuration file", process.cwd())
36
36
  .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")
37
+ .option("-p, --port <port>", "Port to run the server on", "8123")
38
38
  .option("--recreate", "Force recreate containers and volumes", false)
39
39
  .option("--no-pull", "Running the server with locally-built images. By default LangGraph will pull the latest images from the registry")
40
40
  .option("--watch", "Restart on file changes", false)
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.6",
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",