@assistant-ui/react 0.1.0 → 0.1.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -24,301 +24,18 @@ __export(experimental_exports, {
24
24
  useAssistantInstructions: () => useAssistantInstructions,
25
25
  useComposerContext: () => useComposerContext,
26
26
  useContentPartContext: () => useContentPartContext,
27
- useLocalRuntime: () => useLocalRuntime,
28
27
  useMessageContext: () => useMessageContext,
29
28
  useThreadContext: () => useThreadContext
30
29
  });
31
30
  module.exports = __toCommonJS(experimental_exports);
32
31
 
33
- // src/runtime/local/useLocalRuntime.tsx
34
- var import_react = require("react");
35
-
36
- // src/utils/ModelConfigTypes.ts
37
- var mergeModelConfigs = (configs) => {
38
- return configs.reduce((acc, config) => {
39
- if (config.system) {
40
- if (acc.system) {
41
- acc.system += `
42
-
43
- ${config.system}`;
44
- } else {
45
- acc.system = config.system;
46
- }
47
- }
48
- if (config.tools) {
49
- acc.tools = { ...acc.tools, ...config.tools };
50
- }
51
- return acc;
52
- }, {});
53
- };
54
-
55
- // src/runtime/utils/idUtils.tsx
56
- var import_non_secure = require("nanoid/non-secure");
57
- var generateId = (0, import_non_secure.customAlphabet)(
58
- "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
59
- 7
60
- );
61
- var optimisticPrefix = "__optimistic__";
62
- var generateOptimisticId = () => `${optimisticPrefix}${generateId()}`;
63
-
64
- // src/runtime/utils/MessageRepository.tsx
65
- var findHead = (message) => {
66
- if (message.next) return findHead(message.next);
67
- return message;
68
- };
69
- var MessageRepository = class {
70
- messages = /* @__PURE__ */ new Map();
71
- // message_id -> item
72
- head = null;
73
- root = {
74
- children: []
75
- };
76
- performOp(newParent, child, operation) {
77
- const parentOrRoot = child.prev ?? this.root;
78
- const newParentOrRoot = newParent ?? this.root;
79
- if (operation === "relink" && parentOrRoot === newParentOrRoot) return;
80
- if (operation !== "link") {
81
- parentOrRoot.children = parentOrRoot.children.filter(
82
- (m) => m !== child.current.id
83
- );
84
- if (child.prev?.next === child) {
85
- const fallbackId = child.prev.children.at(-1);
86
- const fallback = fallbackId ? this.messages.get(fallbackId) : null;
87
- if (fallback === void 0) {
88
- throw new Error(
89
- "MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui."
90
- );
91
- }
92
- child.prev.next = fallback;
93
- }
94
- }
95
- if (operation !== "cut") {
96
- newParentOrRoot.children = [
97
- ...newParentOrRoot.children,
98
- child.current.id
99
- ];
100
- if (newParent && (findHead(child) === this.head || newParent.next === null)) {
101
- newParent.next = child;
102
- }
103
- child.prev = newParent;
104
- }
105
- }
106
- getMessages() {
107
- const messages = new Array(this.head?.level ?? 0);
108
- for (let current = this.head; current; current = current.prev) {
109
- messages[current.level] = current.current;
110
- }
111
- return messages;
112
- }
113
- addOrUpdateMessage(parentId, message) {
114
- const existingItem = this.messages.get(message.id);
115
- const prev = parentId ? this.messages.get(parentId) : null;
116
- if (prev === void 0)
117
- throw new Error(
118
- "MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui."
119
- );
120
- if (existingItem) {
121
- existingItem.current = message;
122
- this.performOp(prev, existingItem, "relink");
123
- return;
124
- }
125
- const newItem = {
126
- prev,
127
- current: message,
128
- next: null,
129
- children: [],
130
- level: prev ? prev.level + 1 : 0
131
- };
132
- this.messages.set(message.id, newItem);
133
- this.performOp(prev, newItem, "link");
134
- if (this.head === prev) {
135
- this.head = newItem;
136
- }
137
- }
138
- appendOptimisticMessage(parentId, message) {
139
- let optimisticId;
140
- do {
141
- optimisticId = generateOptimisticId();
142
- } while (this.messages.has(optimisticId));
143
- this.addOrUpdateMessage(parentId, {
144
- ...message,
145
- id: optimisticId,
146
- createdAt: /* @__PURE__ */ new Date(),
147
- ...message.role === "assistant" ? { status: "in_progress" } : void 0
148
- });
149
- return optimisticId;
150
- }
151
- deleteMessage(messageId, replacementId) {
152
- const message = this.messages.get(messageId);
153
- if (!message)
154
- throw new Error(
155
- "MessageRepository(deleteMessage): Optimistic message not found. This is likely an internal bug in assistant-ui."
156
- );
157
- const replacement = replacementId === void 0 ? message.prev : replacementId === null ? null : this.messages.get(replacementId);
158
- if (replacement === void 0)
159
- throw new Error(
160
- "MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui."
161
- );
162
- for (const child of message.children) {
163
- const childMessage = this.messages.get(child);
164
- if (!childMessage)
165
- throw new Error(
166
- "MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui."
167
- );
168
- this.performOp(replacement, childMessage, "relink");
169
- }
170
- this.performOp(null, message, "cut");
171
- this.messages.delete(messageId);
172
- if (this.head === message) {
173
- this.head = replacement ? findHead(replacement) : null;
174
- }
175
- }
176
- getBranches(messageId) {
177
- const message = this.messages.get(messageId);
178
- if (!message)
179
- throw new Error(
180
- "MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui."
181
- );
182
- const { children } = message.prev ?? this.root;
183
- return children;
184
- }
185
- switchToBranch(messageId) {
186
- const message = this.messages.get(messageId);
187
- if (!message)
188
- throw new Error(
189
- "MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui."
190
- );
191
- if (message.prev) {
192
- message.prev.next = message;
193
- }
194
- this.head = findHead(message);
195
- }
196
- resetHead(messageId) {
197
- if (messageId === null) {
198
- this.head = null;
199
- return;
200
- }
201
- const message = this.messages.get(messageId);
202
- if (!message)
203
- throw new Error(
204
- "MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui."
205
- );
206
- this.head = message;
207
- for (let current = message; current; current = current.prev) {
208
- if (current.prev) {
209
- current.prev.next = current;
210
- }
211
- }
212
- }
213
- };
214
-
215
- // src/runtime/local/LocalRuntime.tsx
216
- var LocalRuntime = class {
217
- constructor(adapter) {
218
- this.adapter = adapter;
219
- }
220
- _subscriptions = /* @__PURE__ */ new Set();
221
- _configProviders = /* @__PURE__ */ new Set();
222
- abortController = null;
223
- repository = new MessageRepository();
224
- get messages() {
225
- return this.repository.getMessages();
226
- }
227
- get isRunning() {
228
- return this.abortController != null;
229
- }
230
- getBranches(messageId) {
231
- return this.repository.getBranches(messageId);
232
- }
233
- switchToBranch(branchId) {
234
- this.repository.switchToBranch(branchId);
235
- this.notifySubscribers();
236
- }
237
- async append(message) {
238
- const userMessageId = generateId();
239
- const userMessage = {
240
- id: userMessageId,
241
- role: "user",
242
- content: message.content,
243
- createdAt: /* @__PURE__ */ new Date()
244
- };
245
- this.repository.addOrUpdateMessage(message.parentId, userMessage);
246
- await this.startRun(userMessageId);
247
- }
248
- async startRun(parentId) {
249
- const id = generateId();
250
- this.repository.resetHead(parentId);
251
- const messages = this.repository.getMessages();
252
- const message = {
253
- id,
254
- role: "assistant",
255
- status: "in_progress",
256
- content: [{ type: "text", text: "" }],
257
- createdAt: /* @__PURE__ */ new Date()
258
- };
259
- this.repository.addOrUpdateMessage(parentId, { ...message });
260
- this.abortController?.abort();
261
- this.abortController = new AbortController();
262
- this.notifySubscribers();
263
- try {
264
- const updateHandler = ({ content }) => {
265
- message.content = content;
266
- this.repository.addOrUpdateMessage(parentId, { ...message });
267
- this.notifySubscribers();
268
- };
269
- const result = await this.adapter.run({
270
- messages,
271
- abortSignal: this.abortController.signal,
272
- config: mergeModelConfigs([...this._configProviders].map((p) => p())),
273
- onUpdate: updateHandler
274
- });
275
- updateHandler(result);
276
- message.status = "done";
277
- this.repository.addOrUpdateMessage(parentId, { ...message });
278
- } catch (e) {
279
- message.status = "error";
280
- this.repository.addOrUpdateMessage(parentId, { ...message });
281
- console.error(e);
282
- } finally {
283
- this.abortController = null;
284
- this.notifySubscribers();
285
- }
286
- }
287
- cancelRun() {
288
- if (!this.abortController) return;
289
- this.abortController.abort();
290
- this.abortController = null;
291
- this.notifySubscribers();
292
- }
293
- notifySubscribers() {
294
- for (const callback of this._subscriptions) callback();
295
- }
296
- subscribe(callback) {
297
- this._subscriptions.add(callback);
298
- return () => this._subscriptions.delete(callback);
299
- }
300
- registerModelConfigProvider(provider) {
301
- this._configProviders.add(provider);
302
- return () => this._configProviders.delete(provider);
303
- }
304
- };
305
-
306
- // src/runtime/local/useLocalRuntime.tsx
307
- var useLocalRuntime = (adapter) => {
308
- const [runtime] = (0, import_react.useState)(() => new LocalRuntime(adapter));
309
- (0, import_react.useInsertionEffect)(() => {
310
- runtime.adapter = adapter;
311
- });
312
- return runtime;
313
- };
314
-
315
32
  // src/context/AssistantContext.ts
316
- var import_react2 = require("react");
317
- var AssistantContext = (0, import_react2.createContext)(
33
+ var import_react = require("react");
34
+ var AssistantContext = (0, import_react.createContext)(
318
35
  null
319
36
  );
320
37
  var useAssistantContext = () => {
321
- const context = (0, import_react2.useContext)(AssistantContext);
38
+ const context = (0, import_react.useContext)(AssistantContext);
322
39
  if (!context)
323
40
  throw new Error(
324
41
  "This component must be used within an AssistantRuntimeProvider."
@@ -327,23 +44,23 @@ var useAssistantContext = () => {
327
44
  };
328
45
 
329
46
  // src/context/ThreadContext.ts
330
- var import_react3 = require("react");
331
- var ThreadContext = (0, import_react3.createContext)(null);
47
+ var import_react2 = require("react");
48
+ var ThreadContext = (0, import_react2.createContext)(null);
332
49
  var useThreadContext = () => {
333
- const context = (0, import_react3.useContext)(ThreadContext);
50
+ const context = (0, import_react2.useContext)(ThreadContext);
334
51
  if (!context)
335
52
  throw new Error("This component must be used within an AssistantRuntimeProvider.");
336
53
  return context;
337
54
  };
338
55
 
339
56
  // src/context/ComposerContext.ts
340
- var import_react5 = require("react");
57
+ var import_react4 = require("react");
341
58
 
342
59
  // src/context/MessageContext.ts
343
- var import_react4 = require("react");
344
- var MessageContext = (0, import_react4.createContext)(null);
60
+ var import_react3 = require("react");
61
+ var MessageContext = (0, import_react3.createContext)(null);
345
62
  var useMessageContext = () => {
346
- const context = (0, import_react4.useContext)(MessageContext);
63
+ const context = (0, import_react3.useContext)(MessageContext);
347
64
  if (!context)
348
65
  throw new Error(
349
66
  "This component can only be used inside a component passed to <ThreadPrimitive.Messages components={...} />."
@@ -354,8 +71,8 @@ var useMessageContext = () => {
354
71
  // src/context/ComposerContext.ts
355
72
  var useComposerContext = () => {
356
73
  const { useComposer } = useThreadContext();
357
- const { useComposer: useEditComposer } = (0, import_react5.useContext)(MessageContext) ?? {};
358
- return (0, import_react5.useMemo)(
74
+ const { useComposer: useEditComposer } = (0, import_react4.useContext)(MessageContext) ?? {};
75
+ return (0, import_react4.useMemo)(
359
76
  () => ({
360
77
  useComposer: useEditComposer ?? useComposer,
361
78
  type: useEditComposer ? "edit" : "new"
@@ -365,12 +82,12 @@ var useComposerContext = () => {
365
82
  };
366
83
 
367
84
  // src/context/ContentPartContext.ts
368
- var import_react6 = require("react");
369
- var ContentPartContext = (0, import_react6.createContext)(
85
+ var import_react5 = require("react");
86
+ var ContentPartContext = (0, import_react5.createContext)(
370
87
  null
371
88
  );
372
89
  var useContentPartContext = () => {
373
- const context = (0, import_react6.useContext)(ContentPartContext);
90
+ const context = (0, import_react5.useContext)(ContentPartContext);
374
91
  if (!context)
375
92
  throw new Error(
376
93
  "This component can only be used inside a component passed to <MessagePrimitive.Content components={...} >."
@@ -379,13 +96,13 @@ var useContentPartContext = () => {
379
96
  };
380
97
 
381
98
  // src/model-config/useAssistantInstructions.tsx
382
- var import_react7 = require("react");
99
+ var import_react6 = require("react");
383
100
  var useAssistantInstructions = (instruction) => {
384
101
  const { useModelConfig } = useAssistantContext();
385
102
  const addContextProvider = useModelConfig(
386
103
  (s) => s.registerModelConfigProvider
387
104
  );
388
- (0, import_react7.useEffect)(
105
+ (0, import_react6.useEffect)(
389
106
  () => addContextProvider(() => {
390
107
  return {
391
108
  system: instruction
@@ -400,7 +117,6 @@ var useAssistantInstructions = (instruction) => {
400
117
  useAssistantInstructions,
401
118
  useComposerContext,
402
119
  useContentPartContext,
403
- useLocalRuntime,
404
120
  useMessageContext,
405
121
  useThreadContext
406
122
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/experimental.ts","../src/runtime/local/useLocalRuntime.tsx","../src/utils/ModelConfigTypes.ts","../src/runtime/utils/idUtils.tsx","../src/runtime/utils/MessageRepository.tsx","../src/runtime/local/LocalRuntime.tsx","../src/context/AssistantContext.ts","../src/context/ThreadContext.ts","../src/context/ComposerContext.ts","../src/context/MessageContext.ts","../src/context/ContentPartContext.ts","../src/model-config/useAssistantInstructions.tsx"],"sourcesContent":["export type {\n ImageContentPart,\n ToolCallContentPart,\n UIContentPart,\n} from \"./utils/AssistantTypes\";\n\nexport type { ModelConfigProvider } from \"./utils/ModelConfigTypes\";\n\nexport { useLocalRuntime } from \"./runtime/local/useLocalRuntime\";\nexport type {\n ChatModelAdapter,\n ChatModelRunOptions,\n} from \"./runtime/local/ChatModelAdapter\";\n\nexport * from \"./context\";\nexport { useAssistantInstructions } from \"./model-config/useAssistantInstructions\";\n","\"use client\";\n\nimport { useInsertionEffect, useState } from \"react\";\nimport type { ChatModelAdapter } from \"./ChatModelAdapter\";\nimport { LocalRuntime } from \"./LocalRuntime\";\n\nexport const useLocalRuntime = (adapter: ChatModelAdapter) => {\n const [runtime] = useState(() => new LocalRuntime(adapter));\n\n useInsertionEffect(() => {\n runtime.adapter = adapter;\n });\n\n return runtime;\n};\n","\"use client\";\nimport type { z } from \"zod\";\n\nexport type Tool<TArgs> = {\n description: string;\n parameters: z.ZodSchema<TArgs>;\n execute: (args: TArgs) => unknown; // TODO return type\n};\n\nexport type ModelConfig = {\n system?: string;\n // biome-ignore lint/suspicious/noExplicitAny: TODO\n tools?: Record<string, Tool<any>>;\n};\n\nexport type ModelConfigProvider = () => ModelConfig;\n\nexport const mergeModelConfigs = (configs: ModelConfig[]): ModelConfig => {\n return configs.reduce((acc, config) => {\n if (config.system) {\n if (acc.system) {\n // TODO should the separator be configurable?\n acc.system += `\\n\\n${config.system}`;\n } else {\n acc.system = config.system;\n }\n }\n if (config.tools) {\n acc.tools = { ...acc.tools, ...config.tools };\n }\n return acc;\n }, {} as ModelConfig);\n};\n","import { customAlphabet } from \"nanoid/non-secure\";\n\nexport const generateId = customAlphabet(\n \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\",\n 7,\n);\n\nconst optimisticPrefix = \"__optimistic__\";\nexport const generateOptimisticId = () => `${optimisticPrefix}${generateId()}`;\nexport const isOptimisticId = (id: string) => id.startsWith(optimisticPrefix);\n","import type { ThreadMessage } from \"../../utils/AssistantTypes\";\nimport { generateOptimisticId } from \"./idUtils\";\n\ntype RepositoryParent = {\n children: string[];\n};\n\ntype RepositoryMessage = RepositoryParent & {\n prev: RepositoryMessage | null;\n current: ThreadMessage;\n next: RepositoryMessage | null;\n level: number;\n};\n\nconst findHead = (message: RepositoryMessage): RepositoryMessage => {\n if (message.next) return findHead(message.next);\n return message;\n};\n\nexport class MessageRepository {\n private messages = new Map<string, RepositoryMessage>(); // message_id -> item\n private head: RepositoryMessage | null = null;\n private root: RepositoryParent = {\n children: [],\n };\n\n private performOp(\n newParent: RepositoryMessage | null,\n child: RepositoryMessage,\n operation: \"cut\" | \"link\" | \"relink\",\n ) {\n const parentOrRoot = child.prev ?? this.root;\n const newParentOrRoot = newParent ?? this.root;\n\n if (operation === \"relink\" && parentOrRoot === newParentOrRoot) return;\n\n // cut\n if (operation !== \"link\") {\n parentOrRoot.children = parentOrRoot.children.filter(\n (m) => m !== child.current.id,\n );\n\n if (child.prev?.next === child) {\n const fallbackId = child.prev.children.at(-1);\n const fallback = fallbackId ? this.messages.get(fallbackId) : null;\n if (fallback === undefined) {\n throw new Error(\n \"MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.\",\n );\n }\n child.prev.next = fallback;\n }\n }\n\n // link\n if (operation !== \"cut\") {\n newParentOrRoot.children = [\n ...newParentOrRoot.children,\n child.current.id,\n ];\n\n if (\n newParent &&\n (findHead(child) === this.head || newParent.next === null)\n ) {\n newParent.next = child;\n }\n\n child.prev = newParent;\n }\n }\n getMessages() {\n const messages = new Array<ThreadMessage>(this.head?.level ?? 0);\n for (let current = this.head; current; current = current.prev) {\n messages[current.level] = current.current;\n }\n return messages;\n }\n\n addOrUpdateMessage(parentId: string | null, message: ThreadMessage) {\n const existingItem = this.messages.get(message.id);\n const prev = parentId ? this.messages.get(parentId) : null;\n if (prev === undefined)\n throw new Error(\n \"MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.\",\n );\n\n // update existing message\n if (existingItem) {\n existingItem.current = message;\n this.performOp(prev, existingItem, \"relink\");\n return;\n }\n\n // create a new message\n const newItem: RepositoryMessage = {\n prev,\n current: message,\n next: null,\n children: [],\n level: prev ? prev.level + 1 : 0,\n };\n\n this.messages.set(message.id, newItem);\n this.performOp(prev, newItem, \"link\");\n\n if (this.head === prev) {\n this.head = newItem;\n }\n }\n\n appendOptimisticMessage(\n parentId: string | null,\n message: Omit<ThreadMessage, \"id\" | \"createdAt\">,\n ) {\n let optimisticId: string;\n do {\n optimisticId = generateOptimisticId();\n } while (this.messages.has(optimisticId));\n\n this.addOrUpdateMessage(parentId, {\n ...message,\n id: optimisticId,\n createdAt: new Date(),\n ...(message.role === \"assistant\" ? { status: \"in_progress\" } : undefined),\n } as ThreadMessage);\n\n return optimisticId;\n }\n\n deleteMessage(messageId: string, replacementId?: string | null | undefined) {\n const message = this.messages.get(messageId);\n\n if (!message)\n throw new Error(\n \"MessageRepository(deleteMessage): Optimistic message not found. This is likely an internal bug in assistant-ui.\",\n );\n\n const replacement =\n replacementId === undefined\n ? message.prev // if no replacementId is provided, use the parent\n : replacementId === null\n ? null\n : this.messages.get(replacementId);\n if (replacement === undefined)\n throw new Error(\n \"MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.\",\n );\n\n for (const child of message.children) {\n const childMessage = this.messages.get(child);\n if (!childMessage)\n throw new Error(\n \"MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.\",\n );\n this.performOp(replacement, childMessage, \"relink\");\n }\n\n this.performOp(null, message, \"cut\");\n this.messages.delete(messageId);\n\n if (this.head === message) {\n this.head = replacement ? findHead(replacement) : null;\n }\n }\n\n getBranches(messageId: string) {\n const message = this.messages.get(messageId);\n if (!message)\n throw new Error(\n \"MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.\",\n );\n\n const { children } = message.prev ?? this.root;\n return children;\n }\n\n switchToBranch(messageId: string) {\n const message = this.messages.get(messageId);\n if (!message)\n throw new Error(\n \"MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.\",\n );\n\n if (message.prev) {\n message.prev.next = message;\n }\n\n this.head = findHead(message);\n }\n\n resetHead(messageId: string | null) {\n if (messageId === null) {\n this.head = null;\n return;\n }\n\n const message = this.messages.get(messageId);\n if (!message)\n throw new Error(\n \"MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.\",\n );\n\n this.head = message;\n for (\n let current: RepositoryMessage | null = message;\n current;\n current = current.prev\n ) {\n if (current.prev) {\n current.prev.next = current;\n }\n }\n }\n}\n","import type {\n AppendMessage,\n AssistantMessage,\n UserMessage,\n} from \"../../utils/AssistantTypes\";\nimport {\n type ModelConfigProvider,\n mergeModelConfigs,\n} from \"../../utils/ModelConfigTypes\";\nimport type { Unsubscribe } from \"../../utils/Unsubscribe\";\nimport type { AssistantRuntime } from \"../core/AssistantRuntime\";\nimport { MessageRepository } from \"../utils/MessageRepository\";\nimport { generateId } from \"../utils/idUtils\";\nimport type { ChatModelAdapter, ChatModelRunResult } from \"./ChatModelAdapter\";\n\nexport class LocalRuntime implements AssistantRuntime {\n private _subscriptions = new Set<() => void>();\n private _configProviders = new Set<ModelConfigProvider>();\n\n private abortController: AbortController | null = null;\n private repository = new MessageRepository();\n\n public get messages() {\n return this.repository.getMessages();\n }\n public get isRunning() {\n return this.abortController != null;\n }\n\n constructor(public adapter: ChatModelAdapter) {}\n\n public getBranches(messageId: string): string[] {\n return this.repository.getBranches(messageId);\n }\n\n public switchToBranch(branchId: string): void {\n this.repository.switchToBranch(branchId);\n this.notifySubscribers();\n }\n\n public async append(message: AppendMessage): Promise<void> {\n // add user message\n const userMessageId = generateId();\n const userMessage: UserMessage = {\n id: userMessageId,\n role: \"user\",\n content: message.content,\n createdAt: new Date(),\n };\n this.repository.addOrUpdateMessage(message.parentId, userMessage);\n\n await this.startRun(userMessageId);\n }\n\n public async startRun(parentId: string | null): Promise<void> {\n const id = generateId();\n\n this.repository.resetHead(parentId);\n const messages = this.repository.getMessages();\n\n // add assistant message\n const message: AssistantMessage = {\n id,\n role: \"assistant\",\n status: \"in_progress\",\n content: [{ type: \"text\", text: \"\" }],\n createdAt: new Date(),\n };\n this.repository.addOrUpdateMessage(parentId, { ...message });\n\n // abort existing run\n this.abortController?.abort();\n this.abortController = new AbortController();\n\n this.notifySubscribers();\n\n try {\n const updateHandler = ({ content }: ChatModelRunResult) => {\n message.content = content;\n this.repository.addOrUpdateMessage(parentId, { ...message });\n this.notifySubscribers();\n };\n const result = await this.adapter.run({\n messages,\n abortSignal: this.abortController.signal,\n config: mergeModelConfigs([...this._configProviders].map((p) => p())),\n onUpdate: updateHandler,\n });\n updateHandler(result);\n\n message.status = \"done\";\n this.repository.addOrUpdateMessage(parentId, { ...message });\n } catch (e) {\n message.status = \"error\";\n this.repository.addOrUpdateMessage(parentId, { ...message });\n console.error(e);\n } finally {\n this.abortController = null;\n this.notifySubscribers();\n }\n }\n\n cancelRun(): void {\n if (!this.abortController) return;\n\n this.abortController.abort();\n this.abortController = null;\n this.notifySubscribers();\n }\n\n private notifySubscribers() {\n for (const callback of this._subscriptions) callback();\n }\n\n public subscribe(callback: () => void): Unsubscribe {\n this._subscriptions.add(callback);\n return () => this._subscriptions.delete(callback);\n }\n\n registerModelConfigProvider(provider: ModelConfigProvider) {\n this._configProviders.add(provider);\n return () => this._configProviders.delete(provider);\n }\n}\n","import { createContext, useContext } from \"react\";\nimport type { StoreApi, UseBoundStore } from \"zustand\";\nimport type { AssistantModelConfigState } from \"./stores/AssistantModelConfig\";\n\nexport type AssistantContextValue = {\n useModelConfig: UseBoundStore<StoreApi<AssistantModelConfigState>>;\n};\n\nexport const AssistantContext = createContext<AssistantContextValue | null>(\n null,\n);\n\nexport const useAssistantContext = (): AssistantContextValue => {\n const context = useContext(AssistantContext);\n if (!context)\n throw new Error(\n \"This component must be used within an AssistantRuntimeProvider.\",\n );\n return context;\n};\n","import { createContext, useContext } from \"react\";\nimport type { StoreApi, UseBoundStore } from \"zustand\";\nimport type { ComposerState } from \"./stores/Composer\";\nimport type { ThreadState } from \"./stores/Thread\";\nimport type { ThreadViewportState } from \"./stores/ThreadViewport\";\n\nexport type ThreadContextValue = {\n useThread: UseBoundStore<StoreApi<ThreadState>>;\n useComposer: UseBoundStore<StoreApi<ComposerState>>;\n useViewport: UseBoundStore<StoreApi<ThreadViewportState>>;\n};\n\nexport const ThreadContext = createContext<ThreadContextValue | null>(null);\n\nexport const useThreadContext = (): ThreadContextValue => {\n const context = useContext(ThreadContext);\n if (!context)\n throw new Error(\"This component must be used within an AssistantRuntimeProvider.\");\n return context;\n};\n","import { useContext, useMemo } from \"react\";\nimport type { StoreApi, UseBoundStore } from \"zustand\";\nimport { MessageContext } from \"./MessageContext\";\nimport { useThreadContext } from \"./ThreadContext\";\nimport type { ComposerState } from \"./stores/Composer\";\nimport type { EditComposerState } from \"./stores/MessageComposer\";\n\nexport type ComposerContextValue = {\n useComposer: UseBoundStore<StoreApi<EditComposerState | ComposerState>>;\n type: \"edit\" | \"new\";\n};\n\nexport const useComposerContext = (): ComposerContextValue => {\n const { useComposer } = useThreadContext();\n const { useComposer: useEditComposer } = useContext(MessageContext) ?? {};\n return useMemo(\n () => ({\n useComposer: (useEditComposer ?? useComposer) as UseBoundStore<\n StoreApi<EditComposerState | ComposerState>\n >,\n type: useEditComposer ? (\"edit\" as const) : (\"new\" as const),\n }),\n [useEditComposer, useComposer],\n );\n};\n","import { createContext, useContext } from \"react\";\nimport type { StoreApi, UseBoundStore } from \"zustand\";\nimport type { MessageState } from \"./stores/Message\";\nimport type { EditComposerState } from \"./stores/MessageComposer\";\n\nexport type MessageContextValue = {\n useMessage: UseBoundStore<StoreApi<MessageState>>;\n useComposer: UseBoundStore<StoreApi<EditComposerState>>;\n};\n\nexport const MessageContext = createContext<MessageContextValue | null>(null);\n\nexport const useMessageContext = () => {\n const context = useContext(MessageContext);\n if (!context)\n throw new Error(\n \"This component can only be used inside a component passed to <ThreadPrimitive.Messages components={...} />.\",\n );\n return context;\n};\n","import { createContext, useContext } from \"react\";\nimport type { StoreApi, UseBoundStore } from \"zustand\";\nimport type { ContentPartState } from \"./stores/ContentPart\";\n\nexport type ContentPartContextValue = {\n useContentPart: UseBoundStore<StoreApi<ContentPartState>>;\n};\n\nexport const ContentPartContext = createContext<ContentPartContextValue | null>(\n null,\n);\n\nexport const useContentPartContext = (): ContentPartContextValue => {\n const context = useContext(ContentPartContext);\n if (!context)\n throw new Error(\n \"This component can only be used inside a component passed to <MessagePrimitive.Content components={...} >.\",\n );\n return context;\n};\n","\"use client\";\n\nimport { useEffect } from \"react\";\nimport { useAssistantContext } from \"../context/AssistantContext\";\n\nexport const useAssistantInstructions = (instruction: string) => {\n const { useModelConfig } = useAssistantContext();\n const addContextProvider = useModelConfig(\n (s) => s.registerModelConfigProvider,\n );\n useEffect(\n () =>\n addContextProvider(() => {\n return {\n system: instruction,\n };\n }),\n [addContextProvider, instruction],\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,mBAA6C;;;ACetC,IAAM,oBAAoB,CAAC,YAAwC;AACxE,SAAO,QAAQ,OAAO,CAAC,KAAK,WAAW;AACrC,QAAI,OAAO,QAAQ;AACjB,UAAI,IAAI,QAAQ;AAEd,YAAI,UAAU;AAAA;AAAA,EAAO,OAAO,MAAM;AAAA,MACpC,OAAO;AACL,YAAI,SAAS,OAAO;AAAA,MACtB;AAAA,IACF;AACA,QAAI,OAAO,OAAO;AAChB,UAAI,QAAQ,EAAE,GAAG,IAAI,OAAO,GAAG,OAAO,MAAM;AAAA,IAC9C;AACA,WAAO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C,QAAM,qBAAqB;AAAA,IACzB,CAAC,MAAM,EAAE;AAAA,EACX;AACA;AAAA,IACE,MACE,mBAAmB,MAAM;AACvB,aAAO;AAAA,QACL,QAAQ;AAAA,MACV;AAAA,IACF,CAAC;AAAA,IACH,CAAC,oBAAoB,WAAW;AAAA,EAClC;AACF;","names":["import_react","import_react","import_react","import_react","import_react","import_react"]}
1
+ {"version":3,"sources":["../src/experimental.ts","../src/context/AssistantContext.ts","../src/context/ThreadContext.ts","../src/context/ComposerContext.ts","../src/context/MessageContext.ts","../src/context/ContentPartContext.ts","../src/model-config/useAssistantInstructions.tsx"],"sourcesContent":["export type {\n ImageContentPart,\n ToolCallContentPart,\n UIContentPart,\n} from \"./utils/AssistantTypes\";\n\nexport type { ModelConfigProvider } from \"./utils/ModelConfigTypes\";\n\nexport * from \"./context\";\nexport { useAssistantInstructions } from \"./model-config/useAssistantInstructions\";\n","import { createContext, useContext } from \"react\";\nimport type { StoreApi, UseBoundStore } from \"zustand\";\nimport type { AssistantModelConfigState } from \"./stores/AssistantModelConfig\";\n\nexport type AssistantContextValue = {\n useModelConfig: UseBoundStore<StoreApi<AssistantModelConfigState>>;\n};\n\nexport const AssistantContext = createContext<AssistantContextValue | null>(\n null,\n);\n\nexport const useAssistantContext = (): AssistantContextValue => {\n const context = useContext(AssistantContext);\n if (!context)\n throw new Error(\n \"This component must be used within an AssistantRuntimeProvider.\",\n );\n return context;\n};\n","import { createContext, useContext } from \"react\";\nimport type { StoreApi, UseBoundStore } from \"zustand\";\nimport type { ComposerState } from \"./stores/Composer\";\nimport type { ThreadState } from \"./stores/Thread\";\nimport type { ThreadViewportState } from \"./stores/ThreadViewport\";\n\nexport type ThreadContextValue = {\n useThread: UseBoundStore<StoreApi<ThreadState>>;\n useComposer: UseBoundStore<StoreApi<ComposerState>>;\n useViewport: UseBoundStore<StoreApi<ThreadViewportState>>;\n};\n\nexport const ThreadContext = createContext<ThreadContextValue | null>(null);\n\nexport const useThreadContext = (): ThreadContextValue => {\n const context = useContext(ThreadContext);\n if (!context)\n throw new Error(\"This component must be used within an AssistantRuntimeProvider.\");\n return context;\n};\n","import { useContext, useMemo } from \"react\";\nimport type { StoreApi, UseBoundStore } from \"zustand\";\nimport { MessageContext } from \"./MessageContext\";\nimport { useThreadContext } from \"./ThreadContext\";\nimport type { ComposerState } from \"./stores/Composer\";\nimport type { EditComposerState } from \"./stores/MessageComposer\";\n\nexport type ComposerContextValue = {\n useComposer: UseBoundStore<StoreApi<EditComposerState | ComposerState>>;\n type: \"edit\" | \"new\";\n};\n\nexport const useComposerContext = (): ComposerContextValue => {\n const { useComposer } = useThreadContext();\n const { useComposer: useEditComposer } = useContext(MessageContext) ?? {};\n return useMemo(\n () => ({\n useComposer: (useEditComposer ?? useComposer) as UseBoundStore<\n StoreApi<EditComposerState | ComposerState>\n >,\n type: useEditComposer ? (\"edit\" as const) : (\"new\" as const),\n }),\n [useEditComposer, useComposer],\n );\n};\n","import { createContext, useContext } from \"react\";\nimport type { StoreApi, UseBoundStore } from \"zustand\";\nimport type { MessageState } from \"./stores/Message\";\nimport type { EditComposerState } from \"./stores/MessageComposer\";\n\nexport type MessageContextValue = {\n useMessage: UseBoundStore<StoreApi<MessageState>>;\n useComposer: UseBoundStore<StoreApi<EditComposerState>>;\n};\n\nexport const MessageContext = createContext<MessageContextValue | null>(null);\n\nexport const useMessageContext = () => {\n const context = useContext(MessageContext);\n if (!context)\n throw new Error(\n \"This component can only be used inside a component passed to <ThreadPrimitive.Messages components={...} />.\",\n );\n return context;\n};\n","import { createContext, useContext } from \"react\";\nimport type { StoreApi, UseBoundStore } from \"zustand\";\nimport type { ContentPartState } from \"./stores/ContentPart\";\n\nexport type ContentPartContextValue = {\n useContentPart: UseBoundStore<StoreApi<ContentPartState>>;\n};\n\nexport const ContentPartContext = createContext<ContentPartContextValue | null>(\n null,\n);\n\nexport const useContentPartContext = (): ContentPartContextValue => {\n const context = useContext(ContentPartContext);\n if (!context)\n throw new Error(\n \"This component can only be used inside a component passed to <MessagePrimitive.Content components={...} >.\",\n );\n return context;\n};\n","\"use client\";\n\nimport { useEffect } from \"react\";\nimport { useAssistantContext } from \"../context/AssistantContext\";\n\nexport const useAssistantInstructions = (instruction: string) => {\n const { useModelConfig } = useAssistantContext();\n const addContextProvider = useModelConfig(\n (s) => s.registerModelConfigProvider,\n );\n useEffect(\n () =>\n addContextProvider(() => {\n return {\n system: instruction,\n };\n }),\n [addContextProvider, instruction],\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAA0C;AAQnC,IAAM,uBAAmB;AAAA,EAC9B;AACF;AAEO,IAAM,sBAAsB,MAA6B;AAC9D,QAAM,cAAU,yBAAW,gBAAgB;AAC3C,MAAI,CAAC;AACH,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AACF,SAAO;AACT;;;ACnBA,IAAAA,gBAA0C;AAYnC,IAAM,oBAAgB,6BAAyC,IAAI;AAEnE,IAAM,mBAAmB,MAA0B;AACxD,QAAM,cAAU,0BAAW,aAAa;AACxC,MAAI,CAAC;AACH,UAAM,IAAI,MAAM,iEAAiE;AACnF,SAAO;AACT;;;ACnBA,IAAAC,gBAAoC;;;ACApC,IAAAC,gBAA0C;AAUnC,IAAM,qBAAiB,6BAA0C,IAAI;AAErE,IAAM,oBAAoB,MAAM;AACrC,QAAM,cAAU,0BAAW,cAAc;AACzC,MAAI,CAAC;AACH,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AACF,SAAO;AACT;;;ADPO,IAAM,qBAAqB,MAA4B;AAC5D,QAAM,EAAE,YAAY,IAAI,iBAAiB;AACzC,QAAM,EAAE,aAAa,gBAAgB,QAAI,0BAAW,cAAc,KAAK,CAAC;AACxE,aAAO;AAAA,IACL,OAAO;AAAA,MACL,aAAc,mBAAmB;AAAA,MAGjC,MAAM,kBAAmB,SAAoB;AAAA,IAC/C;AAAA,IACA,CAAC,iBAAiB,WAAW;AAAA,EAC/B;AACF;;;AExBA,IAAAC,gBAA0C;AAQnC,IAAM,yBAAqB;AAAA,EAChC;AACF;AAEO,IAAM,wBAAwB,MAA+B;AAClE,QAAM,cAAU,0BAAW,kBAAkB;AAC7C,MAAI,CAAC;AACH,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AACF,SAAO;AACT;;;ACjBA,IAAAC,gBAA0B;AAGnB,IAAM,2BAA2B,CAAC,gBAAwB;AAC/D,QAAM,EAAE,eAAe,IAAI,oBAAoB;AAC/C,QAAM,qBAAqB;AAAA,IACzB,CAAC,MAAM,EAAE;AAAA,EACX;AACA;AAAA,IACE,MACE,mBAAmB,MAAM;AACvB,aAAO;AAAA,QACL,QAAQ;AAAA,MACV;AAAA,IACF,CAAC;AAAA,IACH,CAAC,oBAAoB,WAAW;AAAA,EAClC;AACF;","names":["import_react","import_react","import_react","import_react","import_react"]}
@@ -5,116 +5,7 @@ import {
5
5
  useMessageContext,
6
6
  useThreadContext
7
7
  } from "./chunk-CY4TTHR7.mjs";
8
- import {
9
- MessageRepository,
10
- generateId
11
- } from "./chunk-GQKH2ADD.mjs";
12
- import {
13
- mergeModelConfigs
14
- } from "./chunk-X4HBDEFP.mjs";
15
-
16
- // src/runtime/local/useLocalRuntime.tsx
17
- import { useInsertionEffect, useState } from "react";
18
-
19
- // src/runtime/local/LocalRuntime.tsx
20
- var LocalRuntime = class {
21
- constructor(adapter) {
22
- this.adapter = adapter;
23
- }
24
- _subscriptions = /* @__PURE__ */ new Set();
25
- _configProviders = /* @__PURE__ */ new Set();
26
- abortController = null;
27
- repository = new MessageRepository();
28
- get messages() {
29
- return this.repository.getMessages();
30
- }
31
- get isRunning() {
32
- return this.abortController != null;
33
- }
34
- getBranches(messageId) {
35
- return this.repository.getBranches(messageId);
36
- }
37
- switchToBranch(branchId) {
38
- this.repository.switchToBranch(branchId);
39
- this.notifySubscribers();
40
- }
41
- async append(message) {
42
- const userMessageId = generateId();
43
- const userMessage = {
44
- id: userMessageId,
45
- role: "user",
46
- content: message.content,
47
- createdAt: /* @__PURE__ */ new Date()
48
- };
49
- this.repository.addOrUpdateMessage(message.parentId, userMessage);
50
- await this.startRun(userMessageId);
51
- }
52
- async startRun(parentId) {
53
- const id = generateId();
54
- this.repository.resetHead(parentId);
55
- const messages = this.repository.getMessages();
56
- const message = {
57
- id,
58
- role: "assistant",
59
- status: "in_progress",
60
- content: [{ type: "text", text: "" }],
61
- createdAt: /* @__PURE__ */ new Date()
62
- };
63
- this.repository.addOrUpdateMessage(parentId, { ...message });
64
- this.abortController?.abort();
65
- this.abortController = new AbortController();
66
- this.notifySubscribers();
67
- try {
68
- const updateHandler = ({ content }) => {
69
- message.content = content;
70
- this.repository.addOrUpdateMessage(parentId, { ...message });
71
- this.notifySubscribers();
72
- };
73
- const result = await this.adapter.run({
74
- messages,
75
- abortSignal: this.abortController.signal,
76
- config: mergeModelConfigs([...this._configProviders].map((p) => p())),
77
- onUpdate: updateHandler
78
- });
79
- updateHandler(result);
80
- message.status = "done";
81
- this.repository.addOrUpdateMessage(parentId, { ...message });
82
- } catch (e) {
83
- message.status = "error";
84
- this.repository.addOrUpdateMessage(parentId, { ...message });
85
- console.error(e);
86
- } finally {
87
- this.abortController = null;
88
- this.notifySubscribers();
89
- }
90
- }
91
- cancelRun() {
92
- if (!this.abortController) return;
93
- this.abortController.abort();
94
- this.abortController = null;
95
- this.notifySubscribers();
96
- }
97
- notifySubscribers() {
98
- for (const callback of this._subscriptions) callback();
99
- }
100
- subscribe(callback) {
101
- this._subscriptions.add(callback);
102
- return () => this._subscriptions.delete(callback);
103
- }
104
- registerModelConfigProvider(provider) {
105
- this._configProviders.add(provider);
106
- return () => this._configProviders.delete(provider);
107
- }
108
- };
109
-
110
- // src/runtime/local/useLocalRuntime.tsx
111
- var useLocalRuntime = (adapter) => {
112
- const [runtime] = useState(() => new LocalRuntime(adapter));
113
- useInsertionEffect(() => {
114
- runtime.adapter = adapter;
115
- });
116
- return runtime;
117
- };
8
+ import "./chunk-J5LGTIGS.mjs";
118
9
 
119
10
  // src/model-config/useAssistantInstructions.tsx
120
11
  import { useEffect } from "react";
@@ -137,7 +28,6 @@ export {
137
28
  useAssistantInstructions,
138
29
  useComposerContext,
139
30
  useContentPartContext,
140
- useLocalRuntime,
141
31
  useMessageContext,
142
32
  useThreadContext
143
33
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/runtime/local/useLocalRuntime.tsx","../src/runtime/local/LocalRuntime.tsx","../src/model-config/useAssistantInstructions.tsx"],"sourcesContent":["\"use client\";\n\nimport { useInsertionEffect, useState } from \"react\";\nimport type { ChatModelAdapter } from \"./ChatModelAdapter\";\nimport { LocalRuntime } from \"./LocalRuntime\";\n\nexport const useLocalRuntime = (adapter: ChatModelAdapter) => {\n const [runtime] = useState(() => new LocalRuntime(adapter));\n\n useInsertionEffect(() => {\n runtime.adapter = adapter;\n });\n\n return runtime;\n};\n","import type {\n AppendMessage,\n AssistantMessage,\n UserMessage,\n} from \"../../utils/AssistantTypes\";\nimport {\n type ModelConfigProvider,\n mergeModelConfigs,\n} from \"../../utils/ModelConfigTypes\";\nimport type { Unsubscribe } from \"../../utils/Unsubscribe\";\nimport type { AssistantRuntime } from \"../core/AssistantRuntime\";\nimport { MessageRepository } from \"../utils/MessageRepository\";\nimport { generateId } from \"../utils/idUtils\";\nimport type { ChatModelAdapter, ChatModelRunResult } from \"./ChatModelAdapter\";\n\nexport class LocalRuntime implements AssistantRuntime {\n private _subscriptions = new Set<() => void>();\n private _configProviders = new Set<ModelConfigProvider>();\n\n private abortController: AbortController | null = null;\n private repository = new MessageRepository();\n\n public get messages() {\n return this.repository.getMessages();\n }\n public get isRunning() {\n return this.abortController != null;\n }\n\n constructor(public adapter: ChatModelAdapter) {}\n\n public getBranches(messageId: string): string[] {\n return this.repository.getBranches(messageId);\n }\n\n public switchToBranch(branchId: string): void {\n this.repository.switchToBranch(branchId);\n this.notifySubscribers();\n }\n\n public async append(message: AppendMessage): Promise<void> {\n // add user message\n const userMessageId = generateId();\n const userMessage: UserMessage = {\n id: userMessageId,\n role: \"user\",\n content: message.content,\n createdAt: new Date(),\n };\n this.repository.addOrUpdateMessage(message.parentId, userMessage);\n\n await this.startRun(userMessageId);\n }\n\n public async startRun(parentId: string | null): Promise<void> {\n const id = generateId();\n\n this.repository.resetHead(parentId);\n const messages = this.repository.getMessages();\n\n // add assistant message\n const message: AssistantMessage = {\n id,\n role: \"assistant\",\n status: \"in_progress\",\n content: [{ type: \"text\", text: \"\" }],\n createdAt: new Date(),\n };\n this.repository.addOrUpdateMessage(parentId, { ...message });\n\n // abort existing run\n this.abortController?.abort();\n this.abortController = new AbortController();\n\n this.notifySubscribers();\n\n try {\n const updateHandler = ({ content }: ChatModelRunResult) => {\n message.content = content;\n this.repository.addOrUpdateMessage(parentId, { ...message });\n this.notifySubscribers();\n };\n const result = await this.adapter.run({\n messages,\n abortSignal: this.abortController.signal,\n config: mergeModelConfigs([...this._configProviders].map((p) => p())),\n onUpdate: updateHandler,\n });\n updateHandler(result);\n\n message.status = \"done\";\n this.repository.addOrUpdateMessage(parentId, { ...message });\n } catch (e) {\n message.status = \"error\";\n this.repository.addOrUpdateMessage(parentId, { ...message });\n console.error(e);\n } finally {\n this.abortController = null;\n this.notifySubscribers();\n }\n }\n\n cancelRun(): void {\n if (!this.abortController) return;\n\n this.abortController.abort();\n this.abortController = null;\n this.notifySubscribers();\n }\n\n private notifySubscribers() {\n for (const callback of this._subscriptions) callback();\n }\n\n public subscribe(callback: () => void): Unsubscribe {\n this._subscriptions.add(callback);\n return () => this._subscriptions.delete(callback);\n }\n\n registerModelConfigProvider(provider: ModelConfigProvider) {\n this._configProviders.add(provider);\n return () => this._configProviders.delete(provider);\n }\n}\n","\"use client\";\n\nimport { useEffect } from \"react\";\nimport { useAssistantContext } from \"../context/AssistantContext\";\n\nexport const useAssistantInstructions = (instruction: string) => {\n const { useModelConfig } = useAssistantContext();\n const addContextProvider = useModelConfig(\n (s) => s.registerModelConfigProvider,\n );\n useEffect(\n () =>\n addContextProvider(() => {\n return {\n system: instruction,\n };\n }),\n [addContextProvider, instruction],\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAEA,SAAS,oBAAoB,gBAAgB;;;ACatC,IAAM,eAAN,MAA+C;AAAA,EAcpD,YAAmB,SAA2B;AAA3B;AAAA,EAA4B;AAAA,EAbvC,iBAAiB,oBAAI,IAAgB;AAAA,EACrC,mBAAmB,oBAAI,IAAyB;AAAA,EAEhD,kBAA0C;AAAA,EAC1C,aAAa,IAAI,kBAAkB;AAAA,EAE3C,IAAW,WAAW;AACpB,WAAO,KAAK,WAAW,YAAY;AAAA,EACrC;AAAA,EACA,IAAW,YAAY;AACrB,WAAO,KAAK,mBAAmB;AAAA,EACjC;AAAA,EAIO,YAAY,WAA6B;AAC9C,WAAO,KAAK,WAAW,YAAY,SAAS;AAAA,EAC9C;AAAA,EAEO,eAAe,UAAwB;AAC5C,SAAK,WAAW,eAAe,QAAQ;AACvC,SAAK,kBAAkB;AAAA,EACzB;AAAA,EAEA,MAAa,OAAO,SAAuC;AAEzD,UAAM,gBAAgB,WAAW;AACjC,UAAM,cAA2B;AAAA,MAC/B,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,SAAS,QAAQ;AAAA,MACjB,WAAW,oBAAI,KAAK;AAAA,IACtB;AACA,SAAK,WAAW,mBAAmB,QAAQ,UAAU,WAAW;AAEhE,UAAM,KAAK,SAAS,aAAa;AAAA,EACnC;AAAA,EAEA,MAAa,SAAS,UAAwC;AAC5D,UAAM,KAAK,WAAW;AAEtB,SAAK,WAAW,UAAU,QAAQ;AAClC,UAAM,WAAW,KAAK,WAAW,YAAY;AAG7C,UAAM,UAA4B;AAAA,MAChC;AAAA,MACA,MAAM;AAAA,MACN,QAAQ;AAAA,MACR,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,GAAG,CAAC;AAAA,MACpC,WAAW,oBAAI,KAAK;AAAA,IACtB;AACA,SAAK,WAAW,mBAAmB,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;AAAA,EACpD;AACF;;;ADrHO,IAAM,kBAAkB,CAAC,YAA8B;AAC5D,QAAM,CAAC,OAAO,IAAI,SAAS,MAAM,IAAI,aAAa,OAAO,CAAC;AAE1D,qBAAmB,MAAM;AACvB,YAAQ,UAAU;AAAA,EACpB,CAAC;AAED,SAAO;AACT;;;AEZA,SAAS,iBAAiB;AAGnB,IAAM,2BAA2B,CAAC,gBAAwB;AAC/D,QAAM,EAAE,eAAe,IAAI,oBAAoB;AAC/C,QAAM,qBAAqB;AAAA,IACzB,CAAC,MAAM,EAAE;AAAA,EACX;AACA;AAAA,IACE,MACE,mBAAmB,MAAM;AACvB,aAAO;AAAA,QACL,QAAQ;AAAA,MACV;AAAA,IACF,CAAC;AAAA,IACH,CAAC,oBAAoB,WAAW;AAAA,EAClC;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/model-config/useAssistantInstructions.tsx"],"sourcesContent":["\"use client\";\n\nimport { useEffect } from \"react\";\nimport { useAssistantContext } from \"../context/AssistantContext\";\n\nexport const useAssistantInstructions = (instruction: string) => {\n const { useModelConfig } = useAssistantContext();\n const addContextProvider = useModelConfig(\n (s) => s.registerModelConfigProvider,\n );\n useEffect(\n () =>\n addContextProvider(() => {\n return {\n system: instruction,\n };\n }),\n [addContextProvider, instruction],\n );\n};\n"],"mappings":";;;;;;;;;;AAEA,SAAS,iBAAiB;AAGnB,IAAM,2BAA2B,CAAC,gBAAwB;AAC/D,QAAM,EAAE,eAAe,IAAI,oBAAoB;AAC/C,QAAM,qBAAqB;AAAA,IACzB,CAAC,MAAM,EAAE;AAAA,EACX;AACA;AAAA,IACE,MACE,mBAAmB,MAAM;AACvB,aAAO;AAAA,QACL,QAAQ;AAAA,MACV;AAAA,IACF,CAAC;AAAA,IACH,CAAC,oBAAoB,WAAW;AAAA,EAClC;AACF;","names":[]}