@langgraph-js/pure-graph 1.4.2 → 1.4.4

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/index.js CHANGED
@@ -1,5 +1,2 @@
1
- export * from './createEndpoint';
2
- export * from './types';
3
- export * from './global';
4
- export * from './threads/index';
5
- export * from './utils/createEntrypointGraph';
1
+ export { A as AssistantEndpoint, L as LangGraphGlobal, c as createEndpoint, a as createEntrypointGraph, r as registerGraph } from './index-DcXE-SZb.js';
2
+ //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@langgraph-js/pure-graph",
3
- "version": "1.4.2",
3
+ "version": "1.4.4",
4
4
  "description": "A library that provides a standard LangGraph endpoint for integrating into various frameworks like Next.js and Hono.js, with support for multiple storage backends (SQLite, PostgreSQL, Redis) and message queues.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -67,7 +67,7 @@
67
67
  },
68
68
  "scripts": {
69
69
  "dev": "bun run test/hono.ts",
70
- "build": " tsc",
70
+ "build": " vite build && tsc",
71
71
  "prepublish": "pnpm build"
72
72
  }
73
73
  }
@@ -1,21 +0,0 @@
1
- import { zValidator } from '@hono/zod-validator';
2
- import { Hono } from 'hono';
3
- import { client } from './endpoint';
4
- import { AssistantsSearchSchema, AssistantGraphQuerySchema } from '../zod';
5
- const api = new Hono();
6
- api.post('/assistants/search', zValidator('json', AssistantsSearchSchema), async (c) => {
7
- // Search Assistants
8
- const payload = c.req.valid('json');
9
- let total = 0;
10
- const data = await client.assistants.search(payload);
11
- c.res.headers.set('X-Pagination-Total', total.toString());
12
- return c.json(data);
13
- });
14
- api.get('/assistants/:assistant_id/graph', zValidator('query', AssistantGraphQuerySchema), async (c) => {
15
- const xray = c.req.valid('query').xray;
16
- const data = await client.assistants.getGraph(c.req.param('assistant_id'), {
17
- xray: xray !== undefined ? xray === 'true' : undefined,
18
- });
19
- return c.json(data);
20
- });
21
- export default api;
@@ -1,2 +0,0 @@
1
- import { createEndpoint } from '../../createEndpoint.js';
2
- export const client = createEndpoint();
@@ -1,11 +0,0 @@
1
- import { Hono } from 'hono';
2
- import Assistants from './assistants';
3
- import Runs from './runs';
4
- import Threads from './threads';
5
- import { cors } from 'hono/cors';
6
- const app = new Hono();
7
- app.use(cors());
8
- app.route('/', Assistants);
9
- app.route('/', Runs);
10
- app.route('/', Threads);
11
- export default app;
@@ -1,54 +0,0 @@
1
- import { zValidator } from '@hono/zod-validator';
2
- import { Hono } from 'hono';
3
- import { streamSSE } from 'hono/streaming';
4
- import { client } from './endpoint';
5
- import { ThreadIdParamSchema, RunIdParamSchema, RunStreamPayloadSchema, RunListQuerySchema, RunCancelQuerySchema, ThreadStateUpdate, } from '../zod';
6
- import { serialiseAsDict } from '../../graph/stream';
7
- import z from 'zod';
8
- const api = new Hono();
9
- // 最常用的对话接口
10
- api.post('/threads/:thread_id/runs/stream', zValidator('param', ThreadIdParamSchema), zValidator('json', RunStreamPayloadSchema), async (c) => {
11
- // Stream Run
12
- const { thread_id } = c.req.valid('param');
13
- const payload = c.req.valid('json');
14
- // c.header('Content-Location', `/threads/${thread_id}/runs/${run.run_id}`);
15
- return streamSSE(c, async (stream) => {
16
- /** @ts-ignore zod v3 的问题,与 ts 类型不一致 */
17
- for await (const { event, data } of client.runs.stream(thread_id, payload.assistant_id, payload)) {
18
- await stream.writeSSE({ data: serialiseAsDict(data) ?? '', event });
19
- }
20
- });
21
- });
22
- api.get('/threads/:thread_id/runs', zValidator('param', ThreadIdParamSchema), zValidator('query', RunListQuerySchema), async (c) => {
23
- const { thread_id } = c.req.valid('param');
24
- const { limit, offset, status } = c.req.valid('query');
25
- const runs = await client.runs.list(thread_id, { limit, offset, status });
26
- return c.json(runs);
27
- });
28
- api.post('/threads/:thread_id/runs/:run_id/cancel', zValidator('param', RunIdParamSchema), zValidator('query', RunCancelQuerySchema), async (c) => {
29
- // Cancel Run Http
30
- const { thread_id, run_id } = c.req.valid('param');
31
- const { wait, action } = c.req.valid('query');
32
- const cancel = client.runs.cancel(thread_id, run_id, wait, action);
33
- if (wait) {
34
- await cancel;
35
- }
36
- return c.body(null, wait ? 204 : 202);
37
- });
38
- api.post('/threads/:thread_id/state', zValidator('param', z.object({ thread_id: z.string().uuid() })), zValidator('json', ThreadStateUpdate), async (c) => {
39
- // Update Thread State
40
- const { thread_id } = c.req.valid('param');
41
- const payload = c.req.valid('json');
42
- // const config: RunnableConfig = { configurable: { thread_id } };
43
- // if (payload.checkpoint_id) {
44
- // config.configurable ??= {};
45
- // config.configurable.checkpoint_id = payload.checkpoint_id;
46
- // }
47
- // if (payload.checkpoint) {
48
- // config.configurable ??= {};
49
- // Object.assign(config.configurable, payload.checkpoint);
50
- // }
51
- const inserted = await client.threads.updateState(thread_id, payload);
52
- return c.json(inserted);
53
- });
54
- export default api;
@@ -1,30 +0,0 @@
1
- import { zValidator } from '@hono/zod-validator';
2
- import { Hono } from 'hono';
3
- import { client } from './endpoint';
4
- import { ThreadIdParamSchema, ThreadCreatePayloadSchema, ThreadSearchPayloadSchema } from '../zod';
5
- const api = new Hono();
6
- // Threads Routes
7
- api.post('/threads', zValidator('json', ThreadCreatePayloadSchema), async (c) => {
8
- const payload = c.req.valid('json');
9
- const thread = await client.threads.create(payload);
10
- return c.json(thread);
11
- });
12
- api.post('/threads/search', zValidator('json', ThreadSearchPayloadSchema), async (c) => {
13
- // Search Threads
14
- const payload = c.req.valid('json');
15
- const result = await client.threads.search(payload);
16
- c.res.headers.set('X-Pagination-Total', result.length.toString());
17
- return c.json(result);
18
- });
19
- api.get('/threads/:thread_id', zValidator('param', ThreadIdParamSchema), async (c) => {
20
- // Get Thread
21
- const { thread_id } = c.req.valid('param');
22
- return c.json(await client.threads.get(thread_id));
23
- });
24
- api.delete('/threads/:thread_id', zValidator('param', ThreadIdParamSchema), async (c) => {
25
- // Delete Thread
26
- const { thread_id } = c.req.valid('param');
27
- await client.threads.delete(thread_id);
28
- return new Response(null, { status: 204 });
29
- });
30
- export default api;
@@ -1,2 +0,0 @@
1
- import { createEndpoint } from '../../createEndpoint.js';
2
- export const client = createEndpoint();
@@ -1,2 +0,0 @@
1
- // 统一路由处理器
2
- export { GET, POST, DELETE } from "./router";
@@ -1,179 +0,0 @@
1
- /** @ts-ignore */
2
- import { NextResponse } from 'next/server';
3
- import { client } from './endpoint';
4
- import { AssistantsSearchSchema, AssistantGraphQuerySchema, RunStreamPayloadSchema, RunListQuerySchema, RunCancelQuerySchema, ThreadCreatePayloadSchema, ThreadSearchPayloadSchema, ThreadStateUpdate, } from '../zod';
5
- import { serialiseAsDict } from '../../graph/stream';
6
- // Next.js App Router 的 SSE 响应实现
7
- async function sseResponse(generator) {
8
- const encoder = new TextEncoder();
9
- const stream = new ReadableStream({
10
- async start(controller) {
11
- try {
12
- for await (const { event, data } of generator) {
13
- const line = `event: ${event}\n` + `data: ${serialiseAsDict(data, 0)}\n\n`;
14
- controller.enqueue(encoder.encode(line));
15
- }
16
- }
17
- catch (err) {
18
- // ignore
19
- }
20
- finally {
21
- controller.close();
22
- }
23
- },
24
- });
25
- return new Response(stream, {
26
- headers: {
27
- 'Content-Type': 'text/event-stream; charset=utf-8',
28
- 'Cache-Control': 'no-cache, no-transform',
29
- Connection: 'keep-alive',
30
- },
31
- });
32
- }
33
- // 统一路由处理器
34
- export async function GET(req) {
35
- const url = new URL(req.url);
36
- const pathname = url.pathname;
37
- // Assistants routes
38
- if (pathname.match(/\/assistants\/[^/]+\/graph$/)) {
39
- const match = pathname.match(/\/assistants\/([^/]+)\/graph$/);
40
- if (match) {
41
- const assistant_id = match[1];
42
- const xrayParam = url.searchParams.get('xray') ?? undefined;
43
- const queryParams = { xray: xrayParam };
44
- const { xray } = AssistantGraphQuerySchema.parse(queryParams);
45
- const data = await client.assistants.getGraph(assistant_id, {
46
- xray: xray !== undefined ? xray === 'true' : undefined,
47
- });
48
- return NextResponse.json(data);
49
- }
50
- }
51
- // Threads routes
52
- if (pathname.match(/\/threads\/[0-9a-fA-F-]{36}$/)) {
53
- const match = pathname.match(/\/threads\/([0-9a-fA-F-]{36})$/);
54
- if (match) {
55
- const thread_id = match[1];
56
- const data = await client.threads.get(thread_id);
57
- return NextResponse.json(data);
58
- }
59
- }
60
- // Runs routes
61
- if (pathname.match(/\/threads\/[0-9a-fA-F-]{36}\/runs$/)) {
62
- const match = pathname.match(/\/threads\/([0-9a-fA-F-]{36})\/runs$/);
63
- if (match) {
64
- const thread_id = match[1];
65
- const limit = url.searchParams.get('limit') ?? undefined;
66
- const offset = url.searchParams.get('offset') ?? undefined;
67
- const status = url.searchParams.get('status') ?? undefined;
68
- const queryParams = { limit, offset, status };
69
- const { limit: parsedLimit, offset: parsedOffset, status: parsedStatus, } = RunListQuerySchema.parse(queryParams);
70
- const runs = await client.runs.list(thread_id, {
71
- limit: parsedLimit,
72
- offset: parsedOffset,
73
- status: parsedStatus,
74
- });
75
- return Response.json(runs);
76
- }
77
- }
78
- return new NextResponse('Not Found', { status: 404 });
79
- }
80
- export async function POST(req) {
81
- const url = new URL(req.url);
82
- const pathname = url.pathname;
83
- // Assistants routes
84
- if (pathname.endsWith('/assistants/search')) {
85
- const body = await req.json();
86
- const payload = AssistantsSearchSchema.parse(body);
87
- const data = await client.assistants.search({
88
- graphId: payload.graph_id,
89
- metadata: payload.metadata,
90
- limit: payload.limit,
91
- offset: payload.offset,
92
- });
93
- return NextResponse.json(data, {
94
- headers: { 'X-Pagination-Total': String(data.length) },
95
- });
96
- }
97
- // Threads routes
98
- if (pathname.endsWith('/threads')) {
99
- const body = await req.json();
100
- const payload = ThreadCreatePayloadSchema.parse(body);
101
- const thread = await client.threads.create({
102
- thread_id: payload.thread_id,
103
- metadata: payload.metadata,
104
- if_exists: payload.if_exists ?? undefined,
105
- });
106
- return NextResponse.json(thread);
107
- }
108
- if (pathname.endsWith('/threads/search')) {
109
- const body = await req.json();
110
- const payload = ThreadSearchPayloadSchema.parse(body);
111
- const result = await client.threads.search({
112
- metadata: payload.metadata,
113
- status: payload.status,
114
- limit: payload.limit,
115
- offset: payload.offset,
116
- sortBy: payload.sort_by ?? undefined,
117
- sortOrder: payload.sort_order ?? undefined,
118
- });
119
- return NextResponse.json(result, {
120
- headers: { 'X-Pagination-Total': String(result.length) },
121
- });
122
- }
123
- // Threads state update
124
- if (pathname.match(/\/threads\/[0-9a-fA-F-]{36}\/state$/)) {
125
- const match = pathname.match(/\/threads\/([0-9a-fA-F-]{36})\/state$/);
126
- if (match) {
127
- const thread_id = match[1];
128
- const body = await req.json();
129
- const payload = ThreadStateUpdate.parse(body);
130
- const result = await client.threads.updateState(thread_id, payload);
131
- return NextResponse.json(result);
132
- }
133
- }
134
- // Runs routes - stream
135
- if (pathname.match(/\/threads\/[0-9a-fA-F-]{36}\/runs\/stream$/)) {
136
- const match = pathname.match(/\/threads\/([0-9a-fA-F-]{36})\/runs\/stream$/);
137
- if (match) {
138
- const thread_id = match[1];
139
- const body = await req.json();
140
- const payload = RunStreamPayloadSchema.parse(body);
141
- const generator = client.runs.stream(thread_id, payload.assistant_id, payload);
142
- return sseResponse(generator);
143
- }
144
- }
145
- // Runs routes - cancel
146
- if (pathname.match(/\/threads\/[0-9a-fA-F-]{36}\/runs\/[0-9a-fA-F-]{36}\/cancel$/)) {
147
- const match = pathname.match(/\/threads\/([0-9a-fA-F-]{36})\/runs\/([0-9a-fA-F-]{36})\/cancel$/);
148
- if (match) {
149
- const thread_id = match[1];
150
- const run_id = match[2];
151
- const waitParam = url.searchParams.get('wait') ?? undefined;
152
- const actionParam = url.searchParams.get('action') ?? undefined;
153
- const queryParams = {
154
- wait: waitParam ? waitParam === 'true' : false,
155
- action: actionParam ?? 'interrupt',
156
- };
157
- const { wait, action } = RunCancelQuerySchema.parse(queryParams);
158
- const promise = client.runs.cancel(thread_id, run_id, wait, action);
159
- if (wait)
160
- await promise;
161
- return new Response(null, { status: wait ? 204 : 202 });
162
- }
163
- }
164
- return new NextResponse('Not Found', { status: 404 });
165
- }
166
- export async function DELETE(req) {
167
- const url = new URL(req.url);
168
- const pathname = url.pathname;
169
- // Threads routes
170
- if (pathname.match(/\/threads\/[0-9a-fA-F-]{36}$/)) {
171
- const match = pathname.match(/\/threads\/([0-9a-fA-F-]{36})$/);
172
- if (match) {
173
- const thread_id = match[1];
174
- await client.threads.delete(thread_id);
175
- return new NextResponse(null, { status: 204 });
176
- }
177
- }
178
- return new NextResponse('Not Found', { status: 404 });
179
- }
@@ -1,127 +0,0 @@
1
- import z from 'zod';
2
- export const AssistantConfigurable = z
3
- .object({
4
- thread_id: z.string().optional(),
5
- thread_ts: z.string().optional(),
6
- })
7
- .catchall(z.unknown());
8
- export const AssistantConfig = z
9
- .object({
10
- tags: z.array(z.string()).optional(),
11
- recursion_limit: z.number().int().optional(),
12
- configurable: AssistantConfigurable.optional(),
13
- })
14
- .catchall(z.unknown())
15
- .describe('The configuration of an assistant.');
16
- export const Assistant = z.object({
17
- assistant_id: z.string().uuid(),
18
- graph_id: z.string(),
19
- config: AssistantConfig,
20
- created_at: z.string(),
21
- updated_at: z.string(),
22
- metadata: z.object({}).catchall(z.any()),
23
- });
24
- export const MetadataSchema = z
25
- .object({
26
- source: z.union([z.literal('input'), z.literal('loop'), z.literal('update'), z.string()]).optional(),
27
- step: z.number().optional(),
28
- writes: z.record(z.unknown()).nullable().optional(),
29
- parents: z.record(z.string()).optional(),
30
- })
31
- .catchall(z.unknown());
32
- export const SendSchema = z.object({
33
- node: z.string(),
34
- input: z.unknown().nullable(),
35
- });
36
- export const CommandSchema = z.object({
37
- update: z
38
- .union([z.record(z.unknown()), z.array(z.tuple([z.string(), z.unknown()]))])
39
- .nullable()
40
- .optional(),
41
- resume: z.unknown().optional(),
42
- goto: z.union([SendSchema, z.array(SendSchema), z.string(), z.array(z.string())]).optional(),
43
- });
44
- // 公共的查询参数验证 schema
45
- export const PaginationQuerySchema = z.object({
46
- limit: z.number().int().optional(),
47
- offset: z.number().int().optional(),
48
- });
49
- export const ThreadIdParamSchema = z.object({
50
- thread_id: z.string().uuid(),
51
- });
52
- export const RunIdParamSchema = z.object({
53
- thread_id: z.string().uuid(),
54
- run_id: z.string().uuid(),
55
- });
56
- // Assistants 相关的 schema
57
- export const AssistantsSearchSchema = z.object({
58
- graph_id: z.string().optional(),
59
- metadata: MetadataSchema.optional(),
60
- limit: z.number().int().optional(),
61
- offset: z.number().int().optional(),
62
- });
63
- export const AssistantGraphQuerySchema = z.object({
64
- xray: z.string().optional(),
65
- });
66
- // Runs 相关的 schema
67
- export const RunStreamPayloadSchema = z
68
- .object({
69
- assistant_id: z.union([z.string().uuid(), z.string()]),
70
- checkpoint_id: z.string().optional(),
71
- input: z.any().optional(),
72
- command: CommandSchema.optional(),
73
- metadata: MetadataSchema.optional(),
74
- config: AssistantConfig.optional(),
75
- webhook: z.string().optional(),
76
- interrupt_before: z.union([z.literal('*'), z.array(z.string())]).optional(),
77
- interrupt_after: z.union([z.literal('*'), z.array(z.string())]).optional(),
78
- on_disconnect: z.enum(['cancel', 'continue']).optional().default('continue'),
79
- multitask_strategy: z.enum(['reject', 'rollback', 'interrupt', 'enqueue']).optional(),
80
- stream_mode: z
81
- .array(z.enum(['values', 'messages', 'messages-tuple', 'updates', 'events', 'debug', 'custom']))
82
- .optional(),
83
- stream_subgraphs: z.boolean().optional(),
84
- stream_resumable: z.boolean().optional(),
85
- after_seconds: z.number().optional(),
86
- if_not_exists: z.enum(['create', 'reject']).optional(),
87
- on_completion: z.enum(['complete', 'continue']).optional(),
88
- feedback_keys: z.array(z.string()).optional(),
89
- langsmith_tracer: z.unknown().optional(),
90
- })
91
- .describe('Payload for creating a stateful run.');
92
- export const RunListQuerySchema = z.object({
93
- limit: z.coerce.number().int().optional(),
94
- offset: z.coerce.number().int().optional(),
95
- status: z.enum(['pending', 'running', 'error', 'success', 'timeout', 'interrupted']).optional(),
96
- });
97
- export const RunCancelQuerySchema = z.object({
98
- wait: z.coerce.boolean().optional().default(false),
99
- action: z.enum(['interrupt', 'rollback']).optional().default('interrupt'),
100
- });
101
- // Threads 相关的 schema
102
- export const ThreadCreatePayloadSchema = z
103
- .object({
104
- thread_id: z.string().uuid().describe('The ID of the thread. If not provided, an ID is generated.').optional(),
105
- metadata: MetadataSchema.optional(),
106
- if_exists: z.union([z.literal('raise'), z.literal('do_nothing')]).optional(),
107
- })
108
- .describe('Payload for creating a thread.');
109
- export const ThreadSearchPayloadSchema = z
110
- .object({
111
- metadata: z.record(z.unknown()).describe('Metadata to search for.').optional(),
112
- status: z.enum(['idle', 'busy', 'interrupted', 'error']).describe('Filter by thread status.').optional(),
113
- values: z.record(z.unknown()).describe('Filter by thread values.').optional(),
114
- limit: z.number().int().gte(1).lte(1000).describe('Maximum number to return.').optional(),
115
- offset: z.number().int().gte(0).describe('Offset to start from.').optional(),
116
- sort_by: z.enum(['thread_id', 'status', 'created_at', 'updated_at']).describe('Sort by field.').optional(),
117
- sort_order: z.enum(['asc', 'desc']).describe('Sort order.').optional(),
118
- })
119
- .describe('Payload for listing threads.');
120
- export const ThreadStateUpdate = z
121
- .object({
122
- values: z.union([z.record(z.string(), z.unknown()), z.array(z.record(z.string(), z.unknown()))]).nullish(),
123
- // as_node: z.string().optional(),
124
- // checkpoint_id: z.string().optional(),
125
- // checkpoint: CheckpointSchema.nullish(),
126
- })
127
- .describe('Payload for adding state to a thread.');
@@ -1,77 +0,0 @@
1
- import { streamState } from './graph/stream.js';
2
- import { getGraph, GRAPHS } from './utils/getGraph.js';
3
- import { LangGraphGlobal } from './global.js';
4
- export { registerGraph } from './utils/getGraph.js';
5
- export const AssistantEndpoint = {
6
- async search(query) {
7
- if (query?.graphId) {
8
- return [
9
- {
10
- assistant_id: query.graphId,
11
- graph_id: query.graphId,
12
- config: {},
13
- created_at: new Date().toISOString(),
14
- updated_at: new Date().toISOString(),
15
- metadata: {},
16
- version: 1,
17
- name: query.graphId,
18
- description: '',
19
- },
20
- ];
21
- }
22
- return Object.entries(GRAPHS).map(([graphId, _]) => ({
23
- assistant_id: graphId,
24
- graph_id: graphId,
25
- config: {},
26
- metadata: {},
27
- version: 1,
28
- name: graphId,
29
- description: '',
30
- created_at: new Date().toISOString(),
31
- updated_at: new Date().toISOString(),
32
- }));
33
- },
34
- async getGraph(assistantId, options) {
35
- const config = {};
36
- const graph = await getGraph(assistantId, config);
37
- const drawable = await graph.getGraphAsync({
38
- ...config,
39
- xray: options?.xray ?? undefined,
40
- });
41
- return drawable.toJSON();
42
- },
43
- };
44
- export const createEndpoint = () => {
45
- const threads = LangGraphGlobal.globalThreadsManager;
46
- return {
47
- assistants: AssistantEndpoint,
48
- threads,
49
- runs: {
50
- list(threadId, options) {
51
- return threads.listRuns(threadId, options);
52
- },
53
- async cancel(threadId, runId, wait, action) {
54
- return LangGraphGlobal.globalMessageQueue.cancelQueue(runId);
55
- },
56
- async *stream(threadId, assistantId, payload) {
57
- if (!payload.config) {
58
- payload.config = {
59
- configurable: {
60
- graph_id: assistantId,
61
- thread_id: threadId,
62
- },
63
- };
64
- }
65
- for await (const data of streamState(threads, threads.createRun(threadId, assistantId, payload), payload, {
66
- attempt: 0,
67
- getGraph,
68
- })) {
69
- yield data;
70
- }
71
- },
72
- joinStream(threadId, runId, options) {
73
- throw new Error('Function not implemented.');
74
- },
75
- },
76
- };
77
- };
package/dist/global.js DELETED
@@ -1,13 +0,0 @@
1
- import { createCheckPointer, createMessageQueue, createThreadManager } from './storage/index.js';
2
- const [globalMessageQueue, globalCheckPointer] = await Promise.all([createMessageQueue(), createCheckPointer()]);
3
- console.debug('LG | checkpointer created');
4
- const globalThreadsManager = await createThreadManager({
5
- checkpointer: globalCheckPointer,
6
- });
7
- console.debug('LG | threads manager created');
8
- console.debug('LG | global init done');
9
- export class LangGraphGlobal {
10
- static globalMessageQueue = globalMessageQueue;
11
- static globalCheckPointer = globalCheckPointer;
12
- static globalThreadsManager = globalThreadsManager;
13
- }