@langgraph-js/sdk 2.2.0 → 3.0.0

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.
@@ -0,0 +1,161 @@
1
+ import { defineComponent, inject, provide, onMounted, h, type InjectionKey, type PropType, Ref } from "vue";
2
+ import { createChatStore } from "../ui-store/index.js";
3
+ import { useStore } from "@nanostores/vue";
4
+ import { PreinitializedWritableAtom, StoreValue } from "nanostores";
5
+
6
+ /**
7
+ * @zh UnionStore 类型用于合并 store 的 data 和 mutations,使其可以直接访问。
8
+ * @en The UnionStore type is used to merge the data and mutations of a store, allowing direct access.
9
+ */
10
+ export type UnionStoreVue<T extends { data: Record<string, PreinitializedWritableAtom<any>>; mutations: Record<string, any> }> = {
11
+ [k in keyof T["data"]]: Readonly<Ref<StoreValue<T["data"][k]>>>;
12
+ } & T["mutations"];
13
+
14
+ /**
15
+ * @zh useUnionStore Hook 用于将 nanostores 的 store 结构转换为更易于在 UI 组件中使用的扁平结构。
16
+ * @en The useUnionStore Hook is used to transform the nanostores store structure into a flatter structure that is easier to use in UI components.
17
+ */
18
+ export const useUnionStoreVue = <T extends { data: Record<string, any>; mutations: Record<string, any> }>(
19
+ store: T,
20
+ useStore: (store: PreinitializedWritableAtom<any>) => Readonly<Ref<any>>
21
+ ): UnionStoreVue<T> => {
22
+ const data: any = Object.fromEntries(
23
+ Object.entries(store.data as any).map(([key, value]) => {
24
+ return [key, useStore(value as any)];
25
+ })
26
+ );
27
+
28
+ return {
29
+ ...data,
30
+ ...store.mutations,
31
+ };
32
+ };
33
+
34
+ // 定义注入的 key,提供完整类型
35
+ const ChatContextKey: InjectionKey<UnionStoreVue<ReturnType<typeof createChatStore>>> = Symbol("ChatContext");
36
+
37
+ /**
38
+ * 使用 Chat Store 的组合式函数
39
+ * @throws {Error} 如果在 ChatProvider 外部使用会抛出错误
40
+ */
41
+ export const useChat = (): UnionStoreVue<ReturnType<typeof createChatStore>> => {
42
+ const context = inject(ChatContextKey);
43
+ if (!context) {
44
+ throw new Error("useChat must be used within a ChatProvider");
45
+ }
46
+ return context;
47
+ };
48
+
49
+ export interface ChatProviderProps {
50
+ defaultAgent?: string;
51
+ apiUrl?: string;
52
+ defaultHeaders?: Record<string, string>;
53
+ withCredentials?: boolean;
54
+ showHistory?: boolean;
55
+ showGraph?: boolean;
56
+ onInitError?: (error: any, currentAgent: string) => void;
57
+ }
58
+
59
+ /**
60
+ * @zh Chat Provider Hook,用于在 setup 中直接使用
61
+ * @en Chat Provider Hook, used directly in setup
62
+ */
63
+ export const useChatProvider = (props: ChatProviderProps) => {
64
+ const F = props.withCredentials
65
+ ? (url: string, options: RequestInit) => {
66
+ options.credentials = "include";
67
+ return fetch(url, options);
68
+ }
69
+ : fetch;
70
+
71
+ const store = createChatStore(
72
+ props.defaultAgent || "",
73
+ {
74
+ apiUrl: props.apiUrl,
75
+ defaultHeaders: props.defaultHeaders,
76
+ callerOptions: {
77
+ fetch: F,
78
+ maxRetries: 1,
79
+ },
80
+ },
81
+ {
82
+ showHistory: props.showHistory,
83
+ showGraph: props.showGraph,
84
+ }
85
+ );
86
+
87
+ const unionStore = useUnionStoreVue(store, useStore);
88
+
89
+ // 提供 store 给子组件
90
+ provide(ChatContextKey, unionStore);
91
+
92
+ // 初始化客户端
93
+ onMounted(() => {
94
+ unionStore
95
+ .initClient()
96
+ .then(() => {
97
+ if (unionStore.showHistory) {
98
+ unionStore.refreshHistoryList();
99
+ }
100
+ })
101
+ .catch((err) => {
102
+ console.error(err);
103
+ if (props.onInitError) {
104
+ props.onInitError(err, unionStore.currentAgent.value);
105
+ }
106
+ });
107
+ });
108
+
109
+ return {
110
+ unionStore,
111
+ };
112
+ };
113
+
114
+ /**
115
+ * Chat Provider 组件
116
+ * 提供 Chat Store 的上下文
117
+ */
118
+ export const ChatProvider = defineComponent({
119
+ name: "ChatProvider",
120
+ props: {
121
+ defaultAgent: {
122
+ type: String as PropType<string>,
123
+ default: "",
124
+ },
125
+ apiUrl: {
126
+ type: String as PropType<string>,
127
+ default: "http://localhost:8123",
128
+ },
129
+ defaultHeaders: {
130
+ type: Object as PropType<Record<string, string>>,
131
+ default: () => ({}),
132
+ },
133
+ withCredentials: {
134
+ type: Boolean as PropType<boolean>,
135
+ default: false,
136
+ },
137
+ showHistory: {
138
+ type: Boolean as PropType<boolean>,
139
+ default: false,
140
+ },
141
+ showGraph: {
142
+ type: Boolean as PropType<boolean>,
143
+ default: false,
144
+ },
145
+ onInitError: {
146
+ type: Function as PropType<(error: any, currentAgent: string) => void>,
147
+ default: undefined,
148
+ },
149
+ },
150
+ setup(props, { slots }) {
151
+ const { unionStore } = useChatProvider(props);
152
+
153
+ defineExpose({
154
+ unionStore,
155
+ });
156
+
157
+ return () => {
158
+ return slots.default?.();
159
+ };
160
+ },
161
+ });
@@ -0,0 +1 @@
1
+ export * from "./ChatContext.js";
package/src/types.ts DELETED
@@ -1,129 +0,0 @@
1
- import {
2
- Thread,
3
- Assistant,
4
- Run,
5
- StreamMode,
6
- Command,
7
- Metadata,
8
- AssistantGraph,
9
- OnConflictBehavior,
10
- ThreadStatus,
11
- ValuesStreamEvent,
12
- UpdatesStreamEvent,
13
- DebugStreamEvent,
14
- MessagesStreamEvent,
15
- MessagesTupleStreamEvent,
16
- CustomStreamEvent,
17
- EventsStreamEvent,
18
- ErrorStreamEvent,
19
- MetadataStreamEvent,
20
- FeedbackStreamEvent,
21
- Config,
22
- Checkpoint,
23
- } from "@langchain/langgraph-sdk";
24
- import { StreamEvent } from "@langchain/core/tracers/log_stream";
25
-
26
- // 基础类型定义
27
- export type AssistantSortBy = "assistant_id" | "graph_id" | "name" | "created_at" | "updated_at";
28
- export type ThreadSortBy = "thread_id" | "status" | "created_at" | "updated_at";
29
- export type SortOrder = "asc" | "desc";
30
- export type RunStatus = "pending" | "running" | "error" | "success" | "timeout" | "interrupted";
31
- export type MultitaskStrategy = "reject" | "interrupt" | "rollback" | "enqueue";
32
- export type DisconnectMode = "cancel" | "continue";
33
- export type OnCompletionBehavior = "complete" | "continue";
34
- export type CancelAction = "interrupt" | "rollback";
35
-
36
- // 流式异步生成器类型
37
- export type TypedAsyncGenerator<TStateType = unknown, TUpdateType = TStateType, TCustomType = unknown> = AsyncGenerator<
38
- | {
39
- values: ValuesStreamEvent<TStateType>;
40
- updates: UpdatesStreamEvent<TUpdateType>;
41
- custom: CustomStreamEvent<TCustomType>;
42
- debug: DebugStreamEvent;
43
- messages: MessagesStreamEvent;
44
- "messages-tuple": MessagesTupleStreamEvent;
45
- events: EventsStreamEvent;
46
- }[StreamMode]
47
- | ErrorStreamEvent
48
- | MetadataStreamEvent
49
- | FeedbackStreamEvent
50
- >;
51
-
52
- /**
53
- * 兼容 LangGraph SDK 的接口定义,方便进行无侵入式的扩展
54
- */
55
- export interface ILangGraphClient<TStateType = {}, TUpdateType = TStateType> {
56
- assistants: {
57
- search(query?: { graphId?: string; metadata?: Metadata; limit?: number; offset?: number; sortBy?: AssistantSortBy; sortOrder?: SortOrder }): Promise<Assistant[]>;
58
- getGraph(assistantId: string, options?: { xray?: boolean | number }): Promise<AssistantGraph>;
59
- };
60
- threads: {
61
- create(payload?: {
62
- metadata?: Metadata;
63
- threadId?: string;
64
- ifExists?: OnConflictBehavior;
65
- graphId?: string;
66
- supersteps?: Array<{
67
- updates: Array<{
68
- values: unknown;
69
- command?: Command;
70
- asNode: string;
71
- }>;
72
- }>;
73
- }): Promise<Thread<TStateType>>;
74
- search(query?: { metadata?: Metadata; limit?: number; offset?: number; status?: ThreadStatus; sortBy?: ThreadSortBy; sortOrder?: SortOrder }): Promise<Thread<TStateType>[]>;
75
- get(threadId: string): Promise<Thread<TStateType>>;
76
- delete(threadId: string): Promise<void>;
77
- };
78
- runs: {
79
- list(
80
- threadId: string,
81
- options?: {
82
- limit?: number;
83
- offset?: number;
84
- status?: RunStatus;
85
- }
86
- ): Promise<Run[]>;
87
-
88
- stream<TSubgraphs extends boolean = false>(
89
- threadId: string,
90
- assistantId: string,
91
- payload?: {
92
- input?: Record<string, unknown> | null;
93
- metadata?: Metadata;
94
- config?: Config;
95
- checkpointId?: string;
96
- checkpoint?: Omit<Checkpoint, "thread_id">;
97
- checkpointDuring?: boolean;
98
- interruptBefore?: "*" | string[];
99
- interruptAfter?: "*" | string[];
100
- multitaskStrategy?: MultitaskStrategy;
101
- onCompletion?: OnCompletionBehavior;
102
- signal?: AbortController["signal"];
103
- webhook?: string;
104
- onDisconnect?: DisconnectMode;
105
- afterSeconds?: number;
106
- ifNotExists?: "create" | "reject";
107
- command?: Command;
108
- onRunCreated?: (params: { run_id: string; thread_id?: string }) => void;
109
- streamMode?: StreamMode[];
110
- streamSubgraphs?: TSubgraphs;
111
- streamResumable?: boolean;
112
- feedbackKeys?: string[];
113
- }
114
- ): TypedAsyncGenerator<TSubgraphs, TStateType, TUpdateType>;
115
- joinStream(
116
- threadId: string,
117
- runId: string,
118
- options?:
119
- | {
120
- signal?: AbortSignal;
121
- cancelOnDisconnect?: boolean;
122
- lastEventId?: string;
123
- streamMode?: StreamMode | StreamMode[];
124
- }
125
- | AbortSignal
126
- ): AsyncGenerator<{ id?: string; event: StreamEvent; data: any }>;
127
- cancel(threadId: string, runId: string, wait?: boolean, action?: CancelAction): Promise<void>;
128
- };
129
- }