@tambo-ai/react 0.21.1 → 0.21.3
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/hooks/use-suggestions.d.ts.map +1 -1
- package/dist/hooks/use-suggestions.js +11 -5
- package/dist/hooks/use-suggestions.js.map +1 -1
- package/dist/providers/tambo-provider.d.ts +1 -0
- package/dist/providers/tambo-provider.d.ts.map +1 -1
- package/dist/providers/tambo-provider.js +3 -2
- package/dist/providers/tambo-provider.js.map +1 -1
- package/dist/providers/tambo-registry-provider.d.ts +3 -0
- package/dist/providers/tambo-registry-provider.d.ts.map +1 -1
- package/dist/providers/tambo-registry-provider.js +7 -1
- package/dist/providers/tambo-registry-provider.js.map +1 -1
- package/dist/providers/tambo-thread-provider.d.ts.map +1 -1
- package/dist/providers/tambo-thread-provider.js +24 -26
- package/dist/providers/tambo-thread-provider.js.map +1 -1
- package/esm/hooks/use-suggestions.d.ts.map +1 -1
- package/esm/hooks/use-suggestions.js +11 -5
- package/esm/hooks/use-suggestions.js.map +1 -1
- package/esm/providers/tambo-provider.d.ts +1 -0
- package/esm/providers/tambo-provider.d.ts.map +1 -1
- package/esm/providers/tambo-provider.js +3 -2
- package/esm/providers/tambo-provider.js.map +1 -1
- package/esm/providers/tambo-registry-provider.d.ts +3 -0
- package/esm/providers/tambo-registry-provider.d.ts.map +1 -1
- package/esm/providers/tambo-registry-provider.js +7 -1
- package/esm/providers/tambo-registry-provider.js.map +1 -1
- package/esm/providers/tambo-thread-provider.d.ts.map +1 -1
- package/esm/providers/tambo-thread-provider.js +24 -26
- package/esm/providers/tambo-thread-provider.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-suggestions.d.ts","sourceRoot":"","sources":["../../src/hooks/use-suggestions.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,0BAA0B,CAAC;
|
|
1
|
+
{"version":3,"file":"use-suggestions.d.ts","source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AAK,CAAC,GACjE,iCAAiC,CAAC;AAEpC;;;;GAIG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,0BAA+B,GACvC,yBAAyB,CAsI3B"}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.useTamboSuggestions = useTamboSuggestions;
|
|
4
4
|
const react_1 = require("react");
|
|
5
|
+
const generate_component_response_1 = require("../model/generate-component-response");
|
|
5
6
|
const validate_input_1 = require("../model/validate-input");
|
|
6
7
|
const tambo_client_provider_1 = require("../providers/tambo-client-provider");
|
|
7
8
|
const tambo_provider_1 = require("../providers/tambo-provider");
|
|
@@ -18,7 +19,7 @@ const use_thread_input_1 = require("./use-thread-input");
|
|
|
18
19
|
*/
|
|
19
20
|
function useTamboSuggestions(options = {}) {
|
|
20
21
|
const { maxSuggestions = 3 } = options;
|
|
21
|
-
const { thread } = (0, tambo_thread_provider_1.useTamboThread)();
|
|
22
|
+
const { thread, generationStage } = (0, tambo_thread_provider_1.useTamboThread)();
|
|
22
23
|
const { sendThreadMessage } = (0, tambo_provider_1.useTambo)();
|
|
23
24
|
const tamboClient = (0, tambo_client_provider_1.useTamboClient)();
|
|
24
25
|
const { componentList, toolRegistry, componentToolAssociations } = (0, tambo_registry_provider_1.useTamboRegistry)();
|
|
@@ -31,12 +32,17 @@ function useTamboSuggestions(options = {}) {
|
|
|
31
32
|
(0, react_1.useEffect)(() => {
|
|
32
33
|
setSelectedSuggestionId(null);
|
|
33
34
|
}, [latestMessageId]);
|
|
35
|
+
const shouldGenerateSuggestions = latestMessageId && isLatestFromTambo && (0, generate_component_response_1.isIdleStage)(generationStage);
|
|
34
36
|
// Use React Query to fetch suggestions when a new hydra message is received
|
|
35
37
|
const suggestionsResult = (0, react_query_hooks_1.useTamboQuery)({
|
|
36
|
-
//
|
|
37
|
-
|
|
38
|
+
// Make sure the query key changes when the message changes, so that we are
|
|
39
|
+
// always generating suggestions when there is a new message
|
|
40
|
+
queryKey: [
|
|
41
|
+
"suggestions",
|
|
42
|
+
shouldGenerateSuggestions ? latestMessageId : null,
|
|
43
|
+
],
|
|
38
44
|
queryFn: async () => {
|
|
39
|
-
if (!
|
|
45
|
+
if (!shouldGenerateSuggestions) {
|
|
40
46
|
return [];
|
|
41
47
|
}
|
|
42
48
|
// Get registered components from the registry
|
|
@@ -78,7 +84,7 @@ function useTamboSuggestions(options = {}) {
|
|
|
78
84
|
// Generate suggestions mutation
|
|
79
85
|
const generateMutationState = (0, react_query_hooks_1.useTamboMutation)({
|
|
80
86
|
mutationFn: async (abortController) => {
|
|
81
|
-
if (!
|
|
87
|
+
if (!shouldGenerateSuggestions) {
|
|
82
88
|
return undefined;
|
|
83
89
|
}
|
|
84
90
|
// Get registered components from the registry
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-suggestions.js","sourceRoot":"","sources":["../../src/hooks/use-suggestions.ts"],"names":[],"mappings":";;AA2EA,kDAmIC;AA7MD,iCAA4C;AAC5C,4DAAwD;AACxD,8EAAoE;AACpE,gEAAuD;AACvD,kFAAwE;AACxE,8EAAoE;AACpE,qDAG6B;AAC7B,+CAA0D;AAC1D,2DAK6B;AAC7B,yDAA+E;AAoD/E;;;;GAIG;AACH,SAAgB,mBAAmB,CACjC,UAAsC,EAAE;IAExC,MAAM,EAAE,cAAc,GAAG,CAAC,EAAE,GAAG,OAAO,CAAC;IACvC,MAAM,EAAE,MAAM,EAAE,GAAG,IAAA,sCAAc,GAAE,CAAC;IACpC,MAAM,EAAE,iBAAiB,EAAE,GAAG,IAAA,yBAAQ,GAAE,CAAC;IACzC,MAAM,WAAW,GAAG,IAAA,sCAAc,GAAE,CAAC;IACrC,MAAM,EAAE,aAAa,EAAE,YAAY,EAAE,yBAAyB,EAAE,GAC9D,IAAA,0CAAgB,GAAE,CAAC;IAErB,MAAM,CAAC,oBAAoB,EAAE,uBAAuB,CAAC,GAAG,IAAA,gBAAQ,EAE9D,IAAI,CA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e,CAAC,MAAM,EAAE,CACnC,CAAC;QACJ,CAAC;QACD,yBAAyB;QACzB,KAAK,EAAE,KAAK;KACb,CAAC,CAAC;IAEH,mEAAmE;IACnE,8DAA8D;IAC9D,MAAM,WAAW,GAAG,iBAAiB;QACnC,CAAC,CAAC,CAAC,iBAAiB,CAAC,IAAI,IAAI,qBAAqB,CAAC,IAAI,IAAI,EAAE,CAAC;QAC9D,CAAC,CAAC,EAAE,CAAC;IAEP,OAAO;QACL,WAAW;QACX,MAAM,EAAE,mBAAmB,CAAC,WAAW;QACvC,oBAAoB;QACpB,YAAY,EAAE,mBAAmB;QACjC,cAAc,EAAE,qBAAqB;QACrC,iBAAiB;QACjB,GAAG,IAAA,oCAAsB,EAAC,mBAAmB,EAAE,qBAAqB,CAAC;KACtE,CAAC;AACJ,CAAC","sourcesContent":["import TamboAI from \"@tambo-ai/typescript-sdk\";\nimport { useEffect, useState } from \"react\";\nimport { validateInput } from \"../model/validate-input\";\nimport { useTamboClient } from \"../providers/tambo-client-provider\";\nimport { useTambo } from \"../providers/tambo-provider\";\nimport { useTamboRegistry } from \"../providers/tambo-registry-provider\";\nimport { useTamboThread } from \"../providers/tambo-thread-provider\";\nimport {\n CombinedMutationResult,\n combineMutationResults,\n} from \"../util/query-utils\";\nimport { getAvailableComponents } from \"../util/registry\";\nimport {\n UseTamboMutationResult,\n UseTamboQueryResult,\n useTamboMutation,\n useTamboQuery,\n} from \"./react-query-hooks\";\nimport { INPUT_ERROR_MESSAGES, useTamboThreadInput } from \"./use-thread-input\";\n\n/**\n * Configuration options for the useTamboSuggestions hook\n */\nexport interface useTamboSuggestionsOptions {\n /** Maximum number of suggestions to generate (1-10, default 3) */\n maxSuggestions?: number;\n}\n\n/**\n * Return value interface for useTamboSuggestions hook\n */\nexport interface useTamboSuggestionsResultInternal {\n /** List of available suggestions (also available in generateResult.data) */\n suggestions: TamboAI.Beta.Threads.Suggestion[];\n /** ID of the currently selected suggestion */\n selectedSuggestionId: string | null;\n /**\n * Accept and apply a suggestion (also available in acceptResult.mutateAsync)\n * @param suggestion - The suggestion to accept\n * @param shouldSubmit - Whether to automatically submit after accepting (default: false)\n */\n accept: (acceptOptions: {\n suggestion: TamboAI.Beta.Threads.Suggestion;\n shouldSubmit?: boolean;\n }) => Promise<void>;\n\n /** Result and network state for accepting a suggestion */\n acceptResult: UseTamboMutationResult<\n void,\n Error,\n { suggestion: TamboAI.Beta.Threads.Suggestion; shouldSubmit?: boolean }\n >;\n\n /** Result and network state for generating suggestions */\n generateResult: UseTamboMutationResult<\n TamboAI.Beta.Threads.Suggestions.SuggestionGenerateResponse | undefined,\n Error,\n AbortController\n >;\n\n /** The full suggestions query object from React Query */\n suggestionsResult: UseTamboQueryResult<\n TamboAI.Beta.Threads.Suggestions.SuggestionGenerateResponse | undefined,\n Error\n >;\n}\n\ntype useTamboSuggestionsResult = CombinedMutationResult<any, Error> &\n useTamboSuggestionsResultInternal;\n\n/**\n * Hook for managing Tambo AI suggestions in a thread\n * @param options - Configuration options for suggestion generation\n * @returns Object containing suggestions state and control functions\n */\nexport function useTamboSuggestions(\n options: useTamboSuggestionsOptions = {},\n): useTamboSuggestionsResult {\n const { maxSuggestions = 3 } = options;\n const { thread } = useTamboThread();\n const { sendThreadMessage } = useTambo();\n const tamboClient = useTamboClient();\n const { componentList, toolRegistry, componentToolAssociations } =\n useTamboRegistry();\n\n const [selectedSuggestionId, setSelectedSuggestionId] = useState<\n string | null\n >(null);\n const { setValue: setInputValue } = useTamboThreadInput();\n\n const latestMessage = thread.messages[thread.messages.length - 1];\n const isLatestFromTambo = latestMessage?.role === \"assistant\";\n const latestMessageId = latestMessage?.id;\n\n // Reset selected suggestion when the message changes\n useEffect(() => {\n setSelectedSuggestionId(null);\n }, [latestMessageId]);\n\n // Use React Query to fetch suggestions when a new hydra message is received\n const suggestionsResult = useTamboQuery({\n // Only include latestMessageId in the queryKey if the message is from hydra\n queryKey: [\"suggestions\", isLatestFromTambo ? latestMessageId : null],\n queryFn: async () => {\n if (!latestMessageId || !isLatestFromTambo) {\n return [];\n }\n\n // Get registered components from the registry\n const components = getAvailableComponents(\n componentList,\n toolRegistry,\n componentToolAssociations,\n );\n\n return await tamboClient.beta.threads.suggestions.generate(\n thread.id,\n latestMessageId,\n {\n maxSuggestions,\n availableComponents: components,\n },\n );\n },\n // Only run the query if we have a valid message from hydra\n enabled: Boolean(latestMessageId && isLatestFromTambo),\n // Don't refetch on window focus or reconnect\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n // Don't retry on failure\n retry: false,\n });\n\n // Accept suggestion mutation\n const acceptMutationState = useTamboMutation<\n void,\n Error,\n { suggestion: TamboAI.Beta.Threads.Suggestion; shouldSubmit?: boolean }\n >({\n mutationFn: async ({ suggestion, shouldSubmit = false }) => {\n const validation = validateInput(suggestion.detailedSuggestion);\n if (!validation.isValid) {\n if (validation.error) {\n throw validation.error;\n }\n throw new Error(INPUT_ERROR_MESSAGES.VALIDATION);\n }\n\n if (shouldSubmit) {\n await sendThreadMessage(validation.sanitizedInput, {\n threadId: thread.id,\n });\n } else {\n setInputValue(validation.sanitizedInput);\n }\n setSelectedSuggestionId(suggestion.id);\n },\n });\n\n // Generate suggestions mutation\n const generateMutationState = useTamboMutation<\n TamboAI.Beta.Threads.Suggestions.SuggestionGenerateResponse | undefined,\n Error,\n AbortController\n >({\n mutationFn: async (abortController: AbortController) => {\n if (!latestMessageId || !isLatestFromTambo) {\n return undefined;\n }\n\n // Get registered components from the registry\n const components = getAvailableComponents(\n componentList,\n toolRegistry,\n componentToolAssociations,\n );\n\n return await tamboClient.beta.threads.suggestions.generate(\n thread.id,\n latestMessageId,\n {\n maxSuggestions,\n availableComponents: components,\n },\n { signal: abortController.signal },\n );\n },\n // Don't retry on failure\n retry: false,\n });\n\n // Use the query data if available, otherwise use the mutation data\n // Only return suggestions if the latest message is from hydra\n const suggestions = isLatestFromTambo\n ? (suggestionsResult.data ?? generateMutationState.data ?? [])\n : [];\n\n return {\n suggestions,\n accept: acceptMutationState.mutateAsync,\n selectedSuggestionId,\n acceptResult: acceptMutationState,\n generateResult: generateMutationState,\n suggestionsResult,\n ...combineMutationResults(acceptMutationState, generateMutationState),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"use-suggestions.js","sourceRoot":"","sources":["../../src/hooks/use-suggestions.ts"],"names":[],"mappings":";;AA4EA,kDAwIC;AAnND,iCAA4C;AAC5C,sFAAmE;AACnE,4DAAwD;AACxD,8EAAoE;AACpE,gEAAuD;AACvD,kFAAwE;AACxE,8EAAoE;AACpE,qDAG6B;AAC7B,+CAA0D;AAC1D,2DAK6B;AAC7B,yDAA+E;AAoD/E;;;;GAIG;AACH,SAAgB,mBAAmB,CACjC,UAAsC,EAAE;IAExC,MAAM,EAAE,cAAc,GAAG,CAAC,EAAE,GAAG,OAAO,CAAC;IACvC,MAAM,EAAE,MAAM,EAAE,eAAe,EAAE,GAAG,IAAA,sCAAc,GAAE,CAAC;IACrD,MAAM,EAAE,iBAAiB,EAAE,GAAG,IAAA,yBAAQ,GAAE,CAAC;IACzC,MAAM,WAAW,GAAG,IAAA,sCAAc,GAAE,CAAC;IACrC,MAAM,EAAE,aAAa,EAAE,YAAY,EAAE,yBAAyB,EAAE,GAC9D,IAAA,0CAAgB,GAAE,CAAC;IAErB,MAAM,CAAC,oBAAoB,EAAE,uBAAuB,CAAC,GAAG,IAAA,gBAAQ,EAE9D,IAAI,CAAC,CAAC;IACR,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAE,GAAG,IAAA,sCAAmB,GAAE,CAAC;IAE1D,MAAM,aAAa,GAAG,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAClE,MAAM,iBAAiB,GAAG,aAAa,EAAE,IAAI,KAAK,WAAW,CAAC;IAC9D,MAAM,eAAe,GAAG,aAAa,EAAE,EAAE,CAAC;IAE1C,qDAAqD;IACrD,IAAA,iBAAS,EAAC,GAAG,EAAE;QACb,uBA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,WAAW;QACX,MAAM,EAAE,mBAAmB,CAAC,WAAW;QACvC,oBAAoB;QACpB,YAAY,EAAE,mBAAmB;QACjC,cAAc,EAAE,qBAAqB;QACrC,iBAAiB;QACjB,GAAG,IAAA,oCAAsB,EAAC,mBAAmB,EAAE,qBAAqB,CAAC;KACtE,CAAC;AACJ,CAAC","sourcesContent":["import TamboAI from \"@tambo-ai/typescript-sdk\";\nimport { useEffect, useState } from \"react\";\nimport { isIdleStage } from \"../model/generate-component-response\";\nimport { validateInput } from \"../model/validate-input\";\nimport { useTamboClient } from \"../providers/tambo-client-provider\";\nimport { useTambo } from \"../providers/tambo-provider\";\nimport { useTamboRegistry } from \"../providers/tambo-registry-provider\";\nimport { useTamboThread } from \"../providers/tambo-thread-provider\";\nimport {\n CombinedMutationResult,\n combineMutationResults,\n} from \"../util/query-utils\";\nimport { getAvailableComponents } from \"../util/registry\";\nimport {\n UseTamboMutationResult,\n UseTamboQueryResult,\n useTamboMutation,\n useTamboQuery,\n} from \"./react-query-hooks\";\nimport { INPUT_ERROR_MESSAGES, useTamboThreadInput } from \"./use-thread-input\";\n\n/**\n * Configuration options for the useTamboSuggestions hook\n */\nexport interface useTamboSuggestionsOptions {\n /** Maximum number of suggestions to generate (1-10, default 3) */\n maxSuggestions?: number;\n}\n\n/**\n * Return value interface for useTamboSuggestions hook\n */\nexport interface useTamboSuggestionsResultInternal {\n /** List of available suggestions (also available in generateResult.data) */\n suggestions: TamboAI.Beta.Threads.Suggestion[];\n /** ID of the currently selected suggestion */\n selectedSuggestionId: string | null;\n /**\n * Accept and apply a suggestion (also available in acceptResult.mutateAsync)\n * @param suggestion - The suggestion to accept\n * @param shouldSubmit - Whether to automatically submit after accepting (default: false)\n */\n accept: (acceptOptions: {\n suggestion: TamboAI.Beta.Threads.Suggestion;\n shouldSubmit?: boolean;\n }) => Promise<void>;\n\n /** Result and network state for accepting a suggestion */\n acceptResult: UseTamboMutationResult<\n void,\n Error,\n { suggestion: TamboAI.Beta.Threads.Suggestion; shouldSubmit?: boolean }\n >;\n\n /** Result and network state for generating suggestions */\n generateResult: UseTamboMutationResult<\n TamboAI.Beta.Threads.Suggestions.SuggestionGenerateResponse | undefined,\n Error,\n AbortController\n >;\n\n /** The full suggestions query object from React Query */\n suggestionsResult: UseTamboQueryResult<\n TamboAI.Beta.Threads.Suggestions.SuggestionGenerateResponse | undefined,\n Error\n >;\n}\n\ntype useTamboSuggestionsResult = CombinedMutationResult<any, Error> &\n useTamboSuggestionsResultInternal;\n\n/**\n * Hook for managing Tambo AI suggestions in a thread\n * @param options - Configuration options for suggestion generation\n * @returns Object containing suggestions state and control functions\n */\nexport function useTamboSuggestions(\n options: useTamboSuggestionsOptions = {},\n): useTamboSuggestionsResult {\n const { maxSuggestions = 3 } = options;\n const { thread, generationStage } = useTamboThread();\n const { sendThreadMessage } = useTambo();\n const tamboClient = useTamboClient();\n const { componentList, toolRegistry, componentToolAssociations } =\n useTamboRegistry();\n\n const [selectedSuggestionId, setSelectedSuggestionId] = useState<\n string | null\n >(null);\n const { setValue: setInputValue } = useTamboThreadInput();\n\n const latestMessage = thread.messages[thread.messages.length - 1];\n const isLatestFromTambo = latestMessage?.role === \"assistant\";\n const latestMessageId = latestMessage?.id;\n\n // Reset selected suggestion when the message changes\n useEffect(() => {\n setSelectedSuggestionId(null);\n }, [latestMessageId]);\n\n const shouldGenerateSuggestions =\n latestMessageId && isLatestFromTambo && isIdleStage(generationStage);\n // Use React Query to fetch suggestions when a new hydra message is received\n const suggestionsResult = useTamboQuery({\n // Make sure the query key changes when the message changes, so that we are\n // always generating suggestions when there is a new message\n queryKey: [\n \"suggestions\",\n shouldGenerateSuggestions ? latestMessageId : null,\n ],\n queryFn: async () => {\n if (!shouldGenerateSuggestions) {\n return [];\n }\n\n // Get registered components from the registry\n const components = getAvailableComponents(\n componentList,\n toolRegistry,\n componentToolAssociations,\n );\n\n return await tamboClient.beta.threads.suggestions.generate(\n thread.id,\n latestMessageId,\n {\n maxSuggestions,\n availableComponents: components,\n },\n );\n },\n // Only run the query if we have a valid message from hydra\n enabled: Boolean(latestMessageId && isLatestFromTambo),\n // Don't refetch on window focus or reconnect\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n // Don't retry on failure\n retry: false,\n });\n\n // Accept suggestion mutation\n const acceptMutationState = useTamboMutation<\n void,\n Error,\n { suggestion: TamboAI.Beta.Threads.Suggestion; shouldSubmit?: boolean }\n >({\n mutationFn: async ({ suggestion, shouldSubmit = false }) => {\n const validation = validateInput(suggestion.detailedSuggestion);\n if (!validation.isValid) {\n if (validation.error) {\n throw validation.error;\n }\n throw new Error(INPUT_ERROR_MESSAGES.VALIDATION);\n }\n\n if (shouldSubmit) {\n await sendThreadMessage(validation.sanitizedInput, {\n threadId: thread.id,\n });\n } else {\n setInputValue(validation.sanitizedInput);\n }\n setSelectedSuggestionId(suggestion.id);\n },\n });\n\n // Generate suggestions mutation\n const generateMutationState = useTamboMutation<\n TamboAI.Beta.Threads.Suggestions.SuggestionGenerateResponse | undefined,\n Error,\n AbortController\n >({\n mutationFn: async (abortController: AbortController) => {\n if (!shouldGenerateSuggestions) {\n return undefined;\n }\n\n // Get registered components from the registry\n const components = getAvailableComponents(\n componentList,\n toolRegistry,\n componentToolAssociations,\n );\n return await tamboClient.beta.threads.suggestions.generate(\n thread.id,\n latestMessageId,\n {\n maxSuggestions,\n availableComponents: components,\n },\n { signal: abortController.signal },\n );\n },\n // Don't retry on failure\n retry: false,\n });\n\n // Use the query data if available, otherwise use the mutation data\n // Only return suggestions if the latest message is from hydra\n const suggestions = isLatestFromTambo\n ? (suggestionsResult.data ?? generateMutationState.data ?? [])\n : [];\n\n return {\n suggestions,\n accept: acceptMutationState.mutateAsync,\n selectedSuggestionId,\n acceptResult: acceptMutationState,\n generateResult: generateMutationState,\n suggestionsResult,\n ...combineMutationResults(acceptMutationState, generateMutationState),\n };\n}\n"]}
|
|
@@ -12,6 +12,7 @@ import { TamboThreadContextProps } from "./tambo-thread-provider";
|
|
|
12
12
|
* @param props.apiKey - The API key for the Tambo API
|
|
13
13
|
* @param props.components - The components to register
|
|
14
14
|
* @param props.environment - The environment to use for the Tambo API
|
|
15
|
+
* @param props.tools - The tools to register
|
|
15
16
|
* @returns The TamboProvider component
|
|
16
17
|
*/
|
|
17
18
|
export declare const TamboProvider: React.FC<PropsWithChildren<TamboClientProviderProps & TamboRegistryProviderProps>>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tambo-provider.d.ts","sourceRoot":"","sources":["../../src/providers/tambo-provider.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,EAAE,iBAAiB,EAA6B,MAAM,OAAO,CAAC;AAC5E,OAAO,EACL,uBAAuB,EAEvB,wBAAwB,EAGzB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACL,0BAA0B,EAG3B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAEL,0BAA0B,EAC3B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,uBAAuB,EAGxB,MAAM,yBAAyB,CAAC;AAEjC
|
|
1
|
+
{"version":3,"file":"tambo-provider.d.ts","sourceRoot":"","sources":["../../src/providers/tambo-provider.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,EAAE,iBAAiB,EAA6B,MAAM,OAAO,CAAC;AAC5E,OAAO,EACL,uBAAuB,EAEvB,wBAAwB,EAGzB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACL,0BAA0B,EAG3B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAEL,0BAA0B,EAC3B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,uBAAuB,EAGxB,MAAM,yBAAyB,CAAC;AAEjC;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,aAAa,EAAE,KAAK,CAAC,EAAE,CAClC,iBAAiB,CAAC,wBAAwB,GAAG,0BAA0B,CAAC,CAsBzE,CAAC;AACF,MAAM,MAAM,iBAAiB,GAAG,uBAAuB,GACrD,uBAAuB,GACvB,0BAA0B,CAAC;AAE7B,eAAO,MAAM,YAAY,kCAExB,CAAC;AA6BF;;;;;;GAMG;AACH,eAAO,MAAM,QAAQ,yBAEpB,CAAC"}
|
|
@@ -49,15 +49,16 @@ const tambo_thread_provider_1 = require("./tambo-thread-provider");
|
|
|
49
49
|
* @param props.apiKey - The API key for the Tambo API
|
|
50
50
|
* @param props.components - The components to register
|
|
51
51
|
* @param props.environment - The environment to use for the Tambo API
|
|
52
|
+
* @param props.tools - The tools to register
|
|
52
53
|
* @returns The TamboProvider component
|
|
53
54
|
*/
|
|
54
|
-
const TamboProvider = ({ children, tamboUrl, apiKey, components, environment }) => {
|
|
55
|
+
const TamboProvider = ({ children, tamboUrl, apiKey, components, environment, tools }) => {
|
|
55
56
|
// Should only be used in browser
|
|
56
57
|
if (typeof window === "undefined") {
|
|
57
58
|
console.error("TamboProvider must be used within a browser");
|
|
58
59
|
}
|
|
59
60
|
return (react_1.default.createElement(tambo_client_provider_1.TamboClientProvider, { tamboUrl: tamboUrl, apiKey: apiKey, environment: environment },
|
|
60
|
-
react_1.default.createElement(tambo_registry_provider_1.TamboRegistryProvider, { components: components },
|
|
61
|
+
react_1.default.createElement(tambo_registry_provider_1.TamboRegistryProvider, { components: components, tools: tools },
|
|
61
62
|
react_1.default.createElement(tambo_thread_provider_1.TamboThreadProvider, null,
|
|
62
63
|
react_1.default.createElement(tambo_component_provider_1.TamboComponentProvider, null,
|
|
63
64
|
react_1.default.createElement(TamboCompositeProvider, null, children))))));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tambo-provider.js","sourceRoot":"","sources":["../../src/providers/tambo-provider.tsx"],"names":[],"mappings":";AAAA,YAAY,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACb,+CAA4E;AAC5E,mEAMiC;AACjC,yEAIoC;AACpC,uEAGmC;AACnC,mEAIiC;AAEjC
|
|
1
|
+
{"version":3,"file":"tambo-provider.js","sourceRoot":"","sources":["../../src/providers/tamb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B,GAAG,OAAO;SACX,IAEA,QAAQ,CACa,CACzB,CAAC;AACJ,CAAC,CAAC;AAEF;;;;;;GAMG;AACI,MAAM,QAAQ,GAAG,GAAG,EAAE;IAC3B,OAAO,IAAA,kBAAU,EAAC,oBAAY,CAAC,CAAC;AAClC,CAAC,CAAC;AAFW,QAAA,QAAQ,YAEnB","sourcesContent":["\"use client\";\nimport React, { PropsWithChildren, createContext, useContext } from \"react\";\nimport {\n TamboClientContextProps,\n TamboClientProvider,\n TamboClientProviderProps,\n useTamboClient,\n useTamboQueryClient,\n} from \"./tambo-client-provider\";\nimport {\n TamboComponentContextProps,\n TamboComponentProvider,\n useTamboComponent,\n} from \"./tambo-component-provider\";\nimport {\n TamboRegistryProvider,\n TamboRegistryProviderProps,\n} from \"./tambo-registry-provider\";\nimport {\n TamboThreadContextProps,\n TamboThreadProvider,\n useTamboThread,\n} from \"./tambo-thread-provider\";\n\n/**\n * The TamboProvider gives full access to the whole Tambo API. This includes the\n * TamboAI client, the component registry, and the current thread context.\n * @param props - The props for the TamboProvider\n * @param props.children - The children to wrap\n * @param props.tamboUrl - The URL of the Tambo API\n * @param props.apiKey - The API key for the Tambo API\n * @param props.components - The components to register\n * @param props.environment - The environment to use for the Tambo API\n * @param props.tools - The tools to register\n * @returns The TamboProvider component\n */\nexport const TamboProvider: React.FC<\n PropsWithChildren<TamboClientProviderProps & TamboRegistryProviderProps>\n> = ({ children, tamboUrl, apiKey, components, environment, tools }) => {\n // Should only be used in browser\n if (typeof window === \"undefined\") {\n console.error(\"TamboProvider must be used within a browser\");\n }\n\n return (\n <TamboClientProvider\n tamboUrl={tamboUrl}\n apiKey={apiKey}\n environment={environment}\n >\n <TamboRegistryProvider components={components} tools={tools}>\n <TamboThreadProvider>\n <TamboComponentProvider>\n <TamboCompositeProvider>{children}</TamboCompositeProvider>\n </TamboComponentProvider>\n </TamboThreadProvider>\n </TamboRegistryProvider>\n </TamboClientProvider>\n );\n};\nexport type TamboContextProps = TamboClientContextProps &\n TamboThreadContextProps &\n TamboComponentContextProps;\n\nexport const TamboContext = createContext<TamboContextProps>(\n {} as TamboContextProps,\n);\n\n/**\n * TamboCompositeProvider is a provider that combines the TamboClient,\n * TamboThread, and TamboComponent providers\n * @param props - The props for the TamboCompositeProvider\n * @param props.children - The children to wrap\n * @returns The wrapped component\n */\nconst TamboCompositeProvider: React.FC<PropsWithChildren> = ({ children }) => {\n const threads = useTamboThread();\n const client = useTamboClient();\n const queryClient = useTamboQueryClient();\n const componentRegistry = useTamboComponent();\n\n return (\n <TamboContext.Provider\n value={{\n client,\n queryClient,\n ...componentRegistry,\n ...threads,\n }}\n >\n {children}\n </TamboContext.Provider>\n );\n};\n\n/**\n * The useTambo hook provides access to the Tambo API. This is the primary entrypoint\n * for the Tambo React SDK.\n *\n * This includes the TamboAI client, the component registry, and the current thread context.\n * @returns The Tambo API\n */\nexport const useTambo = () => {\n return useContext(TamboContext);\n};\n"]}
|
|
@@ -12,6 +12,8 @@ export interface TamboRegistryContext {
|
|
|
12
12
|
export interface TamboRegistryProviderProps {
|
|
13
13
|
/** The components to register */
|
|
14
14
|
components?: TamboComponent[];
|
|
15
|
+
/** The tools to register */
|
|
16
|
+
tools?: TamboTool[];
|
|
15
17
|
}
|
|
16
18
|
/**
|
|
17
19
|
* The TamboRegistryProvider is a React provider that provides a component
|
|
@@ -19,6 +21,7 @@ export interface TamboRegistryProviderProps {
|
|
|
19
21
|
* @param props - The props for the TamboRegistryProvider
|
|
20
22
|
* @param props.children - The children to wrap
|
|
21
23
|
* @param props.components - The components to register
|
|
24
|
+
* @param props.tools - The tools to register
|
|
22
25
|
* @returns The TamboRegistryProvider component
|
|
23
26
|
*/
|
|
24
27
|
export declare const TamboRegistryProvider: React.FC<PropsWithChildren<TamboRegistryProviderProps>>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tambo-registry-provider.d.ts","sourceRoot":"","sources":["../../src/providers/tambo-registry-provider.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,EAEZ,iBAAiB,EAKlB,MAAM,OAAO,CAAC;AAGf,OAAO,EACL,iBAAiB,EACjB,cAAc,EACd,SAAS,EACV,MAAM,6BAA6B,CAAC;AAErC,MAAM,WAAW,oBAAoB;IACnC,aAAa,EAAE,iBAAiB,CAAC;IACjC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;IACxC,yBAAyB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IACpD,iBAAiB,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;IACrD,YAAY,EAAE,CAAC,IAAI,EAAE,SAAS,KAAK,IAAI,CAAC;IACxC,aAAa,EAAE,CAAC,KAAK,EAAE,SAAS,EAAE,KAAK,IAAI,CAAC;IAC5C,kBAAkB,EAAE,CAAC,aAAa,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,KAAK,IAAI,CAAC;CACtE;AAwBD,MAAM,WAAW,0BAA0B;IACzC,iCAAiC;IACjC,UAAU,CAAC,EAAE,cAAc,EAAE,CAAC;
|
|
1
|
+
{"version":3,"file":"tambo-registry-provider.d.ts","sourceRoot":"","sources":["../../src/providers/tambo-registry-provider.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,EAEZ,iBAAiB,EAKlB,MAAM,OAAO,CAAC;AAGf,OAAO,EACL,iBAAiB,EACjB,cAAc,EACd,SAAS,EACV,MAAM,6BAA6B,CAAC;AAErC,MAAM,WAAW,oBAAoB;IACnC,aAAa,EAAE,iBAAiB,CAAC;IACjC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;IACxC,yBAAyB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IACpD,iBAAiB,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;IACrD,YAAY,EAAE,CAAC,IAAI,EAAE,SAAS,KAAK,IAAI,CAAC;IACxC,aAAa,EAAE,CAAC,KAAK,EAAE,SAAS,EAAE,KAAK,IAAI,CAAC;IAC5C,kBAAkB,EAAE,CAAC,aAAa,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,KAAK,IAAI,CAAC;CACtE;AAwBD,MAAM,WAAW,0BAA0B;IACzC,iCAAiC;IACjC,UAAU,CAAC,EAAE,cAAc,EAAE,CAAC;IAC9B,4BAA4B;IAC5B,KAAK,CAAC,EAAE,SAAS,EAAE,CAAC;CACrB;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,qBAAqB,EAAE,KAAK,CAAC,EAAE,CAC1C,iBAAiB,CAAC,0BAA0B,CAAC,CAiI9C,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,4BAE5B,CAAC"}
|
|
@@ -68,9 +68,10 @@ const TamboRegistryContext = (0, react_1.createContext)({
|
|
|
68
68
|
* @param props - The props for the TamboRegistryProvider
|
|
69
69
|
* @param props.children - The children to wrap
|
|
70
70
|
* @param props.components - The components to register
|
|
71
|
+
* @param props.tools - The tools to register
|
|
71
72
|
* @returns The TamboRegistryProvider component
|
|
72
73
|
*/
|
|
73
|
-
const TamboRegistryProvider = ({ children, components: userComponents }) => {
|
|
74
|
+
const TamboRegistryProvider = ({ children, components: userComponents, tools: userTools }) => {
|
|
74
75
|
const [componentList, setComponentList] = (0, react_1.useState)({});
|
|
75
76
|
const [toolRegistry, setToolRegistry] = (0, react_1.useState)({});
|
|
76
77
|
const [componentToolAssociations, setComponentToolAssociations] = (0, react_1.useState)({});
|
|
@@ -140,6 +141,11 @@ const TamboRegistryProvider = ({ children, components: userComponents }) => {
|
|
|
140
141
|
});
|
|
141
142
|
}
|
|
142
143
|
}, [registerComponent, userComponents]);
|
|
144
|
+
(0, react_1.useEffect)(() => {
|
|
145
|
+
if (userTools) {
|
|
146
|
+
registerTools(userTools, false);
|
|
147
|
+
}
|
|
148
|
+
}, [registerTools, userTools]);
|
|
143
149
|
const value = {
|
|
144
150
|
componentList,
|
|
145
151
|
toolRegistry,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tambo-registry-provider.js","sourceRoot":"","sources":["../../src/providers/tambo-registry-provider.tsx"],"names":[],"mappings":";AAAA,YAAY,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACb,+CAOe;AACf,6BAAgC;AAChC,4EAAiD;AAiBjD,MAAM,oBAAoB,GAAG,IAAA,qBAAa,EAAuB;IAC/D,aAAa,EAAE,EAAE;IACjB,YAAY,EAAE,EAAE;IAChB,yBAAyB,EAAE,EAAE;IAC7B;;OAEG;IACH,iBAAiB,EAAE,GAAG,EAAE,GAAE,CAAC;IAC3B;;OAEG;IACH,YAAY,EAAE,GAAG,EAAE,GAAE,CAAC;IACtB;;OAEG;IACH,aAAa,EAAE,GAAG,EAAE,GAAE,CAAC;IACvB;;OAEG;IACH,kBAAkB,EAAE,GAAG,EAAE,GAAE,CAAC;CAC7B,CAAC,CAAC;AAOH;;;;;;;GAOG;AACI,MAAM,qBAAqB,GAE9B,CAAC,EAAE,QAAQ,EAAE,UAAU,EAAE,cAAc,EAAE,EAAE,EAAE;IAC/C,MAAM,CAAC,aAAa,EAAE,gBAAgB,CAAC,GAAG,IAAA,gBAAQ,EAAoB,EAAE,CAAC,CAAC;IAC1E,MAAM,CAAC,YAAY,EAAE,eAAe,CAAC,GAAG,IAAA,gBAAQ,EAC9C,EAAE,CACH,CAAC;IACF,MAAM,CAAC,yBAAyB,EAAE,4BAA4B,CAAC,GAAG,IAAA,gBAAQ,EAExE,EAAE,CAAC,CAAC;IAEN,MAAM,YAAY,GAAG,IAAA,mBAAW,EAC9B,CAAC,IAAe,EAAE,eAAe,GAAG,IAAI,EAAE,EAAE;QAC1C,eAAe,CAAC,CAAC,IAAI,EAAE,EAAE;YACvB,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,eAAe,EAAE,CAAC;gBACvC,OAAO,CAAC,IAAI,CAAC,oBA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;;GAIG;AACH,SAAS,WAAW,CAAC,GAAY;IAC/B,IAAI,GAAG,YAAY,eAAS,EAAE,CAAC;QAC7B,OAAO,IAAI,CAAC;IACd,CAAC;IACD,6CAA6C;IAC7C,OAAO,CACL,OAAO,GAAG,KAAK,QAAQ;QACvB,GAAG,KAAK,IAAI;QACZ,OAAQ,GAAW,CAAC,SAAS,KAAK,UAAU;QAC5C,OAAQ,GAAW,CAAC,IAAI,KAAK,QAAQ,CACtC,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\nimport React, {\n createContext,\n PropsWithChildren,\n useCallback,\n useContext,\n useEffect,\n useState,\n} from \"react\";\nimport { ZodSchema } from \"zod\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\nimport {\n ComponentRegistry,\n TamboComponent,\n TamboTool,\n} from \"../model/component-metadata\";\n\nexport interface TamboRegistryContext {\n componentList: ComponentRegistry;\n toolRegistry: Record<string, TamboTool>;\n componentToolAssociations: Record<string, string[]>;\n registerComponent: (options: TamboComponent) => void;\n registerTool: (tool: TamboTool) => void;\n registerTools: (tools: TamboTool[]) => void;\n addToolAssociation: (componentName: string, tool: TamboTool) => void;\n}\n\nconst TamboRegistryContext = createContext<TamboRegistryContext>({\n componentList: {},\n toolRegistry: {},\n componentToolAssociations: {},\n /**\n *\n */\n registerComponent: () => {},\n /**\n *\n */\n registerTool: () => {},\n /**\n *\n */\n registerTools: () => {},\n /**\n *\n */\n addToolAssociation: () => {},\n});\n\nexport interface TamboRegistryProviderProps {\n /** The components to register */\n components?: TamboComponent[];\n}\n\n/**\n * The TamboRegistryProvider is a React provider that provides a component\n * registry to the descendants of the provider.\n * @param props - The props for the TamboRegistryProvider\n * @param props.children - The children to wrap\n * @param props.components - The components to register\n * @returns The TamboRegistryProvider component\n */\nexport const TamboRegistryProvider: React.FC<\n PropsWithChildren<TamboRegistryProviderProps>\n> = ({ children, components: userComponents }) => {\n const [componentList, setComponentList] = useState<ComponentRegistry>({});\n const [toolRegistry, setToolRegistry] = useState<Record<string, TamboTool>>(\n {},\n );\n const [componentToolAssociations, setComponentToolAssociations] = useState<\n Record<string, string[]>\n >({});\n\n const registerTool = useCallback(\n (tool: TamboTool, warnOnOverwrite = true) => {\n setToolRegistry((prev) => {\n if (prev[tool.name] && warnOnOverwrite) {\n console.warn(`Overwriting tool ${tool.name}`);\n }\n return {\n ...prev,\n [tool.name]: tool,\n };\n });\n },\n [],\n );\n\n const registerTools = useCallback(\n (tools: TamboTool[], warnOnOverwrite = true) => {\n tools.forEach((tool) => registerTool(tool, warnOnOverwrite));\n },\n [registerTool],\n );\n\n const addToolAssociation = useCallback(\n (componentName: string, tool: TamboTool) => {\n if (!componentList[componentName]) {\n throw new Error(`Component ${componentName} not found in registry`);\n }\n setComponentToolAssociations((prev) => ({\n ...prev,\n [componentName]: [...(prev[componentName] || []), tool.name],\n }));\n },\n [componentList],\n );\n\n const registerComponent = useCallback(\n (options: TamboComponent, warnOnOverwrite = true) => {\n const {\n name,\n description,\n component,\n propsSchema,\n propsDefinition,\n loadingComponent,\n associatedTools,\n } = options;\n\n // Validate that at least one props definition is provided\n if (!propsSchema && !propsDefinition) {\n throw new Error(\n `Component ${name} must have either propsSchema (recommended) or propsDefinition defined`,\n );\n }\n\n // Validate that only one props definition is provided\n if (propsSchema && propsDefinition) {\n throw new Error(\n `Component ${name} cannot have both propsSchema and propsDefinition defined. Use only one. We recommend using propsSchema.`,\n );\n }\n\n // Convert propsSchema to JSON Schema if it exists\n const props = getSerializedProps(propsDefinition, propsSchema, name);\n\n setComponentList((prev) => {\n if (prev[name] && warnOnOverwrite) {\n console.warn(`overwriting component ${name}`);\n }\n return {\n ...prev,\n [name]: {\n component,\n loadingComponent,\n name,\n description,\n props,\n contextTools: [],\n },\n };\n });\n if (associatedTools) {\n registerTools(associatedTools);\n setComponentToolAssociations((prev) => ({\n ...prev,\n [name]: associatedTools.map((tool) => tool.name),\n }));\n }\n },\n [registerTools],\n );\n useEffect(() => {\n if (userComponents) {\n userComponents.forEach((component) => {\n registerComponent(component, false);\n });\n }\n }, [registerComponent, userComponents]);\n\n const value = {\n componentList,\n toolRegistry,\n componentToolAssociations,\n registerComponent,\n registerTool,\n registerTools,\n addToolAssociation,\n };\n\n return (\n <TamboRegistryContext.Provider value={value}>\n {children}\n </TamboRegistryContext.Provider>\n );\n};\n\n/**\n * The useTamboRegistry hook provides access to the component registry\n * to the descendants of the TamboRegistryProvider.\n * @returns The component registry\n */\nexport const useTamboRegistry = () => {\n return useContext(TamboRegistryContext);\n};\nfunction getSerializedProps(\n propsDefinition: any,\n propsSchema: any,\n name: string,\n) {\n if (propsDefinition) {\n console.warn(`propsDefinition is deprecated. Use propsSchema instead.`);\n return propsDefinition;\n }\n\n if (isZodSchema(propsSchema)) {\n try {\n return zodToJsonSchema(propsSchema);\n } catch (error) {\n console.error(\n `Error converting ${name} props schema to JSON Schema:`,\n error,\n );\n }\n }\n // try to roughly detect JSONSchema, should always be an object with a properties key\n if (isJSONSchema(propsSchema)) {\n return propsSchema;\n }\n\n throw new Error(`Invalid props schema for ${name}`);\n}\n\n/**\n * Checks if the propsSchema is a JSON Schema. This is a rough check, and the\n * server will provide the definitive check.\n * @param propsSchema - The props schema to check\n * @returns True if the props schema is a JSON Schema, false otherwise\n */\nfunction isJSONSchema(propsSchema: any) {\n return (\n propsSchema &&\n typeof propsSchema === \"object\" &&\n propsSchema.type === \"object\" &&\n propsSchema.properties\n );\n}\n\n/**\n * Since we require a certain zod version, we need to check if the object is a ZodSchema\n * @param obj - The object to check\n * @returns True if the object is a ZodSchema, false otherwise\n */\nfunction isZodSchema(obj: unknown): obj is ZodSchema {\n if (obj instanceof ZodSchema) {\n return true;\n }\n // try to detect if the object is a ZodSchema\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n typeof (obj as any).safeParse === \"function\" &&\n typeof (obj as any)._def === \"object\"\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"tambo-registry-provider.js","sourceRoot":"","sources":["../../src/providers/tambo-registry-provider.tsx"],"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AAC,IAAI,KAAK,QAAQ;QAC7B,WAAW,CAAC,UAAU,CACvB,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,WAAW,CAAC,GAAY;IAC/B,IAAI,GAAG,YAAY,eAAS,EAAE,CAAC;QAC7B,OAAO,IAAI,CAAC;IACd,CAAC;IACD,6CAA6C;IAC7C,OAAO,CACL,OAAO,GAAG,KAAK,QAAQ;QACvB,GAAG,KAAK,IAAI;QACZ,OAAQ,GAAW,CAAC,SAAS,KAAK,UAAU;QAC5C,OAAQ,GAAW,CAAC,IAAI,KAAK,QAAQ,CACtC,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\nimport React, {\n createContext,\n PropsWithChildren,\n useCallback,\n useContext,\n useEffect,\n useState,\n} from \"react\";\nimport { ZodSchema } from \"zod\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\nimport {\n ComponentRegistry,\n TamboComponent,\n TamboTool,\n} from \"../model/component-metadata\";\n\nexport interface TamboRegistryContext {\n componentList: ComponentRegistry;\n toolRegistry: Record<string, TamboTool>;\n componentToolAssociations: Record<string, string[]>;\n registerComponent: (options: TamboComponent) => void;\n registerTool: (tool: TamboTool) => void;\n registerTools: (tools: TamboTool[]) => void;\n addToolAssociation: (componentName: string, tool: TamboTool) => void;\n}\n\nconst TamboRegistryContext = createContext<TamboRegistryContext>({\n componentList: {},\n toolRegistry: {},\n componentToolAssociations: {},\n /**\n *\n */\n registerComponent: () => {},\n /**\n *\n */\n registerTool: () => {},\n /**\n *\n */\n registerTools: () => {},\n /**\n *\n */\n addToolAssociation: () => {},\n});\n\nexport interface TamboRegistryProviderProps {\n /** The components to register */\n components?: TamboComponent[];\n /** The tools to register */\n tools?: TamboTool[];\n}\n\n/**\n * The TamboRegistryProvider is a React provider that provides a component\n * registry to the descendants of the provider.\n * @param props - The props for the TamboRegistryProvider\n * @param props.children - The children to wrap\n * @param props.components - The components to register\n * @param props.tools - The tools to register\n * @returns The TamboRegistryProvider component\n */\nexport const TamboRegistryProvider: React.FC<\n PropsWithChildren<TamboRegistryProviderProps>\n> = ({ children, components: userComponents, tools: userTools }) => {\n const [componentList, setComponentList] = useState<ComponentRegistry>({});\n const [toolRegistry, setToolRegistry] = useState<Record<string, TamboTool>>(\n {},\n );\n const [componentToolAssociations, setComponentToolAssociations] = useState<\n Record<string, string[]>\n >({});\n\n const registerTool = useCallback(\n (tool: TamboTool, warnOnOverwrite = true) => {\n setToolRegistry((prev) => {\n if (prev[tool.name] && warnOnOverwrite) {\n console.warn(`Overwriting tool ${tool.name}`);\n }\n return {\n ...prev,\n [tool.name]: tool,\n };\n });\n },\n [],\n );\n\n const registerTools = useCallback(\n (tools: TamboTool[], warnOnOverwrite = true) => {\n tools.forEach((tool) => registerTool(tool, warnOnOverwrite));\n },\n [registerTool],\n );\n\n const addToolAssociation = useCallback(\n (componentName: string, tool: TamboTool) => {\n if (!componentList[componentName]) {\n throw new Error(`Component ${componentName} not found in registry`);\n }\n setComponentToolAssociations((prev) => ({\n ...prev,\n [componentName]: [...(prev[componentName] || []), tool.name],\n }));\n },\n [componentList],\n );\n\n const registerComponent = useCallback(\n (options: TamboComponent, warnOnOverwrite = true) => {\n const {\n name,\n description,\n component,\n propsSchema,\n propsDefinition,\n loadingComponent,\n associatedTools,\n } = options;\n\n // Validate that at least one props definition is provided\n if (!propsSchema && !propsDefinition) {\n throw new Error(\n `Component ${name} must have either propsSchema (recommended) or propsDefinition defined`,\n );\n }\n\n // Validate that only one props definition is provided\n if (propsSchema && propsDefinition) {\n throw new Error(\n `Component ${name} cannot have both propsSchema and propsDefinition defined. Use only one. We recommend using propsSchema.`,\n );\n }\n\n // Convert propsSchema to JSON Schema if it exists\n const props = getSerializedProps(propsDefinition, propsSchema, name);\n\n setComponentList((prev) => {\n if (prev[name] && warnOnOverwrite) {\n console.warn(`overwriting component ${name}`);\n }\n return {\n ...prev,\n [name]: {\n component,\n loadingComponent,\n name,\n description,\n props,\n contextTools: [],\n },\n };\n });\n if (associatedTools) {\n registerTools(associatedTools);\n setComponentToolAssociations((prev) => ({\n ...prev,\n [name]: associatedTools.map((tool) => tool.name),\n }));\n }\n },\n [registerTools],\n );\n useEffect(() => {\n if (userComponents) {\n userComponents.forEach((component) => {\n registerComponent(component, false);\n });\n }\n }, [registerComponent, userComponents]);\n\n useEffect(() => {\n if (userTools) {\n registerTools(userTools, false);\n }\n }, [registerTools, userTools]);\n\n const value = {\n componentList,\n toolRegistry,\n componentToolAssociations,\n registerComponent,\n registerTool,\n registerTools,\n addToolAssociation,\n };\n\n return (\n <TamboRegistryContext.Provider value={value}>\n {children}\n </TamboRegistryContext.Provider>\n );\n};\n\n/**\n * The useTamboRegistry hook provides access to the component registry\n * to the descendants of the TamboRegistryProvider.\n * @returns The component registry\n */\nexport const useTamboRegistry = () => {\n return useContext(TamboRegistryContext);\n};\nfunction getSerializedProps(\n propsDefinition: any,\n propsSchema: any,\n name: string,\n) {\n if (propsDefinition) {\n console.warn(`propsDefinition is deprecated. Use propsSchema instead.`);\n return propsDefinition;\n }\n\n if (isZodSchema(propsSchema)) {\n try {\n return zodToJsonSchema(propsSchema);\n } catch (error) {\n console.error(\n `Error converting ${name} props schema to JSON Schema:`,\n error,\n );\n }\n }\n // try to roughly detect JSONSchema, should always be an object with a properties key\n if (isJSONSchema(propsSchema)) {\n return propsSchema;\n }\n\n throw new Error(`Invalid props schema for ${name}`);\n}\n\n/**\n * Checks if the propsSchema is a JSON Schema. This is a rough check, and the\n * server will provide the definitive check.\n * @param propsSchema - The props schema to check\n * @returns True if the props schema is a JSON Schema, false otherwise\n */\nfunction isJSONSchema(propsSchema: any) {\n return (\n propsSchema &&\n typeof propsSchema === \"object\" &&\n propsSchema.type === \"object\" &&\n propsSchema.properties\n );\n}\n\n/**\n * Since we require a certain zod version, we need to check if the object is a ZodSchema\n * @param obj - The object to check\n * @returns True if the object is a ZodSchema, false otherwise\n */\nfunction isZodSchema(obj: unknown): obj is ZodSchema {\n if (obj instanceof ZodSchema) {\n return true;\n }\n // try to detect if the object is a ZodSchema\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n typeof (obj as any).safeParse === \"function\" &&\n typeof (obj as any)._def === \"object\"\n );\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tambo-thread-provider.d.ts","sourceRoot":"","sources":["../../src/providers/tambo-thread-provider.tsx"],"names":[],"mappings":"AACA,OAAO,OAA0B,MAAM,0BAA0B,CAAC;AAClE,OAAO,KAAK,EAAE,EAEZ,iBAAiB,EAMlB,MAAM,OAAO,CAAC;AACf,OAAO,EACL,eAAe,EAEf,kBAAkB,EACnB,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAYpD,MAAM,WAAW,uBAAuB;IACtC,yBAAyB;IACzB,MAAM,EAAE,WAAW,CAAC;IACpB,mCAAmC;IACnC,mBAAmB,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;IACjE,yBAAyB;IACzB,cAAc,EAAE,MAAM,IAAI,CAAC;IAC3B,0CAA0C;IAC1C,gBAAgB,EAAE,CAChB,OAAO,EAAE,kBAAkB,EAC3B,YAAY,EAAE,OAAO,KAClB,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC,CAAC;IACnD,6CAA6C;IAC7C,mBAAmB,EAAE,CACnB,EAAE,EAAE,MAAM,EACV,OAAO,EAAE,kBAAkB,EAC3B,YAAY,EAAE,OAAO,KAClB,OAAO,CAAC,IAAI,CAAC,CAAC;IACnB,4CAA4C;IAC5C,UAAU,EAAE,MAAM,CAAC;IACnB,gDAAgD;IAChD,aAAa,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IACvC,2CAA2C;IAC3C,iBAAiB,EAAE,CACjB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE;QACP,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,cAAc,CAAC,EAAE,OAAO,CAAC;QACzB,UAAU,CAAC,EAAE,MAAM,CAAC;KACrB,KACE,OAAO,CAAC,kBAAkB,CAAC,CAAC;IACjC,oFAAoF;IACpF,eAAe,EAAE,eAAe,CAAC;IACjC,6FAA6F;IAC7F,uBAAuB,EAAE,MAAM,CAAC;IAChC,iCAAiC;IACjC,MAAM,EAAE,OAAO,CAAC;CACjB;AAED;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,EAAE,WAOhC,CAAC;AAEF,eAAO,MAAM,kBAAkB,wCA0C7B,CAAC;AAEH;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB,EAAE,KAAK,CAAC,EAAE,CAAC,iBAAiB,
|
|
1
|
+
{"version":3,"file":"tambo-thread-provider.d.ts","sourceRoot":"","sources":["../../src/providers/tambo-thread-provider.tsx"],"names":[],"mappings":"AACA,OAAO,OAA0B,MAAM,0BAA0B,CAAC;AAClE,OAAO,KAAK,EAAE,EAEZ,iBAAiB,EAMlB,MAAM,OAAO,CAAC;AACf,OAAO,EACL,eAAe,EAEf,kBAAkB,EACnB,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAYpD,MAAM,WAAW,uBAAuB;IACtC,yBAAyB;IACzB,MAAM,EAAE,WAAW,CAAC;IACpB,mCAAmC;IACnC,mBAAmB,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;IACjE,yBAAyB;IACzB,cAAc,EAAE,MAAM,IAAI,CAAC;IAC3B,0CAA0C;IAC1C,gBAAgB,EAAE,CAChB,OAAO,EAAE,kBAAkB,EAC3B,YAAY,EAAE,OAAO,KAClB,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC,CAAC;IACnD,6CAA6C;IAC7C,mBAAmB,EAAE,CACnB,EAAE,EAAE,MAAM,EACV,OAAO,EAAE,kBAAkB,EAC3B,YAAY,EAAE,OAAO,KAClB,OAAO,CAAC,IAAI,CAAC,CAAC;IACnB,4CAA4C;IAC5C,UAAU,EAAE,MAAM,CAAC;IACnB,gDAAgD;IAChD,aAAa,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IACvC,2CAA2C;IAC3C,iBAAiB,EAAE,CACjB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE;QACP,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,cAAc,CAAC,EAAE,OAAO,CAAC;QACzB,UAAU,CAAC,EAAE,MAAM,CAAC;KACrB,KACE,OAAO,CAAC,kBAAkB,CAAC,CAAC;IACjC,oFAAoF;IACpF,eAAe,EAAE,eAAe,CAAC;IACjC,6FAA6F;IAC7F,uBAAuB,EAAE,MAAM,CAAC;IAChC,iCAAiC;IACjC,MAAM,EAAE,OAAO,CAAC;CACjB;AAED;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,EAAE,WAOhC,CAAC;AAEF,eAAO,MAAM,kBAAkB,wCA0C7B,CAAC;AAEH;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB,EAAE,KAAK,CAAC,EAAE,CAAC,iBAAiB,CAwe3D,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,cAAc,+BAM1B,CAAC"}
|
|
@@ -172,13 +172,23 @@ const TamboThreadProvider = ({ children, }) => {
|
|
|
172
172
|
createdAt,
|
|
173
173
|
};
|
|
174
174
|
const threadId = message.threadId;
|
|
175
|
+
const messageId = chatMessage.id;
|
|
175
176
|
// optimistically update the thread in the local state
|
|
176
177
|
setThreadMap((prevMap) => {
|
|
177
178
|
if (!threadId) {
|
|
178
179
|
return prevMap;
|
|
179
180
|
}
|
|
180
181
|
const prevMessages = prevMap[threadId]?.messages || [];
|
|
181
|
-
const
|
|
182
|
+
const haveMessage = prevMessages.find((msg) => msg.id === messageId);
|
|
183
|
+
// Update in place if the message already exists
|
|
184
|
+
const updatedMessages = haveMessage
|
|
185
|
+
? prevMessages.map((msg) => {
|
|
186
|
+
if (msg.id === messageId) {
|
|
187
|
+
return chatMessage;
|
|
188
|
+
}
|
|
189
|
+
return msg;
|
|
190
|
+
})
|
|
191
|
+
: [...prevMessages, chatMessage];
|
|
182
192
|
const updatedThreadMap = {
|
|
183
193
|
...prevMap,
|
|
184
194
|
[threadId]: {
|
|
@@ -231,17 +241,6 @@ const TamboThreadProvider = ({ children, }) => {
|
|
|
231
241
|
});
|
|
232
242
|
}
|
|
233
243
|
}, [client.beta.threads.messages]);
|
|
234
|
-
const deleteThreadMessage = (0, react_1.useCallback)((messageId, threadId) => {
|
|
235
|
-
if (!threadMap[threadId])
|
|
236
|
-
return;
|
|
237
|
-
setThreadMap((prevMap) => ({
|
|
238
|
-
...prevMap,
|
|
239
|
-
[threadId]: {
|
|
240
|
-
...prevMap[threadId],
|
|
241
|
-
messages: prevMap[threadId].messages.filter((msg) => msg.id !== messageId),
|
|
242
|
-
},
|
|
243
|
-
}));
|
|
244
|
-
}, [threadMap]);
|
|
245
244
|
const startNewThread = (0, react_1.useCallback)(() => {
|
|
246
245
|
setCurrentThreadId(exports.PLACEHOLDER_THREAD.id);
|
|
247
246
|
setThreadMap((prevMap) => {
|
|
@@ -274,7 +273,7 @@ const TamboThreadProvider = ({ children, }) => {
|
|
|
274
273
|
if (fetch) {
|
|
275
274
|
await fetchThread(threadId);
|
|
276
275
|
}
|
|
277
|
-
}, [fetchThread
|
|
276
|
+
}, [fetchThread]);
|
|
278
277
|
const updateThreadStatus = (0, react_1.useCallback)((threadId, stage, statusMessage) => {
|
|
279
278
|
setThreadMap((prevMap) => {
|
|
280
279
|
const updatedThreadMap = {
|
|
@@ -288,16 +287,11 @@ const TamboThreadProvider = ({ children, }) => {
|
|
|
288
287
|
return updatedThreadMap;
|
|
289
288
|
});
|
|
290
289
|
}, []);
|
|
291
|
-
const handleAdvanceStream = (0, react_1.useCallback)(async (stream, params, threadId
|
|
290
|
+
const handleAdvanceStream = (0, react_1.useCallback)(async (stream, params, threadId) => {
|
|
292
291
|
let finalMessage;
|
|
293
292
|
let hasSetThreadId = false;
|
|
294
|
-
let isFirstChunk = true;
|
|
295
293
|
updateThreadStatus(threadId, generate_component_response_1.GenerationStage.STREAMING_RESPONSE);
|
|
296
294
|
for await (const chunk of stream) {
|
|
297
|
-
if (isFirstChunk && messageIdToRemove) {
|
|
298
|
-
deleteThreadMessage(messageIdToRemove, threadId);
|
|
299
|
-
}
|
|
300
|
-
isFirstChunk = false;
|
|
301
295
|
if (chunk.responseMessageDto.toolCallRequest) {
|
|
302
296
|
updateThreadStatus(chunk.responseMessageDto.threadId, generate_component_response_1.GenerationStage.FETCHING_CONTEXT);
|
|
303
297
|
const toolCallResponse = await (0, tool_caller_1.handleToolCall)(chunk.responseMessageDto, toolRegistry);
|
|
@@ -323,20 +317,26 @@ const TamboThreadProvider = ({ children, }) => {
|
|
|
323
317
|
chunk.responseMessageDto.threadId &&
|
|
324
318
|
chunk.responseMessageDto.threadId !== currentThread?.id) {
|
|
325
319
|
hasSetThreadId = true;
|
|
326
|
-
switchCurrentThread(chunk.responseMessageDto.threadId, false);
|
|
320
|
+
await switchCurrentThread(chunk.responseMessageDto.threadId, false);
|
|
327
321
|
}
|
|
328
322
|
if (!finalMessage) {
|
|
329
323
|
finalMessage = chunk.responseMessageDto.component?.componentName
|
|
330
324
|
? (0, generate_component_1.renderComponentIntoMessage)(chunk.responseMessageDto, componentList)
|
|
331
325
|
: chunk.responseMessageDto;
|
|
332
|
-
addThreadMessage(finalMessage, false);
|
|
326
|
+
await addThreadMessage(finalMessage, false);
|
|
333
327
|
}
|
|
334
328
|
else {
|
|
335
|
-
|
|
329
|
+
// if we start getting a new message mid-stream, put the previous one on screen
|
|
330
|
+
const isNewMessage = chunk.responseMessageDto.id !== finalMessage.id;
|
|
336
331
|
finalMessage = chunk.responseMessageDto.component?.componentName
|
|
337
332
|
? (0, generate_component_1.renderComponentIntoMessage)(chunk.responseMessageDto, componentList)
|
|
338
333
|
: chunk.responseMessageDto;
|
|
339
|
-
|
|
334
|
+
if (isNewMessage) {
|
|
335
|
+
await addThreadMessage(finalMessage, false);
|
|
336
|
+
}
|
|
337
|
+
else {
|
|
338
|
+
await updateThreadMessage(finalMessage.id, finalMessage, false);
|
|
339
|
+
}
|
|
340
340
|
}
|
|
341
341
|
}
|
|
342
342
|
}
|
|
@@ -344,7 +344,7 @@ const TamboThreadProvider = ({ children, }) => {
|
|
|
344
344
|
return (finalMessage ?? {
|
|
345
345
|
threadId: "",
|
|
346
346
|
content: [{ type: "text", text: `Error processing stream` }],
|
|
347
|
-
role: "
|
|
347
|
+
role: "assistant",
|
|
348
348
|
createdAt: new Date().toISOString(),
|
|
349
349
|
id: crypto.randomUUID(),
|
|
350
350
|
componentState: {},
|
|
@@ -354,8 +354,6 @@ const TamboThreadProvider = ({ children, }) => {
|
|
|
354
354
|
client,
|
|
355
355
|
componentList,
|
|
356
356
|
currentThread?.id,
|
|
357
|
-
deleteThreadMessage,
|
|
358
|
-
fetchThread,
|
|
359
357
|
switchCurrentThread,
|
|
360
358
|
toolRegistry,
|
|
361
359
|
updateThreadMessage,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tambo-thread-provider.js","sourceRoot":"","sources":["../../src/providers/tambo-thread-provider.tsx"],"names":[],"mappings":";AAAA,YAAY,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACb,6DAAkE;AAClE,+CAQe;AACf,sFAI8C;AAE9C,mEAAwE;AACxE,+CAK0B;AAC1B,qDAAqD;AACrD,mEAAyD;AACzD,uEAA6D;AAyC7D;;;;;;GAMG;AACU,QAAA,kBAAkB,GAAgB;IAC7C,EAAE,EAAE,aAAa;IACjB,QAAQ,EAAE,EAAE;IACZ,SAAS,EAAE,EAAE;IACb,SAAS,EAAE,EAAE;IACb,SAAS,EAAE,EAAE;IACb,QAAQ,EAAE,EAAE;CACb,CAAC;AAEW,QAAA,kBAAkB,GAAG,IAA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AC;QACvC,MAAM,mBAAmB,CAAC,eAAe,CAAC,kBAAkB,CAAC,QAAQ,CAAC,CAAC;QACvE,kBAAkB,CAChB,eAAe,CAAC,kBAAkB,CAAC,QAAQ,EAC3C,6CAAe,CAAC,QAAQ,CACzB,CAAC;QACF,OAAO,YAAY,CAAC;IACtB,CAAC,EACD;QACE,aAAa;QACb,YAAY;QACZ,yBAAyB;QACzB,aAAa,CAAC,EAAE;QAChB,mBAAmB;QACnB,gBAAgB;QAChB,MAAM;QACN,kBAAkB;QAClB,mBAAmB;KACpB,CACF,CAAC;IAEF,OAAO,CACL,8BAAC,0BAAkB,CAAC,QAAQ,IAC1B,KAAK,EAAE;YACL,MAAM,EAAE,aAAa;YACrB,mBAAmB;YACnB,cAAc;YACd,gBAAgB;YAChB,mBAAmB;YACnB,UAAU;YACV,aAAa;YACb,iBAAiB;YACjB,eAAe,EAAE,CAAC,aAAa,EAAE,eAAe;gBAC9C,6CAAe,CAAC,IAAI,CAAoB;YAC1C,uBAAuB,EAAE,aAAa,EAAE,aAAa,IAAI,EAAE;YAC3D,MAAM,EAAE,IAAA,yCAAW,EACjB,CAAC,aAAa,EAAE,eAAe;gBAC7B,6CAAe,CAAC,IAAI,CAAoB,CAC3C;SACF,IAEA,QAAQ,CACmB,CAC/B,CAAC;AACJ,CAAC,CAAC;AAhfW,QAAA,mBAAmB,uBAgf9B;AAEF;;;;GAIG;AACI,MAAM,cAAc,GAAG,GAAG,EAAE;IACjC,MAAM,OAAO,GAAG,IAAA,kBAAU,EAAC,0BAAkB,CAAC,CAAC;IAC/C,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC;IAC9E,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC,CAAC;AANW,QAAA,cAAc,kBAMzB","sourcesContent":["\"use client\";\nimport TamboAI, { advanceStream } from \"@tambo-ai/typescript-sdk\";\nimport React, {\n createContext,\n PropsWithChildren,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from \"react\";\nimport {\n GenerationStage,\n isIdleStage,\n TamboThreadMessage,\n} from \"../model/generate-component-response\";\nimport { TamboThread } from \"../model/tambo-thread\";\nimport { renderComponentIntoMessage } from \"../util/generate-component\";\nimport {\n getAvailableComponents,\n getClientContext,\n getUnassociatedTools,\n mapTamboToolToContextTool,\n} from \"../util/registry\";\nimport { handleToolCall } from \"../util/tool-caller\";\nimport { useTamboClient } from \"./tambo-client-provider\";\nimport { useTamboRegistry } from \"./tambo-registry-provider\";\n\nexport interface TamboThreadContextProps {\n /** The current thread */\n thread: TamboThread;\n /** Switch to a different thread */\n switchCurrentThread: (threadId: string, fetch?: boolean) => void;\n /** Start a new thread */\n startNewThread: () => void;\n /** Add a message to the current thread */\n addThreadMessage: (\n message: TamboThreadMessage,\n sendToServer: boolean,\n ) => Promise<TamboAI.Beta.Threads.ThreadMessage[]>;\n /** Update a message in the current thread */\n updateThreadMessage: (\n id: string,\n message: TamboThreadMessage,\n sendToServer: boolean,\n ) => Promise<void>;\n /** The input value of the current thread */\n inputValue: string;\n /** Set the input value of the current thread */\n setInputValue: (value: string) => void;\n /** Send a message to the current thread */\n sendThreadMessage: (\n message: string,\n options: {\n threadId?: string;\n streamResponse?: boolean;\n contextKey?: string;\n },\n ) => Promise<TamboThreadMessage>;\n /** The generation stage of the current thread - updated as the thread progresses */\n generationStage: GenerationStage;\n /** The generation status message of the current thread - updated as the thread progresses */\n generationStatusMessage: string;\n /** Whether the thread is idle */\n isIdle: boolean;\n}\n\n/**\n * This is a stub entry for when the thread is not yet created, the first time\n * the user sends a message\n *\n * Note that the consumer needs to be careful never to send `PLACEHOLDER_THREAD.id` to the server,\n * as this doesn't really exist on the server side.\n */\nexport const PLACEHOLDER_THREAD: TamboThread = {\n id: \"placeholder\",\n messages: [],\n createdAt: \"\",\n projectId: \"\",\n updatedAt: \"\",\n metadata: {},\n};\n\nexport const TamboThreadContext = createContext<TamboThreadContextProps>({\n thread: PLACEHOLDER_THREAD,\n /**\n *\n */\n switchCurrentThread: () => {\n throw new Error(\"switchCurrentThread not implemented\");\n },\n /**\n *\n */\n startNewThread: () => {\n throw new Error(\"startNewThread not implemented\");\n },\n /**\n *\n */\n addThreadMessage: () => {\n throw new Error(\"updateThreadMessageHistory not implemented\");\n },\n inputValue: \"\",\n /**\n *\n */\n setInputValue: () => {\n throw new Error(\"setInputValue not implemented\");\n },\n /**\n *\n */\n updateThreadMessage: () => {\n throw new Error(\"updateThreadMessage not implemented\");\n },\n /**\n *\n */\n sendThreadMessage: () => {\n throw new Error(\"advance not implemented\");\n },\n generationStage: GenerationStage.IDLE,\n generationStatusMessage: \"\",\n isIdle: true,\n});\n\n/**\n * The TamboThreadProvider is a React provider that provides a thread context\n * to the descendants of the provider.\n * @param props - The props for the TamboThreadProvider\n * @param props.children - The children to wrap\n * @returns The TamboThreadProvider component\n */\nexport const TamboThreadProvider: React.FC<PropsWithChildren> = ({\n children,\n}) => {\n const [threadMap, setThreadMap] = useState<Record<string, TamboThread>>({\n [PLACEHOLDER_THREAD.id]: PLACEHOLDER_THREAD,\n });\n const client = useTamboClient();\n const { componentList, toolRegistry, componentToolAssociations } =\n useTamboRegistry();\n const [inputValue, setInputValue] = useState(\"\");\n\n const [currentThreadId, setCurrentThreadId] = useState<string>(\n PLACEHOLDER_THREAD.id,\n );\n const currentThread: TamboThread | undefined = threadMap[currentThreadId];\n\n // Use existing messages from the current thread to avoid re-generating any components\n const currentMessageCache = useMemo(() => {\n const messageCache = new Map<string, TamboThreadMessage>();\n if (currentThread) {\n for (const message of currentThread.messages) {\n messageCache.set(message.id, message);\n }\n }\n return messageCache;\n }, [currentThread]);\n\n const fetchThread = useCallback(\n async (threadId: string) => {\n const thread = await client.beta.threads.retrieve(threadId);\n const threadWithRenderedComponents = {\n ...thread,\n messages: thread.messages.map((message) => {\n if (currentMessageCache.has(message.id)) {\n const renderedMessage = currentMessageCache.get(message.id);\n return {\n ...renderedMessage,\n ...message,\n };\n }\n if (message.component?.componentName) {\n const messageWithComponent = renderComponentIntoMessage(\n message,\n componentList,\n );\n return messageWithComponent;\n }\n return message;\n }),\n };\n\n setThreadMap((prevMap) => {\n const updatedThreadMap = {\n ...prevMap,\n [threadId]: threadWithRenderedComponents,\n };\n return updatedThreadMap;\n });\n },\n [client.beta.threads, componentList, currentMessageCache],\n );\n\n useEffect(() => {\n if (\n currentThreadId &&\n currentThreadId !== PLACEHOLDER_THREAD.id &&\n !threadMap[currentThreadId]\n ) {\n fetchThread(currentThreadId);\n }\n }, [currentThreadId, fetchThread, threadMap]);\n\n const addThreadMessage = useCallback(\n async (\n message: TamboThreadMessage,\n sendToServer = true,\n createdAt: string = new Date().toISOString(),\n ) => {\n if (!currentThread) {\n console.warn(\"Cannot add messages if we do not have a current thread\");\n return [];\n }\n const chatMessage: TamboThreadMessage & {\n additionalContext?: string;\n } = {\n ...message,\n additionalContext:\n message.role === \"user\" ? getClientContext() : undefined,\n createdAt,\n };\n const threadId = message.threadId;\n // optimistically update the thread in the local state\n setThreadMap((prevMap) => {\n if (!threadId) {\n return prevMap;\n }\n const prevMessages = prevMap[threadId]?.messages || [];\n const updatedMessages = [...prevMessages, chatMessage];\n\n const updatedThreadMap = {\n ...prevMap,\n [threadId]: {\n ...prevMap[threadId],\n messages: updatedMessages,\n },\n };\n return updatedThreadMap;\n });\n\n if (sendToServer) {\n // TODO: if this fails, we need to revert the local state update\n await client.beta.threads.messages.create(message.threadId, {\n content: message.content,\n role: message.role,\n // additionalContext: chatMessage.additionalContext,\n });\n }\n return threadMap[threadId]?.messages || [];\n },\n [client.beta.threads.messages, currentThread, threadMap],\n );\n\n const updateThreadMessage = useCallback(\n async (\n id: string,\n message: TamboThreadMessage,\n sendToServer = true,\n createdAt: string = new Date().toISOString(),\n ) => {\n const chatMessage: TamboThreadMessage = {\n ...message,\n createdAt,\n };\n\n setThreadMap((prevMap) => {\n if (!message.threadId) {\n return prevMap;\n }\n const prevMessages = prevMap[message.threadId]?.messages || [];\n const updatedMessages = prevMessages.map((msg) => {\n if (msg.id === id) {\n return chatMessage;\n }\n return msg;\n });\n return {\n ...prevMap,\n [message.threadId]: {\n ...prevMap[message.threadId],\n messages: updatedMessages,\n },\n };\n });\n if (sendToServer) {\n // TODO: if this fails, we need to revert the local state update\n await client.beta.threads.messages.create(message.threadId, {\n content: message.content,\n role: message.role,\n // additionalContext: chatMessage.additionalContext,\n });\n }\n },\n [client.beta.threads.messages],\n );\n\n const deleteThreadMessage = useCallback(\n (messageId: string, threadId: string) => {\n if (!threadMap[threadId]) return;\n\n setThreadMap((prevMap) => ({\n ...prevMap,\n [threadId]: {\n ...prevMap[threadId],\n messages: prevMap[threadId].messages.filter(\n (msg) => msg.id !== messageId,\n ),\n },\n }));\n },\n [threadMap],\n );\n\n const startNewThread = useCallback(() => {\n setCurrentThreadId(PLACEHOLDER_THREAD.id);\n setThreadMap((prevMap) => {\n return {\n ...prevMap,\n [PLACEHOLDER_THREAD.id]: PLACEHOLDER_THREAD,\n };\n });\n }, []);\n\n const switchCurrentThread = useCallback(\n async (threadId: string, fetch = true) => {\n if (threadId === PLACEHOLDER_THREAD.id) {\n console.warn(\"Switching to placeholder thread, may be a bug.\");\n return;\n }\n setCurrentThreadId(threadId);\n setThreadMap((prevMap) => {\n if (prevMap[threadId]) {\n return prevMap;\n }\n // If this is a new thread, add placeholder thread messages to the thread\n const updatedThreadMap = {\n ...prevMap,\n [threadId]: {\n ...prevMap[PLACEHOLDER_THREAD.id],\n id: threadId,\n },\n };\n return updatedThreadMap;\n });\n if (fetch) {\n await fetchThread(threadId);\n }\n },\n [fetchThread, threadMap],\n );\n\n const updateThreadStatus = useCallback(\n (threadId: string, stage: GenerationStage, statusMessage?: string) => {\n setThreadMap((prevMap) => {\n const updatedThreadMap = {\n ...prevMap,\n [threadId]: {\n ...prevMap[threadId],\n generationStage: stage,\n statusMessage: statusMessage,\n },\n };\n return updatedThreadMap;\n });\n },\n [],\n );\n\n const handleAdvanceStream = useCallback(\n async (\n stream: AsyncIterable<TamboAI.Beta.Threads.ThreadAdvanceResponse>,\n params: TamboAI.Beta.Threads.ThreadAdvanceParams,\n threadId: string,\n messageIdToRemove?: string,\n ): Promise<TamboThreadMessage> => {\n let finalMessage: TamboThreadMessage | undefined;\n let hasSetThreadId = false;\n let isFirstChunk = true;\n updateThreadStatus(threadId, GenerationStage.STREAMING_RESPONSE);\n\n for await (const chunk of stream) {\n if (isFirstChunk && messageIdToRemove) {\n deleteThreadMessage(messageIdToRemove, threadId);\n }\n isFirstChunk = false;\n\n if (chunk.responseMessageDto.toolCallRequest) {\n updateThreadStatus(\n chunk.responseMessageDto.threadId,\n GenerationStage.FETCHING_CONTEXT,\n );\n const toolCallResponse = await handleToolCall(\n chunk.responseMessageDto,\n toolRegistry,\n );\n const toolCallResponseString =\n typeof toolCallResponse === \"string\"\n ? toolCallResponse\n : JSON.stringify(toolCallResponse);\n const toolCallResponseParams: TamboAI.Beta.Threads.ThreadAdvanceParams =\n {\n ...params,\n messageToAppend: {\n content: [{ type: \"text\", text: toolCallResponseString }],\n role: \"tool\",\n actionType: \"tool_response\",\n component: chunk.responseMessageDto.component,\n tool_call_id: chunk.responseMessageDto.tool_call_id,\n },\n };\n updateThreadStatus(\n chunk.responseMessageDto.threadId,\n GenerationStage.STREAMING_RESPONSE,\n );\n const toolCallResponseStream = await advanceStream(\n client,\n toolCallResponseParams,\n chunk.responseMessageDto.threadId,\n );\n\n return await handleAdvanceStream(\n toolCallResponseStream,\n toolCallResponseParams,\n chunk.responseMessageDto.threadId,\n );\n } else {\n if (\n !hasSetThreadId &&\n chunk.responseMessageDto.threadId &&\n chunk.responseMessageDto.threadId !== currentThread?.id\n ) {\n hasSetThreadId = true;\n switchCurrentThread(chunk.responseMessageDto.threadId, false);\n }\n\n if (!finalMessage) {\n finalMessage = chunk.responseMessageDto.component?.componentName\n ? renderComponentIntoMessage(\n chunk.responseMessageDto,\n componentList,\n )\n : chunk.responseMessageDto;\n addThreadMessage(finalMessage, false);\n } else {\n const previousId = finalMessage.id;\n finalMessage = chunk.responseMessageDto.component?.componentName\n ? renderComponentIntoMessage(\n chunk.responseMessageDto,\n componentList,\n )\n : chunk.responseMessageDto;\n updateThreadMessage(previousId, finalMessage, false);\n }\n }\n }\n\n updateThreadStatus(\n finalMessage?.threadId ?? threadId,\n GenerationStage.COMPLETE,\n );\n return (\n finalMessage ?? {\n threadId: \"\",\n content: [{ type: \"text\", text: `Error processing stream` }],\n role: \"hydra\",\n createdAt: new Date().toISOString(),\n id: crypto.randomUUID(),\n componentState: {},\n }\n );\n },\n [\n addThreadMessage,\n client,\n componentList,\n currentThread?.id,\n deleteThreadMessage,\n fetchThread,\n switchCurrentThread,\n toolRegistry,\n updateThreadMessage,\n updateThreadStatus,\n ],\n );\n\n const sendThreadMessage = useCallback(\n async (\n message: string,\n options: {\n threadId?: string;\n streamResponse?: boolean;\n contextKey?: string;\n } = { threadId: PLACEHOLDER_THREAD.id },\n ): Promise<TamboThreadMessage> => {\n const { threadId = currentThread.id, streamResponse } = options;\n updateThreadStatus(threadId, GenerationStage.CHOOSING_COMPONENT);\n\n addThreadMessage(\n {\n content: [{ type: \"text\", text: message }],\n renderedComponent: null,\n role: \"user\",\n threadId: threadId,\n id: crypto.randomUUID(),\n createdAt: new Date().toISOString(),\n componentState: {},\n },\n false,\n );\n\n const availableComponents = getAvailableComponents(\n componentList,\n toolRegistry,\n componentToolAssociations,\n );\n const unassociatedTools = getUnassociatedTools(\n toolRegistry,\n componentToolAssociations,\n );\n const params: TamboAI.Beta.Threads.ThreadAdvanceParams = {\n messageToAppend: {\n content: [{ type: \"text\", text: message }],\n role: \"user\",\n },\n contextKey: options.contextKey,\n availableComponents: availableComponents,\n clientTools: unassociatedTools.map((tool) =>\n mapTamboToolToContextTool(tool),\n ),\n };\n\n if (streamResponse) {\n const advanceStreamResponse = await advanceStream(\n client,\n params,\n threadId === PLACEHOLDER_THREAD.id ? undefined : threadId,\n );\n return await handleAdvanceStream(\n advanceStreamResponse,\n params,\n threadId,\n );\n }\n let advanceResponse = await (threadId === PLACEHOLDER_THREAD.id\n ? client.beta.threads.advance(params)\n : client.beta.threads.advanceById(threadId, params));\n\n //handle tool calls\n while (advanceResponse.responseMessageDto.toolCallRequest) {\n updateThreadStatus(threadId, GenerationStage.FETCHING_CONTEXT);\n const toolCallResponse = await handleToolCall(\n advanceResponse.responseMessageDto,\n toolRegistry,\n );\n const toolResponseString =\n typeof toolCallResponse === \"string\"\n ? toolCallResponse\n : JSON.stringify(toolCallResponse);\n const toolCallResponseParams: TamboAI.Beta.Threads.ThreadAdvanceParams =\n {\n ...params,\n messageToAppend: {\n ...params.messageToAppend,\n content: [{ type: \"text\", text: toolResponseString }],\n role: \"tool\",\n actionType: \"tool_response\",\n component: advanceResponse.responseMessageDto.component,\n tool_call_id: advanceResponse.responseMessageDto.tool_call_id,\n },\n };\n updateThreadStatus(threadId, GenerationStage.HYDRATING_COMPONENT);\n advanceResponse = await client.beta.threads.advanceById(\n advanceResponse.responseMessageDto.threadId,\n toolCallResponseParams,\n );\n }\n\n const finalMessage = advanceResponse.responseMessageDto.component\n ?.componentName\n ? renderComponentIntoMessage(\n advanceResponse.responseMessageDto,\n componentList,\n )\n : advanceResponse.responseMessageDto;\n await switchCurrentThread(advanceResponse.responseMessageDto.threadId);\n updateThreadStatus(\n advanceResponse.responseMessageDto.threadId,\n GenerationStage.COMPLETE,\n );\n return finalMessage;\n },\n [\n componentList,\n toolRegistry,\n componentToolAssociations,\n currentThread.id,\n switchCurrentThread,\n addThreadMessage,\n client,\n updateThreadStatus,\n handleAdvanceStream,\n ],\n );\n\n return (\n <TamboThreadContext.Provider\n value={{\n thread: currentThread,\n switchCurrentThread,\n startNewThread,\n addThreadMessage,\n updateThreadMessage,\n inputValue,\n setInputValue,\n sendThreadMessage,\n generationStage: (currentThread?.generationStage ??\n GenerationStage.IDLE) as GenerationStage,\n generationStatusMessage: currentThread?.statusMessage ?? \"\",\n isIdle: isIdleStage(\n (currentThread?.generationStage ??\n GenerationStage.IDLE) as GenerationStage,\n ),\n }}\n >\n {children}\n </TamboThreadContext.Provider>\n );\n};\n\n/**\n * The useTamboThread hook provides access to the current thread context\n * to the descendants of the TamboThreadProvider.\n * @returns All state and actions for the current thread\n */\nexport const useTamboThread = () => {\n const context = useContext(TamboThreadContext);\n if (context === undefined) {\n throw new Error(\"useTamboThread must be used within a TamboThreadProvider\");\n }\n return context;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"tambo-thread-provider.js","sourceRoot":"","sources":["../../src/providers/tambo-thread-provider.tsx"],"names":[],"mappings":";AAAA,YAAY,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACb,6DAAkE;AAClE,+CAQe;AACf,sFAI8C;AAE9C,mEAAwE;AACxE,+CAK0B;AAC1B,qDAAqD;AACrD,mEAAyD;AACzD,uEAA6D;AAyC7D;;;;;;GAMG;AACU,QAAA,kBAAkB,GAAgB;IAC7C,EAAE,EAAE,aAAa;IACjB,QAAQ,EAAE,EAAE;IACZ,SAAS,EAAE,EAAE;IACb,SAAS,EAAE,EAAE;IACb,SAAS,EAAE,EAAE;IACb,QAAQ,EAAE,EAAE;CACb,CAAC;AAEW,QAAA,kBAAkB,GAAG,IAAA,qBAAa,EAA0B;IACvE,MAAM,EAAE,0BAAkB;IAC1B;;OAEG;IACH,mBAAmB,EAAE,GAAG,EAAE;QACxB,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;IACzD,CAAC;IACD;;OAEG;IACH,cAAc,EAAE,GAAG,EAAE;QACnB,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;IACpD,CAAC;IACD;;OAEG;IACH,gBAAgB,EAAE,GAAG,EAAE;QACrB,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;IAChE,CAAC;IACD,UAAU,EAAE,EAAE;IACd;;OAEG;IACH,aAAa,EAAE,GAAG,EAAE;QAClB,MAAM,IAAI,KAAK,CAAC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AC,aAAa,EAAE,eAAe;gBAC9C,6CAAe,CAAC,IAAI,CAAoB;YAC1C,uBAAuB,EAAE,aAAa,EAAE,aAAa,IAAI,EAAE;YAC3D,MAAM,EAAE,IAAA,yCAAW,EACjB,CAAC,aAAa,EAAE,eAAe;gBAC7B,6CAAe,CAAC,IAAI,CAAoB,CAC3C;SACF,IAEA,QAAQ,CACmB,CAC/B,CAAC;AACJ,CAAC,CAAC;AAxeW,QAAA,mBAAmB,uBAwe9B;AAEF;;;;GAIG;AACI,MAAM,cAAc,GAAG,GAAG,EAAE;IACjC,MAAM,OAAO,GAAG,IAAA,kBAAU,EAAC,0BAAkB,CAAC,CAAC;IAC/C,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC;IAC9E,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC,CAAC;AANW,QAAA,cAAc,kBAMzB","sourcesContent":["\"use client\";\nimport TamboAI, { advanceStream } from \"@tambo-ai/typescript-sdk\";\nimport React, {\n createContext,\n PropsWithChildren,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from \"react\";\nimport {\n GenerationStage,\n isIdleStage,\n TamboThreadMessage,\n} from \"../model/generate-component-response\";\nimport { TamboThread } from \"../model/tambo-thread\";\nimport { renderComponentIntoMessage } from \"../util/generate-component\";\nimport {\n getAvailableComponents,\n getClientContext,\n getUnassociatedTools,\n mapTamboToolToContextTool,\n} from \"../util/registry\";\nimport { handleToolCall } from \"../util/tool-caller\";\nimport { useTamboClient } from \"./tambo-client-provider\";\nimport { useTamboRegistry } from \"./tambo-registry-provider\";\n\nexport interface TamboThreadContextProps {\n /** The current thread */\n thread: TamboThread;\n /** Switch to a different thread */\n switchCurrentThread: (threadId: string, fetch?: boolean) => void;\n /** Start a new thread */\n startNewThread: () => void;\n /** Add a message to the current thread */\n addThreadMessage: (\n message: TamboThreadMessage,\n sendToServer: boolean,\n ) => Promise<TamboAI.Beta.Threads.ThreadMessage[]>;\n /** Update a message in the current thread */\n updateThreadMessage: (\n id: string,\n message: TamboThreadMessage,\n sendToServer: boolean,\n ) => Promise<void>;\n /** The input value of the current thread */\n inputValue: string;\n /** Set the input value of the current thread */\n setInputValue: (value: string) => void;\n /** Send a message to the current thread */\n sendThreadMessage: (\n message: string,\n options: {\n threadId?: string;\n streamResponse?: boolean;\n contextKey?: string;\n },\n ) => Promise<TamboThreadMessage>;\n /** The generation stage of the current thread - updated as the thread progresses */\n generationStage: GenerationStage;\n /** The generation status message of the current thread - updated as the thread progresses */\n generationStatusMessage: string;\n /** Whether the thread is idle */\n isIdle: boolean;\n}\n\n/**\n * This is a stub entry for when the thread is not yet created, the first time\n * the user sends a message\n *\n * Note that the consumer needs to be careful never to send `PLACEHOLDER_THREAD.id` to the server,\n * as this doesn't really exist on the server side.\n */\nexport const PLACEHOLDER_THREAD: TamboThread = {\n id: \"placeholder\",\n messages: [],\n createdAt: \"\",\n projectId: \"\",\n updatedAt: \"\",\n metadata: {},\n};\n\nexport const TamboThreadContext = createContext<TamboThreadContextProps>({\n thread: PLACEHOLDER_THREAD,\n /**\n *\n */\n switchCurrentThread: () => {\n throw new Error(\"switchCurrentThread not implemented\");\n },\n /**\n *\n */\n startNewThread: () => {\n throw new Error(\"startNewThread not implemented\");\n },\n /**\n *\n */\n addThreadMessage: () => {\n throw new Error(\"updateThreadMessageHistory not implemented\");\n },\n inputValue: \"\",\n /**\n *\n */\n setInputValue: () => {\n throw new Error(\"setInputValue not implemented\");\n },\n /**\n *\n */\n updateThreadMessage: () => {\n throw new Error(\"updateThreadMessage not implemented\");\n },\n /**\n *\n */\n sendThreadMessage: () => {\n throw new Error(\"advance not implemented\");\n },\n generationStage: GenerationStage.IDLE,\n generationStatusMessage: \"\",\n isIdle: true,\n});\n\n/**\n * The TamboThreadProvider is a React provider that provides a thread context\n * to the descendants of the provider.\n * @param props - The props for the TamboThreadProvider\n * @param props.children - The children to wrap\n * @returns The TamboThreadProvider component\n */\nexport const TamboThreadProvider: React.FC<PropsWithChildren> = ({\n children,\n}) => {\n const [threadMap, setThreadMap] = useState<Record<string, TamboThread>>({\n [PLACEHOLDER_THREAD.id]: PLACEHOLDER_THREAD,\n });\n const client = useTamboClient();\n const { componentList, toolRegistry, componentToolAssociations } =\n useTamboRegistry();\n const [inputValue, setInputValue] = useState(\"\");\n\n const [currentThreadId, setCurrentThreadId] = useState<string>(\n PLACEHOLDER_THREAD.id,\n );\n const currentThread: TamboThread | undefined = threadMap[currentThreadId];\n\n // Use existing messages from the current thread to avoid re-generating any components\n const currentMessageCache = useMemo(() => {\n const messageCache = new Map<string, TamboThreadMessage>();\n if (currentThread) {\n for (const message of currentThread.messages) {\n messageCache.set(message.id, message);\n }\n }\n return messageCache;\n }, [currentThread]);\n\n const fetchThread = useCallback(\n async (threadId: string) => {\n const thread = await client.beta.threads.retrieve(threadId);\n const threadWithRenderedComponents = {\n ...thread,\n messages: thread.messages.map((message) => {\n if (currentMessageCache.has(message.id)) {\n const renderedMessage = currentMessageCache.get(message.id);\n return {\n ...renderedMessage,\n ...message,\n };\n }\n if (message.component?.componentName) {\n const messageWithComponent = renderComponentIntoMessage(\n message,\n componentList,\n );\n return messageWithComponent;\n }\n return message;\n }),\n };\n\n setThreadMap((prevMap) => {\n const updatedThreadMap = {\n ...prevMap,\n [threadId]: threadWithRenderedComponents,\n };\n return updatedThreadMap;\n });\n },\n [client.beta.threads, componentList, currentMessageCache],\n );\n\n useEffect(() => {\n if (\n currentThreadId &&\n currentThreadId !== PLACEHOLDER_THREAD.id &&\n !threadMap[currentThreadId]\n ) {\n fetchThread(currentThreadId);\n }\n }, [currentThreadId, fetchThread, threadMap]);\n\n const addThreadMessage = useCallback(\n async (\n message: TamboThreadMessage,\n sendToServer = true,\n createdAt: string = new Date().toISOString(),\n ) => {\n if (!currentThread) {\n console.warn(\"Cannot add messages if we do not have a current thread\");\n return [];\n }\n const chatMessage: TamboThreadMessage & {\n additionalContext?: string;\n } = {\n ...message,\n additionalContext:\n message.role === \"user\" ? getClientContext() : undefined,\n createdAt,\n };\n const threadId = message.threadId;\n const messageId = chatMessage.id;\n // optimistically update the thread in the local state\n setThreadMap((prevMap) => {\n if (!threadId) {\n return prevMap;\n }\n const prevMessages = prevMap[threadId]?.messages || [];\n const haveMessage = prevMessages.find((msg) => msg.id === messageId);\n // Update in place if the message already exists\n const updatedMessages = haveMessage\n ? prevMessages.map((msg) => {\n if (msg.id === messageId) {\n return chatMessage;\n }\n return msg;\n })\n : [...prevMessages, chatMessage];\n\n const updatedThreadMap = {\n ...prevMap,\n [threadId]: {\n ...prevMap[threadId],\n messages: updatedMessages,\n },\n };\n return updatedThreadMap;\n });\n\n if (sendToServer) {\n // TODO: if this fails, we need to revert the local state update\n await client.beta.threads.messages.create(message.threadId, {\n content: message.content,\n role: message.role,\n // additionalContext: chatMessage.additionalContext,\n });\n }\n return threadMap[threadId]?.messages || [];\n },\n [client.beta.threads.messages, currentThread, threadMap],\n );\n\n const updateThreadMessage = useCallback(\n async (\n id: string,\n message: TamboThreadMessage,\n sendToServer = true,\n createdAt: string = new Date().toISOString(),\n ) => {\n const chatMessage: TamboThreadMessage = {\n ...message,\n createdAt,\n };\n\n setThreadMap((prevMap) => {\n if (!message.threadId) {\n return prevMap;\n }\n const prevMessages = prevMap[message.threadId]?.messages || [];\n const updatedMessages = prevMessages.map((msg) => {\n if (msg.id === id) {\n return chatMessage;\n }\n return msg;\n });\n return {\n ...prevMap,\n [message.threadId]: {\n ...prevMap[message.threadId],\n messages: updatedMessages,\n },\n };\n });\n if (sendToServer) {\n // TODO: if this fails, we need to revert the local state update\n await client.beta.threads.messages.create(message.threadId, {\n content: message.content,\n role: message.role,\n // additionalContext: chatMessage.additionalContext,\n });\n }\n },\n [client.beta.threads.messages],\n );\n\n const startNewThread = useCallback(() => {\n setCurrentThreadId(PLACEHOLDER_THREAD.id);\n setThreadMap((prevMap) => {\n return {\n ...prevMap,\n [PLACEHOLDER_THREAD.id]: PLACEHOLDER_THREAD,\n };\n });\n }, []);\n\n const switchCurrentThread = useCallback(\n async (threadId: string, fetch = true) => {\n if (threadId === PLACEHOLDER_THREAD.id) {\n console.warn(\"Switching to placeholder thread, may be a bug.\");\n return;\n }\n setCurrentThreadId(threadId);\n setThreadMap((prevMap) => {\n if (prevMap[threadId]) {\n return prevMap;\n }\n // If this is a new thread, add placeholder thread messages to the thread\n const updatedThreadMap = {\n ...prevMap,\n [threadId]: {\n ...prevMap[PLACEHOLDER_THREAD.id],\n id: threadId,\n },\n };\n return updatedThreadMap;\n });\n if (fetch) {\n await fetchThread(threadId);\n }\n },\n [fetchThread],\n );\n\n const updateThreadStatus = useCallback(\n (threadId: string, stage: GenerationStage, statusMessage?: string) => {\n setThreadMap((prevMap) => {\n const updatedThreadMap = {\n ...prevMap,\n [threadId]: {\n ...prevMap[threadId],\n generationStage: stage,\n statusMessage: statusMessage,\n },\n };\n return updatedThreadMap;\n });\n },\n [],\n );\n\n const handleAdvanceStream = useCallback(\n async (\n stream: AsyncIterable<TamboAI.Beta.Threads.ThreadAdvanceResponse>,\n params: TamboAI.Beta.Threads.ThreadAdvanceParams,\n threadId: string,\n ): Promise<TamboThreadMessage> => {\n let finalMessage: Readonly<TamboThreadMessage> | undefined;\n let hasSetThreadId = false;\n updateThreadStatus(threadId, GenerationStage.STREAMING_RESPONSE);\n\n for await (const chunk of stream) {\n if (chunk.responseMessageDto.toolCallRequest) {\n updateThreadStatus(\n chunk.responseMessageDto.threadId,\n GenerationStage.FETCHING_CONTEXT,\n );\n const toolCallResponse = await handleToolCall(\n chunk.responseMessageDto,\n toolRegistry,\n );\n const toolCallResponseString =\n typeof toolCallResponse === \"string\"\n ? toolCallResponse\n : JSON.stringify(toolCallResponse);\n const toolCallResponseParams: TamboAI.Beta.Threads.ThreadAdvanceParams =\n {\n ...params,\n messageToAppend: {\n content: [{ type: \"text\", text: toolCallResponseString }],\n role: \"tool\",\n actionType: \"tool_response\",\n component: chunk.responseMessageDto.component,\n tool_call_id: chunk.responseMessageDto.tool_call_id,\n },\n };\n updateThreadStatus(\n chunk.responseMessageDto.threadId,\n GenerationStage.STREAMING_RESPONSE,\n );\n const toolCallResponseStream = await advanceStream(\n client,\n toolCallResponseParams,\n chunk.responseMessageDto.threadId,\n );\n\n return await handleAdvanceStream(\n toolCallResponseStream,\n toolCallResponseParams,\n chunk.responseMessageDto.threadId,\n );\n } else {\n if (\n !hasSetThreadId &&\n chunk.responseMessageDto.threadId &&\n chunk.responseMessageDto.threadId !== currentThread?.id\n ) {\n hasSetThreadId = true;\n await switchCurrentThread(chunk.responseMessageDto.threadId, false);\n }\n\n if (!finalMessage) {\n finalMessage = chunk.responseMessageDto.component?.componentName\n ? renderComponentIntoMessage(\n chunk.responseMessageDto,\n componentList,\n )\n : chunk.responseMessageDto;\n await addThreadMessage(finalMessage, false);\n } else {\n // if we start getting a new message mid-stream, put the previous one on screen\n const isNewMessage =\n chunk.responseMessageDto.id !== finalMessage.id;\n\n finalMessage = chunk.responseMessageDto.component?.componentName\n ? renderComponentIntoMessage(\n chunk.responseMessageDto,\n componentList,\n )\n : chunk.responseMessageDto;\n\n if (isNewMessage) {\n await addThreadMessage(finalMessage, false);\n } else {\n await updateThreadMessage(finalMessage.id, finalMessage, false);\n }\n }\n }\n }\n\n updateThreadStatus(\n finalMessage?.threadId ?? threadId,\n GenerationStage.COMPLETE,\n );\n return (\n finalMessage ?? {\n threadId: \"\",\n content: [{ type: \"text\", text: `Error processing stream` }],\n role: \"assistant\",\n createdAt: new Date().toISOString(),\n id: crypto.randomUUID(),\n componentState: {},\n }\n );\n },\n [\n addThreadMessage,\n client,\n componentList,\n currentThread?.id,\n switchCurrentThread,\n toolRegistry,\n updateThreadMessage,\n updateThreadStatus,\n ],\n );\n\n const sendThreadMessage = useCallback(\n async (\n message: string,\n options: {\n threadId?: string;\n streamResponse?: boolean;\n contextKey?: string;\n } = { threadId: PLACEHOLDER_THREAD.id },\n ): Promise<TamboThreadMessage> => {\n const { threadId = currentThread.id, streamResponse } = options;\n updateThreadStatus(threadId, GenerationStage.CHOOSING_COMPONENT);\n\n addThreadMessage(\n {\n content: [{ type: \"text\", text: message }],\n renderedComponent: null,\n role: \"user\",\n threadId: threadId,\n id: crypto.randomUUID(),\n createdAt: new Date().toISOString(),\n componentState: {},\n },\n false,\n );\n\n const availableComponents = getAvailableComponents(\n componentList,\n toolRegistry,\n componentToolAssociations,\n );\n const unassociatedTools = getUnassociatedTools(\n toolRegistry,\n componentToolAssociations,\n );\n const params: TamboAI.Beta.Threads.ThreadAdvanceParams = {\n messageToAppend: {\n content: [{ type: \"text\", text: message }],\n role: \"user\",\n },\n contextKey: options.contextKey,\n availableComponents: availableComponents,\n clientTools: unassociatedTools.map((tool) =>\n mapTamboToolToContextTool(tool),\n ),\n };\n\n if (streamResponse) {\n const advanceStreamResponse = await advanceStream(\n client,\n params,\n threadId === PLACEHOLDER_THREAD.id ? undefined : threadId,\n );\n return await handleAdvanceStream(\n advanceStreamResponse,\n params,\n threadId,\n );\n }\n let advanceResponse = await (threadId === PLACEHOLDER_THREAD.id\n ? client.beta.threads.advance(params)\n : client.beta.threads.advanceById(threadId, params));\n\n //handle tool calls\n while (advanceResponse.responseMessageDto.toolCallRequest) {\n updateThreadStatus(threadId, GenerationStage.FETCHING_CONTEXT);\n const toolCallResponse = await handleToolCall(\n advanceResponse.responseMessageDto,\n toolRegistry,\n );\n const toolResponseString =\n typeof toolCallResponse === \"string\"\n ? toolCallResponse\n : JSON.stringify(toolCallResponse);\n const toolCallResponseParams: TamboAI.Beta.Threads.ThreadAdvanceParams =\n {\n ...params,\n messageToAppend: {\n ...params.messageToAppend,\n content: [{ type: \"text\", text: toolResponseString }],\n role: \"tool\",\n actionType: \"tool_response\",\n component: advanceResponse.responseMessageDto.component,\n tool_call_id: advanceResponse.responseMessageDto.tool_call_id,\n },\n };\n updateThreadStatus(threadId, GenerationStage.HYDRATING_COMPONENT);\n advanceResponse = await client.beta.threads.advanceById(\n advanceResponse.responseMessageDto.threadId,\n toolCallResponseParams,\n );\n }\n\n const finalMessage = advanceResponse.responseMessageDto.component\n ?.componentName\n ? renderComponentIntoMessage(\n advanceResponse.responseMessageDto,\n componentList,\n )\n : advanceResponse.responseMessageDto;\n await switchCurrentThread(advanceResponse.responseMessageDto.threadId);\n updateThreadStatus(\n advanceResponse.responseMessageDto.threadId,\n GenerationStage.COMPLETE,\n );\n return finalMessage;\n },\n [\n componentList,\n toolRegistry,\n componentToolAssociations,\n currentThread.id,\n switchCurrentThread,\n addThreadMessage,\n client,\n updateThreadStatus,\n handleAdvanceStream,\n ],\n );\n\n return (\n <TamboThreadContext.Provider\n value={{\n thread: currentThread,\n switchCurrentThread,\n startNewThread,\n addThreadMessage,\n updateThreadMessage,\n inputValue,\n setInputValue,\n sendThreadMessage,\n generationStage: (currentThread?.generationStage ??\n GenerationStage.IDLE) as GenerationStage,\n generationStatusMessage: currentThread?.statusMessage ?? \"\",\n isIdle: isIdleStage(\n (currentThread?.generationStage ??\n GenerationStage.IDLE) as GenerationStage,\n ),\n }}\n >\n {children}\n </TamboThreadContext.Provider>\n );\n};\n\n/**\n * The useTamboThread hook provides access to the current thread context\n * to the descendants of the TamboThreadProvider.\n * @returns All state and actions for the current thread\n */\nexport const useTamboThread = () => {\n const context = useContext(TamboThreadContext);\n if (context === undefined) {\n throw new Error(\"useTamboThread must be used within a TamboThreadProvider\");\n }\n return context;\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-suggestions.d.ts","sourceRoot":"","sources":["../../src/hooks/use-suggestions.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,0BAA0B,CAAC;
|
|
1
|
+
{"version":3,"file":"use-suggestions.d.ts","sourceRoot":"","sources":["../../src/hooks/use-suggestions.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,0BAA0B,CAAC;AAQ/C,OAAO,EACL,sBAAsB,EAEvB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAC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|
import { useEffect, useState } from "react";
|
|
2
|
+
import { isIdleStage } from "../model/generate-component-response";
|
|
2
3
|
import { validateInput } from "../model/validate-input";
|
|
3
4
|
import { useTamboClient } from "../providers/tambo-client-provider";
|
|
4
5
|
import { useTambo } from "../providers/tambo-provider";
|
|
@@ -15,7 +16,7 @@ import { INPUT_ERROR_MESSAGES, useTamboThreadInput } from "./use-thread-input";
|
|
|
15
16
|
*/
|
|
16
17
|
export function useTamboSuggestions(options = {}) {
|
|
17
18
|
const { maxSuggestions = 3 } = options;
|
|
18
|
-
const { thread } = useTamboThread();
|
|
19
|
+
const { thread, generationStage } = useTamboThread();
|
|
19
20
|
const { sendThreadMessage } = useTambo();
|
|
20
21
|
const tamboClient = useTamboClient();
|
|
21
22
|
const { componentList, toolRegistry, componentToolAssociations } = useTamboRegistry();
|
|
@@ -28,12 +29,17 @@ export function useTamboSuggestions(options = {}) {
|
|
|
28
29
|
useEffect(() => {
|
|
29
30
|
setSelectedSuggestionId(null);
|
|
30
31
|
}, [latestMessageId]);
|
|
32
|
+
const shouldGenerateSuggestions = latestMessageId && isLatestFromTambo && isIdleStage(generationStage);
|
|
31
33
|
// Use React Query to fetch suggestions when a new hydra message is received
|
|
32
34
|
const suggestionsResult = useTamboQuery({
|
|
33
|
-
//
|
|
34
|
-
|
|
35
|
+
// Make sure the query key changes when the message changes, so that we are
|
|
36
|
+
// always generating suggestions when there is a new message
|
|
37
|
+
queryKey: [
|
|
38
|
+
"suggestions",
|
|
39
|
+
shouldGenerateSuggestions ? latestMessageId : null,
|
|
40
|
+
],
|
|
35
41
|
queryFn: async () => {
|
|
36
|
-
if (!
|
|
42
|
+
if (!shouldGenerateSuggestions) {
|
|
37
43
|
return [];
|
|
38
44
|
}
|
|
39
45
|
// Get registered components from the registry
|
|
@@ -75,7 +81,7 @@ export function useTamboSuggestions(options = {}) {
|
|
|
75
81
|
// Generate suggestions mutation
|
|
76
82
|
const generateMutationState = useTamboMutation({
|
|
77
83
|
mutationFn: async (abortController) => {
|
|
78
|
-
if (!
|
|
84
|
+
if (!shouldGenerateSuggestions) {
|
|
79
85
|
return undefined;
|
|
80
86
|
}
|
|
81
87
|
// Get registered components from the registry
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-suggestions.js","sourceRoot":"","sources":["../../src/hooks/use-suggestions.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AACpE,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AACxE,OAAO,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AACpE,OAAO,EAEL,sBAAsB,GACvB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAGL,gBAAgB,EAChB,aAAa,GACd,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAoD/E;;;;GAIG;AACH,MAAM,UAAU,mBAAmB,CACjC,UAAsC,EAAE;IAExC,MAAM,EAAE,cAAc,GAAG,CAAC,EAAE,GAAG,OAAO,CAAC;IACvC,MAAM,EAAE,MAAM,EAAE,GAAG,cAAc,EAAE,CAAC;IACpC,MAAM,EAAE,iBAAiB,EAAE,GAAG,QAAQ,EAAE,CAAC;IACzC,MAAM,WAAW,GAAG,cAAc,EAAE,CAAC;IACrC,MAAM,EAAE,aAAa,EAAE,YAAY,EAAE,yBAAyB,EAAE,GAC9D,gBAAgB,EAAE,CAAC;IAErB,MAAM,CAAC,oBAAoB,EAAE,uBAAuB,CAAC,GAAG,QAAQ,CAE9D,IAAI,CAAC,CAAC;IACR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AAK,EAAE,KAAK;KACb,CAAC,CAAC;IAEH,mEAAmE;IACnE,8DAA8D;IAC9D,MAAM,WAAW,GAAG,iBAAiB;QACnC,CAAC,CAAC,CAAC,iBAAiB,CAAC,IAAI,IAAI,qBAAqB,CAAC,IAAI,IAAI,EAAE,CAAC;QAC9D,CAAC,CAAC,EAAE,CAAC;IAEP,OAAO;QACL,WAAW;QACX,MAAM,EAAE,mBAAmB,CAAC,WAAW;QACvC,oBAAoB;QACpB,YAAY,EAAE,mBAAmB;QACjC,cAAc,EAAE,qBAAqB;QACrC,iBAAiB;QACjB,GAAG,sBAAsB,CAAC,mBAAmB,EAAE,qBAAqB,CAAC;KACtE,CAAC;AACJ,CAAC","sourcesContent":["import TamboAI from \"@tambo-ai/typescript-sdk\";\nimport { useEffect, useState } from \"react\";\nimport { validateInput } from \"../model/validate-input\";\nimport { useTamboClient } from \"../providers/tambo-client-provider\";\nimport { useTambo } from \"../providers/tambo-provider\";\nimport { useTamboRegistry } from \"../providers/tambo-registry-provider\";\nimport { useTamboThread } from \"../providers/tambo-thread-provider\";\nimport {\n CombinedMutationResult,\n combineMutationResults,\n} from \"../util/query-utils\";\nimport { getAvailableComponents } from \"../util/registry\";\nimport {\n UseTamboMutationResult,\n UseTamboQueryResult,\n useTamboMutation,\n useTamboQuery,\n} from \"./react-query-hooks\";\nimport { INPUT_ERROR_MESSAGES, useTamboThreadInput } from \"./use-thread-input\";\n\n/**\n * Configuration options for the useTamboSuggestions hook\n */\nexport interface useTamboSuggestionsOptions {\n /** Maximum number of suggestions to generate (1-10, default 3) */\n maxSuggestions?: number;\n}\n\n/**\n * Return value interface for useTamboSuggestions hook\n */\nexport interface useTamboSuggestionsResultInternal {\n /** List of available suggestions (also available in generateResult.data) */\n suggestions: TamboAI.Beta.Threads.Suggestion[];\n /** ID of the currently selected suggestion */\n selectedSuggestionId: string | null;\n /**\n * Accept and apply a suggestion (also available in acceptResult.mutateAsync)\n * @param suggestion - The suggestion to accept\n * @param shouldSubmit - Whether to automatically submit after accepting (default: false)\n */\n accept: (acceptOptions: {\n suggestion: TamboAI.Beta.Threads.Suggestion;\n shouldSubmit?: boolean;\n }) => Promise<void>;\n\n /** Result and network state for accepting a suggestion */\n acceptResult: UseTamboMutationResult<\n void,\n Error,\n { suggestion: TamboAI.Beta.Threads.Suggestion; shouldSubmit?: boolean }\n >;\n\n /** Result and network state for generating suggestions */\n generateResult: UseTamboMutationResult<\n TamboAI.Beta.Threads.Suggestions.SuggestionGenerateResponse | undefined,\n Error,\n AbortController\n >;\n\n /** The full suggestions query object from React Query */\n suggestionsResult: UseTamboQueryResult<\n TamboAI.Beta.Threads.Suggestions.SuggestionGenerateResponse | undefined,\n Error\n >;\n}\n\ntype useTamboSuggestionsResult = CombinedMutationResult<any, Error> &\n useTamboSuggestionsResultInternal;\n\n/**\n * Hook for managing Tambo AI suggestions in a thread\n * @param options - Configuration options for suggestion generation\n * @returns Object containing suggestions state and control functions\n */\nexport function useTamboSuggestions(\n options: useTamboSuggestionsOptions = {},\n): useTamboSuggestionsResult {\n const { maxSuggestions = 3 } = options;\n const { thread } = useTamboThread();\n const { sendThreadMessage } = useTambo();\n const tamboClient = useTamboClient();\n const { componentList, toolRegistry, componentToolAssociations } =\n useTamboRegistry();\n\n const [selectedSuggestionId, setSelectedSuggestionId] = useState<\n string | null\n >(null);\n const { setValue: setInputValue } = useTamboThreadInput();\n\n const latestMessage = thread.messages[thread.messages.length - 1];\n const isLatestFromTambo = latestMessage?.role === \"assistant\";\n const latestMessageId = latestMessage?.id;\n\n // Reset selected suggestion when the message changes\n useEffect(() => {\n setSelectedSuggestionId(null);\n }, [latestMessageId]);\n\n // Use React Query to fetch suggestions when a new hydra message is received\n const suggestionsResult = useTamboQuery({\n // Only include latestMessageId in the queryKey if the message is from hydra\n queryKey: [\"suggestions\", isLatestFromTambo ? latestMessageId : null],\n queryFn: async () => {\n if (!latestMessageId || !isLatestFromTambo) {\n return [];\n }\n\n // Get registered components from the registry\n const components = getAvailableComponents(\n componentList,\n toolRegistry,\n componentToolAssociations,\n );\n\n return await tamboClient.beta.threads.suggestions.generate(\n thread.id,\n latestMessageId,\n {\n maxSuggestions,\n availableComponents: components,\n },\n );\n },\n // Only run the query if we have a valid message from hydra\n enabled: Boolean(latestMessageId && isLatestFromTambo),\n // Don't refetch on window focus or reconnect\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n // Don't retry on failure\n retry: false,\n });\n\n // Accept suggestion mutation\n const acceptMutationState = useTamboMutation<\n void,\n Error,\n { suggestion: TamboAI.Beta.Threads.Suggestion; shouldSubmit?: boolean }\n >({\n mutationFn: async ({ suggestion, shouldSubmit = false }) => {\n const validation = validateInput(suggestion.detailedSuggestion);\n if (!validation.isValid) {\n if (validation.error) {\n throw validation.error;\n }\n throw new Error(INPUT_ERROR_MESSAGES.VALIDATION);\n }\n\n if (shouldSubmit) {\n await sendThreadMessage(validation.sanitizedInput, {\n threadId: thread.id,\n });\n } else {\n setInputValue(validation.sanitizedInput);\n }\n setSelectedSuggestionId(suggestion.id);\n },\n });\n\n // Generate suggestions mutation\n const generateMutationState = useTamboMutation<\n TamboAI.Beta.Threads.Suggestions.SuggestionGenerateResponse | undefined,\n Error,\n AbortController\n >({\n mutationFn: async (abortController: AbortController) => {\n if (!latestMessageId || !isLatestFromTambo) {\n return undefined;\n }\n\n // Get registered components from the registry\n const components = getAvailableComponents(\n componentList,\n toolRegistry,\n componentToolAssociations,\n );\n\n return await tamboClient.beta.threads.suggestions.generate(\n thread.id,\n latestMessageId,\n {\n maxSuggestions,\n availableComponents: components,\n },\n { signal: abortController.signal },\n );\n },\n // Don't retry on failure\n retry: false,\n });\n\n // Use the query data if available, otherwise use the mutation data\n // Only return suggestions if the latest message is from hydra\n const suggestions = isLatestFromTambo\n ? (suggestionsResult.data ?? generateMutationState.data ?? [])\n : [];\n\n return {\n suggestions,\n accept: acceptMutationState.mutateAsync,\n selectedSuggestionId,\n acceptResult: acceptMutationState,\n generateResult: generateMutationState,\n suggestionsResult,\n ...combineMutationResults(acceptMutationState, generateMutationState),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"use-suggestions.js","sourceRoot":"","sources":["../../src/hooks/use-suggestions.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,sCAAsC,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AACpE,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AACxE,OAAO,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AACpE,OAAO,EAEL,sBAAsB,GACvB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAGL,gBAAgB,EAChB,aAAa,GACd,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAoD/E;;;;GAIG;AACH,MAAM,UAAU,mBAAmB,CACjC,UAAsC,EAAE;IAExC,MAAM,EAAE,cAAc,GAAG,CAAC,EAAE,GAAG,OAAO,CAAC;IACvC,MAAM,EAAE,MAAM,EAAE,eAAe,EAAE,GAAG,cAAc,EAAE,CAAC;IACrD,MAAM,EAAE,iBAAiB,EAAE,GAAG,QAAQ,EAAE,CAAC;IACzC,MAAM,WAAW,GAAG,cAAc,EAAE,CAAC;IACrC,MAAM,EAAE,aAAa,EAAE,YAAY,EAAE,yBAAyB,EAAE,GAC9D,gBAAgB,EAAE,CAAC;IAErB,MAAM,CAAC,oBAAoB,EAAE,uBAAuB,CAAC,GAAG,QAAQ,CAE9D,IAAI,CAAC,CAAC;IACR,MAAM,EAAE,QAAQ,EA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AC;QACJ,CAAC;QACD,yBAAyB;QACzB,KAAK,EAAE,KAAK;KACb,CAAC,CAAC;IAEH,mEAAmE;IACnE,8DAA8D;IAC9D,MAAM,WAAW,GAAG,iBAAiB;QACnC,CAAC,CAAC,CAAC,iBAAiB,CAAC,IAAI,IAAI,qBAAqB,CAAC,IAAI,IAAI,EAAE,CAAC;QAC9D,CAAC,CAAC,EAAE,CAAC;IAEP,OAAO;QACL,WAAW;QACX,MAAM,EAAE,mBAAmB,CAAC,WAAW;QACvC,oBAAoB;QACpB,YAAY,EAAE,mBAAmB;QACjC,cAAc,EAAE,qBAAqB;QACrC,iBAAiB;QACjB,GAAG,sBAAsB,CAAC,mBAAmB,EAAE,qBAAqB,CAAC;KACtE,CAAC;AACJ,CAAC","sourcesContent":["import TamboAI from \"@tambo-ai/typescript-sdk\";\nimport { useEffect, useState } from \"react\";\nimport { isIdleStage } from \"../model/generate-component-response\";\nimport { validateInput } from \"../model/validate-input\";\nimport { useTamboClient } from \"../providers/tambo-client-provider\";\nimport { useTambo } from \"../providers/tambo-provider\";\nimport { useTamboRegistry } from \"../providers/tambo-registry-provider\";\nimport { useTamboThread } from \"../providers/tambo-thread-provider\";\nimport {\n CombinedMutationResult,\n combineMutationResults,\n} from \"../util/query-utils\";\nimport { getAvailableComponents } from \"../util/registry\";\nimport {\n UseTamboMutationResult,\n UseTamboQueryResult,\n useTamboMutation,\n useTamboQuery,\n} from \"./react-query-hooks\";\nimport { INPUT_ERROR_MESSAGES, useTamboThreadInput } from \"./use-thread-input\";\n\n/**\n * Configuration options for the useTamboSuggestions hook\n */\nexport interface useTamboSuggestionsOptions {\n /** Maximum number of suggestions to generate (1-10, default 3) */\n maxSuggestions?: number;\n}\n\n/**\n * Return value interface for useTamboSuggestions hook\n */\nexport interface useTamboSuggestionsResultInternal {\n /** List of available suggestions (also available in generateResult.data) */\n suggestions: TamboAI.Beta.Threads.Suggestion[];\n /** ID of the currently selected suggestion */\n selectedSuggestionId: string | null;\n /**\n * Accept and apply a suggestion (also available in acceptResult.mutateAsync)\n * @param suggestion - The suggestion to accept\n * @param shouldSubmit - Whether to automatically submit after accepting (default: false)\n */\n accept: (acceptOptions: {\n suggestion: TamboAI.Beta.Threads.Suggestion;\n shouldSubmit?: boolean;\n }) => Promise<void>;\n\n /** Result and network state for accepting a suggestion */\n acceptResult: UseTamboMutationResult<\n void,\n Error,\n { suggestion: TamboAI.Beta.Threads.Suggestion; shouldSubmit?: boolean }\n >;\n\n /** Result and network state for generating suggestions */\n generateResult: UseTamboMutationResult<\n TamboAI.Beta.Threads.Suggestions.SuggestionGenerateResponse | undefined,\n Error,\n AbortController\n >;\n\n /** The full suggestions query object from React Query */\n suggestionsResult: UseTamboQueryResult<\n TamboAI.Beta.Threads.Suggestions.SuggestionGenerateResponse | undefined,\n Error\n >;\n}\n\ntype useTamboSuggestionsResult = CombinedMutationResult<any, Error> &\n useTamboSuggestionsResultInternal;\n\n/**\n * Hook for managing Tambo AI suggestions in a thread\n * @param options - Configuration options for suggestion generation\n * @returns Object containing suggestions state and control functions\n */\nexport function useTamboSuggestions(\n options: useTamboSuggestionsOptions = {},\n): useTamboSuggestionsResult {\n const { maxSuggestions = 3 } = options;\n const { thread, generationStage } = useTamboThread();\n const { sendThreadMessage } = useTambo();\n const tamboClient = useTamboClient();\n const { componentList, toolRegistry, componentToolAssociations } =\n useTamboRegistry();\n\n const [selectedSuggestionId, setSelectedSuggestionId] = useState<\n string | null\n >(null);\n const { setValue: setInputValue } = useTamboThreadInput();\n\n const latestMessage = thread.messages[thread.messages.length - 1];\n const isLatestFromTambo = latestMessage?.role === \"assistant\";\n const latestMessageId = latestMessage?.id;\n\n // Reset selected suggestion when the message changes\n useEffect(() => {\n setSelectedSuggestionId(null);\n }, [latestMessageId]);\n\n const shouldGenerateSuggestions =\n latestMessageId && isLatestFromTambo && isIdleStage(generationStage);\n // Use React Query to fetch suggestions when a new hydra message is received\n const suggestionsResult = useTamboQuery({\n // Make sure the query key changes when the message changes, so that we are\n // always generating suggestions when there is a new message\n queryKey: [\n \"suggestions\",\n shouldGenerateSuggestions ? latestMessageId : null,\n ],\n queryFn: async () => {\n if (!shouldGenerateSuggestions) {\n return [];\n }\n\n // Get registered components from the registry\n const components = getAvailableComponents(\n componentList,\n toolRegistry,\n componentToolAssociations,\n );\n\n return await tamboClient.beta.threads.suggestions.generate(\n thread.id,\n latestMessageId,\n {\n maxSuggestions,\n availableComponents: components,\n },\n );\n },\n // Only run the query if we have a valid message from hydra\n enabled: Boolean(latestMessageId && isLatestFromTambo),\n // Don't refetch on window focus or reconnect\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n // Don't retry on failure\n retry: false,\n });\n\n // Accept suggestion mutation\n const acceptMutationState = useTamboMutation<\n void,\n Error,\n { suggestion: TamboAI.Beta.Threads.Suggestion; shouldSubmit?: boolean }\n >({\n mutationFn: async ({ suggestion, shouldSubmit = false }) => {\n const validation = validateInput(suggestion.detailedSuggestion);\n if (!validation.isValid) {\n if (validation.error) {\n throw validation.error;\n }\n throw new Error(INPUT_ERROR_MESSAGES.VALIDATION);\n }\n\n if (shouldSubmit) {\n await sendThreadMessage(validation.sanitizedInput, {\n threadId: thread.id,\n });\n } else {\n setInputValue(validation.sanitizedInput);\n }\n setSelectedSuggestionId(suggestion.id);\n },\n });\n\n // Generate suggestions mutation\n const generateMutationState = useTamboMutation<\n TamboAI.Beta.Threads.Suggestions.SuggestionGenerateResponse | undefined,\n Error,\n AbortController\n >({\n mutationFn: async (abortController: AbortController) => {\n if (!shouldGenerateSuggestions) {\n return undefined;\n }\n\n // Get registered components from the registry\n const components = getAvailableComponents(\n componentList,\n toolRegistry,\n componentToolAssociations,\n );\n return await tamboClient.beta.threads.suggestions.generate(\n thread.id,\n latestMessageId,\n {\n maxSuggestions,\n availableComponents: components,\n },\n { signal: abortController.signal },\n );\n },\n // Don't retry on failure\n retry: false,\n });\n\n // Use the query data if available, otherwise use the mutation data\n // Only return suggestions if the latest message is from hydra\n const suggestions = isLatestFromTambo\n ? (suggestionsResult.data ?? generateMutationState.data ?? [])\n : [];\n\n return {\n suggestions,\n accept: acceptMutationState.mutateAsync,\n selectedSuggestionId,\n acceptResult: acceptMutationState,\n generateResult: generateMutationState,\n suggestionsResult,\n ...combineMutationResults(acceptMutationState, generateMutationState),\n };\n}\n"]}
|
|
@@ -12,6 +12,7 @@ import { TamboThreadContextProps } from "./tambo-thread-provider";
|
|
|
12
12
|
* @param props.apiKey - The API key for the Tambo API
|
|
13
13
|
* @param props.components - The components to register
|
|
14
14
|
* @param props.environment - The environment to use for the Tambo API
|
|
15
|
+
* @param props.tools - The tools to register
|
|
15
16
|
* @returns The TamboProvider component
|
|
16
17
|
*/
|
|
17
18
|
export declare const TamboProvider: React.FC<PropsWithChildren<TamboClientProviderProps & TamboRegistryProviderProps>>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tambo-provider.d.ts","sourceRoot":"","sources":["../../src/providers/tambo-provider.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,EAAE,iBAAiB,EAA6B,MAAM,OAAO,CAAC;AAC5E,OAAO,EACL,uBAAuB,EAEvB,wBAAwB,EAGzB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACL,0BAA0B,EAG3B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAEL,0BAA0B,EAC3B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,uBAAuB,EAGxB,MAAM,yBAAyB,CAAC;AAEjC
|
|
1
|
+
{"version":3,"file":"tambo-provider.d.ts","sourceRoot":"","sources":["../../src/providers/tambo-provider.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,EAAE,iBAAiB,EAA6B,MAAM,OAAO,CAAC;AAC5E,OAAO,EACL,uBAAuB,EAEvB,wBAAwB,EAGzB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACL,0BAA0B,EAG3B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAEL,0BAA0B,EAC3B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,uBAAuB,EAGxB,MAAM,yBAAyB,CAAC;AAEjC;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,aAAa,EAAE,KAAK,CAAC,EAAE,CAClC,iBAAiB,CAAC,wBAAwB,GAAG,0BAA0B,CAAC,CAsBzE,CAAC;AACF,MAAM,MAAM,iBAAiB,GAAG,uBAAuB,GACrD,uBAAuB,GACvB,0BAA0B,CAAC;AAE7B,eAAO,MAAM,YAAY,kCAExB,CAAC;AA6BF;;;;;;GAMG;AACH,eAAO,MAAM,QAAQ,yBAEpB,CAAC"}
|
|
@@ -13,15 +13,16 @@ import { TamboThreadProvider, useTamboThread, } from "./tambo-thread-provider";
|
|
|
13
13
|
* @param props.apiKey - The API key for the Tambo API
|
|
14
14
|
* @param props.components - The components to register
|
|
15
15
|
* @param props.environment - The environment to use for the Tambo API
|
|
16
|
+
* @param props.tools - The tools to register
|
|
16
17
|
* @returns The TamboProvider component
|
|
17
18
|
*/
|
|
18
|
-
export const TamboProvider = ({ children, tamboUrl, apiKey, components, environment }) => {
|
|
19
|
+
export const TamboProvider = ({ children, tamboUrl, apiKey, components, environment, tools }) => {
|
|
19
20
|
// Should only be used in browser
|
|
20
21
|
if (typeof window === "undefined") {
|
|
21
22
|
console.error("TamboProvider must be used within a browser");
|
|
22
23
|
}
|
|
23
24
|
return (React.createElement(TamboClientProvider, { tamboUrl: tamboUrl, apiKey: apiKey, environment: environment },
|
|
24
|
-
React.createElement(TamboRegistryProvider, { components: components },
|
|
25
|
+
React.createElement(TamboRegistryProvider, { components: components, tools: tools },
|
|
25
26
|
React.createElement(TamboThreadProvider, null,
|
|
26
27
|
React.createElement(TamboComponentProvider, null,
|
|
27
28
|
React.createElement(TamboCompositeProvider, null, children))))));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tambo-provider.js","sourceRoot":"","sources":["../../src/providers/tambo-provider.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;AACb,OAAO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AAK;YACzD,oBAAC,mBAAmB;gBAClB,oBAAC,sBAAsB;oBACrB,oBAAC,sBAAsB,QAAE,QAAQ,CAA0B,CACpC,CACL,CACA,CACJ,CACvB,CAAC;AACJ,CAAC,CAAC;AAKF,MAAM,CAAC,MAAM,YAAY,GAAG,aAAa,CACvC,EAAuB,CACxB,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,sBAAsB,GAAgC,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE;IAC3E,MAAM,OAAO,GAAG,cAAc,EAAE,CAAC;IACjC,MAAM,MAAM,GAAG,cAAc,EAAE,CAAC;IAChC,MAAM,WAAW,GAAG,mBAAmB,EAAE,CAAC;IAC1C,MAAM,iBAAiB,GAAG,iBAAiB,EAAE,CAAC;IAE9C,OAAO,CACL,oBAAC,YAAY,CAAC,QAAQ,IACpB,KAAK,EAAE;YACL,MAAM;YACN,WAAW;YACX,GAAG,iBAAiB;YACpB,GAAG,OAAO;SACX,IAEA,QAAQ,CACa,CACzB,CAAC;AACJ,CAAC,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,GAAG,EAAE;IAC3B,OAAO,UAAU,CAAC,YAAY,CAAC,CAAC;AAClC,CAAC,CAAC","sourcesContent":["\"use client\";\nimport React, { PropsWithChildren, createContext, useContext } from \"react\";\nimport {\n TamboClientContextProps,\n TamboClientProvider,\n TamboClientProviderProps,\n useTamboClient,\n useTamboQueryClient,\n} from \"./tambo-client-provider\";\nimport {\n TamboComponentContextProps,\n TamboComponentProvider,\n useTamboComponent,\n} from \"./tambo-component-provider\";\nimport {\n TamboRegistryProvider,\n TamboRegistryProviderProps,\n} from \"./tambo-registry-provider\";\nimport {\n TamboThreadContextProps,\n TamboThreadProvider,\n useTamboThread,\n} from \"./tambo-thread-provider\";\n\n/**\n * The TamboProvider gives full access to the whole Tambo API. This includes the\n * TamboAI client, the component registry, and the current thread context.\n * @param props - The props for the TamboProvider\n * @param props.children - The children to wrap\n * @param props.tamboUrl - The URL of the Tambo API\n * @param props.apiKey - The API key for the Tambo API\n * @param props.components - The components to register\n * @param props.environment - The environment to use for the Tambo API\n * @param props.tools - The tools to register\n * @returns The TamboProvider component\n */\nexport const TamboProvider: React.FC<\n PropsWithChildren<TamboClientProviderProps & TamboRegistryProviderProps>\n> = ({ children, tamboUrl, apiKey, components, environment, tools }) => {\n // Should only be used in browser\n if (typeof window === \"undefined\") {\n console.error(\"TamboProvider must be used within a browser\");\n }\n\n return (\n <TamboClientProvider\n tamboUrl={tamboUrl}\n apiKey={apiKey}\n environment={environment}\n >\n <TamboRegistryProvider components={components} tools={tools}>\n <TamboThreadProvider>\n <TamboComponentProvider>\n <TamboCompositeProvider>{children}</TamboCompositeProvider>\n </TamboComponentProvider>\n </TamboThreadProvider>\n </TamboRegistryProvider>\n </TamboClientProvider>\n );\n};\nexport type TamboContextProps = TamboClientContextProps &\n TamboThreadContextProps &\n TamboComponentContextProps;\n\nexport const TamboContext = createContext<TamboContextProps>(\n {} as TamboContextProps,\n);\n\n/**\n * TamboCompositeProvider is a provider that combines the TamboClient,\n * TamboThread, and TamboComponent providers\n * @param props - The props for the TamboCompositeProvider\n * @param props.children - The children to wrap\n * @returns The wrapped component\n */\nconst TamboCompositeProvider: React.FC<PropsWithChildren> = ({ children }) => {\n const threads = useTamboThread();\n const client = useTamboClient();\n const queryClient = useTamboQueryClient();\n const componentRegistry = useTamboComponent();\n\n return (\n <TamboContext.Provider\n value={{\n client,\n queryClient,\n ...componentRegistry,\n ...threads,\n }}\n >\n {children}\n </TamboContext.Provider>\n );\n};\n\n/**\n * The useTambo hook provides access to the Tambo API. This is the primary entrypoint\n * for the Tambo React SDK.\n *\n * This includes the TamboAI client, the component registry, and the current thread context.\n * @returns The Tambo API\n */\nexport const useTambo = () => {\n return useContext(TamboContext);\n};\n"]}
|
|
@@ -12,6 +12,8 @@ export interface TamboRegistryContext {
|
|
|
12
12
|
export interface TamboRegistryProviderProps {
|
|
13
13
|
/** The components to register */
|
|
14
14
|
components?: TamboComponent[];
|
|
15
|
+
/** The tools to register */
|
|
16
|
+
tools?: TamboTool[];
|
|
15
17
|
}
|
|
16
18
|
/**
|
|
17
19
|
* The TamboRegistryProvider is a React provider that provides a component
|
|
@@ -19,6 +21,7 @@ export interface TamboRegistryProviderProps {
|
|
|
19
21
|
* @param props - The props for the TamboRegistryProvider
|
|
20
22
|
* @param props.children - The children to wrap
|
|
21
23
|
* @param props.components - The components to register
|
|
24
|
+
* @param props.tools - The tools to register
|
|
22
25
|
* @returns The TamboRegistryProvider component
|
|
23
26
|
*/
|
|
24
27
|
export declare const TamboRegistryProvider: React.FC<PropsWithChildren<TamboRegistryProviderProps>>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tambo-registry-provider.d.ts","sourceRoot":"","sources":["../../src/providers/tambo-registry-provider.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,EAEZ,iBAAiB,EAKlB,MAAM,OAAO,CAAC;AAGf,OAAO,EACL,iBAAiB,EACjB,cAAc,EACd,SAAS,EACV,MAAM,6BAA6B,CAAC;AAErC,MAAM,WAAW,oBAAoB;IACnC,aAAa,EAAE,iBAAiB,CAAC;IACjC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;IACxC,yBAAyB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IACpD,iBAAiB,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;IACrD,YAAY,EAAE,CAAC,IAAI,EAAE,SAAS,KAAK,IAAI,CAAC;IACxC,aAAa,EAAE,CAAC,KAAK,EAAE,SAAS,EAAE,KAAK,IAAI,CAAC;IAC5C,kBAAkB,EAAE,CAAC,aAAa,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,KAAK,IAAI,CAAC;CACtE;AAwBD,MAAM,WAAW,0BAA0B;IACzC,iCAAiC;IACjC,UAAU,CAAC,EAAE,cAAc,EAAE,CAAC;
|
|
1
|
+
{"version":3,"file":"tambo-registry-provider.d.ts","sourceRoot":"","sources":["../../src/providers/tambo-registry-provider.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,EAEZ,iBAAiB,EAKlB,MAAM,OAAO,CAAC;AAGf,OAAO,EACL,iBAAiB,EACjB,cAAc,EACd,SAAS,EACV,MAAM,6BAA6B,CAAC;AAErC,MAAM,WAAW,oBAAoB;IACnC,aAAa,EAAE,iBAAiB,CAAC;IACjC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;IACxC,yBAAyB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IACpD,iBAAiB,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;IACrD,YAAY,EAAE,CAAC,IAAI,EAAE,SAAS,KAAK,IAAI,CAAC;IACxC,aAAa,EAAE,CAAC,KAAK,EAAE,SAAS,EAAE,KAAK,IAAI,CAAC;IAC5C,kBAAkB,EAAE,CAAC,aAAa,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,KAAK,IAAI,CAAC;CACtE;AAwBD,MAAM,WAAW,0BAA0B;IACzC,iCAAiC;IACjC,UAAU,CAAC,EAAE,cAAc,EAAE,CAAC;IAC9B,4BAA4B;IAC5B,KAAK,CAAC,EAAE,SAAS,EAAE,CAAC;CACrB;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,qBAAqB,EAAE,KAAK,CAAC,EAAE,CAC1C,iBAAiB,CAAC,0BAA0B,CAAC,CAiI9C,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,4BAE5B,CAAC"}
|
|
@@ -29,9 +29,10 @@ const TamboRegistryContext = createContext({
|
|
|
29
29
|
* @param props - The props for the TamboRegistryProvider
|
|
30
30
|
* @param props.children - The children to wrap
|
|
31
31
|
* @param props.components - The components to register
|
|
32
|
+
* @param props.tools - The tools to register
|
|
32
33
|
* @returns The TamboRegistryProvider component
|
|
33
34
|
*/
|
|
34
|
-
export const TamboRegistryProvider = ({ children, components: userComponents }) => {
|
|
35
|
+
export const TamboRegistryProvider = ({ children, components: userComponents, tools: userTools }) => {
|
|
35
36
|
const [componentList, setComponentList] = useState({});
|
|
36
37
|
const [toolRegistry, setToolRegistry] = useState({});
|
|
37
38
|
const [componentToolAssociations, setComponentToolAssociations] = useState({});
|
|
@@ -101,6 +102,11 @@ export const TamboRegistryProvider = ({ children, components: userComponents })
|
|
|
101
102
|
});
|
|
102
103
|
}
|
|
103
104
|
}, [registerComponent, userComponents]);
|
|
105
|
+
useEffect(() => {
|
|
106
|
+
if (userTools) {
|
|
107
|
+
registerTools(userTools, false);
|
|
108
|
+
}
|
|
109
|
+
}, [registerTools, userTools]);
|
|
104
110
|
const value = {
|
|
105
111
|
componentList,
|
|
106
112
|
toolRegistry,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tambo-registry-provider.js","sourceRoot":"","sources":["../../src/providers/tambo-registry-provider.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;AACb,OAAO,KAAK,EAAE,EACZ,aAAa,EAEb,WAAW,EACX,UAAU,EACV,SAAS,EACT,QAAQ,GACT,MAAM,OAAO,CAAC;AACf,OAAO,EAAE,SAAS,EAAE,MAAM,KAAK,CAAC;AAChC,OAAO,eAAe,MAAM,oBAAoB,CAAC;AAiBjD,MAAM,oBAAoB,GAAG,aAAa,CAAuB;IAC/D,aAAa,EAAE,EAAE;IACjB,YAAY,EAAE,EAAE;IAChB,yBAAyB,EAAE,EAAE;IAC7B;;OAEG;IACH,iBAAiB,EAAE,GAAG,EAAE,GAAE,CAAC;IAC3B;;OAEG;IACH,YAAY,EAAE,GAAG,EAAE,GAAE,CAAC;IACtB;;OAEG;IACH,aAAa,EAAE,GAAG,EAAE,GAAE,CAAC;IACvB;;OAEG;IACH,kBAAkB,EAAE,GAAG,EAAE,GAAE,CAAC;CAC7B,CAAC,CAAC;AAOH;;;;;;;GA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AAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CACX,oBAAoB,IAAI,+BAA+B,EACvD,KAAK,CACN,CAAC;QACJ,CAAC;IACH,CAAC;IACD,qFAAqF;IACrF,IAAI,YAAY,CAAC,WAAW,CAAC,EAAE,CAAC;QAC9B,OAAO,WAAW,CAAC;IACrB,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,4BAA4B,IAAI,EAAE,CAAC,CAAC;AACtD,CAAC;AAED;;;;;GAKG;AACH,SAAS,YAAY,CAAC,WAAgB;IACpC,OAAO,CACL,WAAW;QACX,OAAO,WAAW,KAAK,QAAQ;QAC/B,WAAW,CAAC,IAAI,KAAK,QAAQ;QAC7B,WAAW,CAAC,UAAU,CACvB,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,WAAW,CAAC,GAAY;IAC/B,IAAI,GAAG,YAAY,SAAS,EAAE,CAAC;QAC7B,OAAO,IAAI,CAAC;IACd,CAAC;IACD,6CAA6C;IAC7C,OAAO,CACL,OAAO,GAAG,KAAK,QAAQ;QACvB,GAAG,KAAK,IAAI;QACZ,OAAQ,GAAW,CAAC,SAAS,KAAK,UAAU;QAC5C,OAAQ,GAAW,CAAC,IAAI,KAAK,QAAQ,CACtC,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\nimport React, {\n createContext,\n PropsWithChildren,\n useCallback,\n useContext,\n useEffect,\n useState,\n} from \"react\";\nimport { ZodSchema } from \"zod\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\nimport {\n ComponentRegistry,\n TamboComponent,\n TamboTool,\n} from \"../model/component-metadata\";\n\nexport interface TamboRegistryContext {\n componentList: ComponentRegistry;\n toolRegistry: Record<string, TamboTool>;\n componentToolAssociations: Record<string, string[]>;\n registerComponent: (options: TamboComponent) => void;\n registerTool: (tool: TamboTool) => void;\n registerTools: (tools: TamboTool[]) => void;\n addToolAssociation: (componentName: string, tool: TamboTool) => void;\n}\n\nconst TamboRegistryContext = createContext<TamboRegistryContext>({\n componentList: {},\n toolRegistry: {},\n componentToolAssociations: {},\n /**\n *\n */\n registerComponent: () => {},\n /**\n *\n */\n registerTool: () => {},\n /**\n *\n */\n registerTools: () => {},\n /**\n *\n */\n addToolAssociation: () => {},\n});\n\nexport interface TamboRegistryProviderProps {\n /** The components to register */\n components?: TamboComponent[];\n}\n\n/**\n * The TamboRegistryProvider is a React provider that provides a component\n * registry to the descendants of the provider.\n * @param props - The props for the TamboRegistryProvider\n * @param props.children - The children to wrap\n * @param props.components - The components to register\n * @returns The TamboRegistryProvider component\n */\nexport const TamboRegistryProvider: React.FC<\n PropsWithChildren<TamboRegistryProviderProps>\n> = ({ children, components: userComponents }) => {\n const [componentList, setComponentList] = useState<ComponentRegistry>({});\n const [toolRegistry, setToolRegistry] = useState<Record<string, TamboTool>>(\n {},\n );\n const [componentToolAssociations, setComponentToolAssociations] = useState<\n Record<string, string[]>\n >({});\n\n const registerTool = useCallback(\n (tool: TamboTool, warnOnOverwrite = true) => {\n setToolRegistry((prev) => {\n if (prev[tool.name] && warnOnOverwrite) {\n console.warn(`Overwriting tool ${tool.name}`);\n }\n return {\n ...prev,\n [tool.name]: tool,\n };\n });\n },\n [],\n );\n\n const registerTools = useCallback(\n (tools: TamboTool[], warnOnOverwrite = true) => {\n tools.forEach((tool) => registerTool(tool, warnOnOverwrite));\n },\n [registerTool],\n );\n\n const addToolAssociation = useCallback(\n (componentName: string, tool: TamboTool) => {\n if (!componentList[componentName]) {\n throw new Error(`Component ${componentName} not found in registry`);\n }\n setComponentToolAssociations((prev) => ({\n ...prev,\n [componentName]: [...(prev[componentName] || []), tool.name],\n }));\n },\n [componentList],\n );\n\n const registerComponent = useCallback(\n (options: TamboComponent, warnOnOverwrite = true) => {\n const {\n name,\n description,\n component,\n propsSchema,\n propsDefinition,\n loadingComponent,\n associatedTools,\n } = options;\n\n // Validate that at least one props definition is provided\n if (!propsSchema && !propsDefinition) {\n throw new Error(\n `Component ${name} must have either propsSchema (recommended) or propsDefinition defined`,\n );\n }\n\n // Validate that only one props definition is provided\n if (propsSchema && propsDefinition) {\n throw new Error(\n `Component ${name} cannot have both propsSchema and propsDefinition defined. Use only one. We recommend using propsSchema.`,\n );\n }\n\n // Convert propsSchema to JSON Schema if it exists\n const props = getSerializedProps(propsDefinition, propsSchema, name);\n\n setComponentList((prev) => {\n if (prev[name] && warnOnOverwrite) {\n console.warn(`overwriting component ${name}`);\n }\n return {\n ...prev,\n [name]: {\n component,\n loadingComponent,\n name,\n description,\n props,\n contextTools: [],\n },\n };\n });\n if (associatedTools) {\n registerTools(associatedTools);\n setComponentToolAssociations((prev) => ({\n ...prev,\n [name]: associatedTools.map((tool) => tool.name),\n }));\n }\n },\n [registerTools],\n );\n useEffect(() => {\n if (userComponents) {\n userComponents.forEach((component) => {\n registerComponent(component, false);\n });\n }\n }, [registerComponent, userComponents]);\n\n const value = {\n componentList,\n toolRegistry,\n componentToolAssociations,\n registerComponent,\n registerTool,\n registerTools,\n addToolAssociation,\n };\n\n return (\n <TamboRegistryContext.Provider value={value}>\n {children}\n </TamboRegistryContext.Provider>\n );\n};\n\n/**\n * The useTamboRegistry hook provides access to the component registry\n * to the descendants of the TamboRegistryProvider.\n * @returns The component registry\n */\nexport const useTamboRegistry = () => {\n return useContext(TamboRegistryContext);\n};\nfunction getSerializedProps(\n propsDefinition: any,\n propsSchema: any,\n name: string,\n) {\n if (propsDefinition) {\n console.warn(`propsDefinition is deprecated. Use propsSchema instead.`);\n return propsDefinition;\n }\n\n if (isZodSchema(propsSchema)) {\n try {\n return zodToJsonSchema(propsSchema);\n } catch (error) {\n console.error(\n `Error converting ${name} props schema to JSON Schema:`,\n error,\n );\n }\n }\n // try to roughly detect JSONSchema, should always be an object with a properties key\n if (isJSONSchema(propsSchema)) {\n return propsSchema;\n }\n\n throw new Error(`Invalid props schema for ${name}`);\n}\n\n/**\n * Checks if the propsSchema is a JSON Schema. This is a rough check, and the\n * server will provide the definitive check.\n * @param propsSchema - The props schema to check\n * @returns True if the props schema is a JSON Schema, false otherwise\n */\nfunction isJSONSchema(propsSchema: any) {\n return (\n propsSchema &&\n typeof propsSchema === \"object\" &&\n propsSchema.type === \"object\" &&\n propsSchema.properties\n );\n}\n\n/**\n * Since we require a certain zod version, we need to check if the object is a ZodSchema\n * @param obj - The object to check\n * @returns True if the object is a ZodSchema, false otherwise\n */\nfunction isZodSchema(obj: unknown): obj is ZodSchema {\n if (obj instanceof ZodSchema) {\n return true;\n }\n // try to detect if the object is a ZodSchema\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n typeof (obj as any).safeParse === \"function\" &&\n typeof (obj as any)._def === \"object\"\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"tambo-registry-provider.js","sourceRoot":"","sources":["../../src/providers/tambo-registry-provider.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;AACb,OAAO,KAAK,EAAE,EACZ,aAAa,EAEb,WAAW,EACX,UAAU,EACV,SAAS,EACT,QAAQ,GACT,MAAM,OAAO,CAAC;AACf,OAAO,EAAE,SAAS,EAAE,MAAM,KAAK,CAAC;AAChC,OAAO,eAAe,MAAM,oBAAoB,CAAC;AAiBjD,MAAM,oBAAoB,GAAG,aAAa,CAAuB;IAC/D,aAAa,EAAE,EAAE;IACjB,YAAY,EAAE,EAAE;IAChB,yBAAyB,EAAE,EAAE;IAC7B;;OAEG;IACH,iBAAiB,EAAE,GAAG,EAAE,GAAE,CAAC;IAC3B;;OAEG;IACH,YAAY,EAAE,GAAG,EAAE,GAAE,CAAC;IACtB;;OAEG;IACH,aAAa,EAAE,GAAG,EAAE,GAAE,CAAC;IACvB;;OAEG;IACH,kBAAkB,EAAE,GAAG,EAAE,GAAE,CAAC;CAC7B,CAAC,CAAC;AASH;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAE9B,CAAC,EAAE,QAAQ,EAAE,UAAU,EAAE,cAAc,EAAE,KAAK,EAAE,SAAS,EAAE,EAAE,EAAE;IACjE,MAAM,C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IAAI,CAAC;YACH,OAAO,eAAe,CAAC,WAAW,CAAC,CAAC;QACtC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CACX,oBAAoB,IAAI,+BAA+B,EACvD,KAAK,CACN,CAAC;QACJ,CAAC;IACH,CAAC;IACD,qFAAqF;IACrF,IAAI,YAAY,CAAC,WAAW,CAAC,EAAE,CAAC;QAC9B,OAAO,WAAW,CAAC;IACrB,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,4BAA4B,IAAI,EAAE,CAAC,CAAC;AACtD,CAAC;AAED;;;;;GAKG;AACH,SAAS,YAAY,CAAC,WAAgB;IACpC,OAAO,CACL,WAAW;QACX,OAAO,WAAW,KAAK,QAAQ;QAC/B,WAAW,CAAC,IAAI,KAAK,QAAQ;QAC7B,WAAW,CAAC,UAAU,CACvB,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,WAAW,CAAC,GAAY;IAC/B,IAAI,GAAG,YAAY,SAAS,EAAE,CAAC;QAC7B,OAAO,IAAI,CAAC;IACd,CAAC;IACD,6CAA6C;IAC7C,OAAO,CACL,OAAO,GAAG,KAAK,QAAQ;QACvB,GAAG,KAAK,IAAI;QACZ,OAAQ,GAAW,CAAC,SAAS,KAAK,UAAU;QAC5C,OAAQ,GAAW,CAAC,IAAI,KAAK,QAAQ,CACtC,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\nimport React, {\n createContext,\n PropsWithChildren,\n useCallback,\n useContext,\n useEffect,\n useState,\n} from \"react\";\nimport { ZodSchema } from \"zod\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\nimport {\n ComponentRegistry,\n TamboComponent,\n TamboTool,\n} from \"../model/component-metadata\";\n\nexport interface TamboRegistryContext {\n componentList: ComponentRegistry;\n toolRegistry: Record<string, TamboTool>;\n componentToolAssociations: Record<string, string[]>;\n registerComponent: (options: TamboComponent) => void;\n registerTool: (tool: TamboTool) => void;\n registerTools: (tools: TamboTool[]) => void;\n addToolAssociation: (componentName: string, tool: TamboTool) => void;\n}\n\nconst TamboRegistryContext = createContext<TamboRegistryContext>({\n componentList: {},\n toolRegistry: {},\n componentToolAssociations: {},\n /**\n *\n */\n registerComponent: () => {},\n /**\n *\n */\n registerTool: () => {},\n /**\n *\n */\n registerTools: () => {},\n /**\n *\n */\n addToolAssociation: () => {},\n});\n\nexport interface TamboRegistryProviderProps {\n /** The components to register */\n components?: TamboComponent[];\n /** The tools to register */\n tools?: TamboTool[];\n}\n\n/**\n * The TamboRegistryProvider is a React provider that provides a component\n * registry to the descendants of the provider.\n * @param props - The props for the TamboRegistryProvider\n * @param props.children - The children to wrap\n * @param props.components - The components to register\n * @param props.tools - The tools to register\n * @returns The TamboRegistryProvider component\n */\nexport const TamboRegistryProvider: React.FC<\n PropsWithChildren<TamboRegistryProviderProps>\n> = ({ children, components: userComponents, tools: userTools }) => {\n const [componentList, setComponentList] = useState<ComponentRegistry>({});\n const [toolRegistry, setToolRegistry] = useState<Record<string, TamboTool>>(\n {},\n );\n const [componentToolAssociations, setComponentToolAssociations] = useState<\n Record<string, string[]>\n >({});\n\n const registerTool = useCallback(\n (tool: TamboTool, warnOnOverwrite = true) => {\n setToolRegistry((prev) => {\n if (prev[tool.name] && warnOnOverwrite) {\n console.warn(`Overwriting tool ${tool.name}`);\n }\n return {\n ...prev,\n [tool.name]: tool,\n };\n });\n },\n [],\n );\n\n const registerTools = useCallback(\n (tools: TamboTool[], warnOnOverwrite = true) => {\n tools.forEach((tool) => registerTool(tool, warnOnOverwrite));\n },\n [registerTool],\n );\n\n const addToolAssociation = useCallback(\n (componentName: string, tool: TamboTool) => {\n if (!componentList[componentName]) {\n throw new Error(`Component ${componentName} not found in registry`);\n }\n setComponentToolAssociations((prev) => ({\n ...prev,\n [componentName]: [...(prev[componentName] || []), tool.name],\n }));\n },\n [componentList],\n );\n\n const registerComponent = useCallback(\n (options: TamboComponent, warnOnOverwrite = true) => {\n const {\n name,\n description,\n component,\n propsSchema,\n propsDefinition,\n loadingComponent,\n associatedTools,\n } = options;\n\n // Validate that at least one props definition is provided\n if (!propsSchema && !propsDefinition) {\n throw new Error(\n `Component ${name} must have either propsSchema (recommended) or propsDefinition defined`,\n );\n }\n\n // Validate that only one props definition is provided\n if (propsSchema && propsDefinition) {\n throw new Error(\n `Component ${name} cannot have both propsSchema and propsDefinition defined. Use only one. We recommend using propsSchema.`,\n );\n }\n\n // Convert propsSchema to JSON Schema if it exists\n const props = getSerializedProps(propsDefinition, propsSchema, name);\n\n setComponentList((prev) => {\n if (prev[name] && warnOnOverwrite) {\n console.warn(`overwriting component ${name}`);\n }\n return {\n ...prev,\n [name]: {\n component,\n loadingComponent,\n name,\n description,\n props,\n contextTools: [],\n },\n };\n });\n if (associatedTools) {\n registerTools(associatedTools);\n setComponentToolAssociations((prev) => ({\n ...prev,\n [name]: associatedTools.map((tool) => tool.name),\n }));\n }\n },\n [registerTools],\n );\n useEffect(() => {\n if (userComponents) {\n userComponents.forEach((component) => {\n registerComponent(component, false);\n });\n }\n }, [registerComponent, userComponents]);\n\n useEffect(() => {\n if (userTools) {\n registerTools(userTools, false);\n }\n }, [registerTools, userTools]);\n\n const value = {\n componentList,\n toolRegistry,\n componentToolAssociations,\n registerComponent,\n registerTool,\n registerTools,\n addToolAssociation,\n };\n\n return (\n <TamboRegistryContext.Provider value={value}>\n {children}\n </TamboRegistryContext.Provider>\n );\n};\n\n/**\n * The useTamboRegistry hook provides access to the component registry\n * to the descendants of the TamboRegistryProvider.\n * @returns The component registry\n */\nexport const useTamboRegistry = () => {\n return useContext(TamboRegistryContext);\n};\nfunction getSerializedProps(\n propsDefinition: any,\n propsSchema: any,\n name: string,\n) {\n if (propsDefinition) {\n console.warn(`propsDefinition is deprecated. Use propsSchema instead.`);\n return propsDefinition;\n }\n\n if (isZodSchema(propsSchema)) {\n try {\n return zodToJsonSchema(propsSchema);\n } catch (error) {\n console.error(\n `Error converting ${name} props schema to JSON Schema:`,\n error,\n );\n }\n }\n // try to roughly detect JSONSchema, should always be an object with a properties key\n if (isJSONSchema(propsSchema)) {\n return propsSchema;\n }\n\n throw new Error(`Invalid props schema for ${name}`);\n}\n\n/**\n * Checks if the propsSchema is a JSON Schema. This is a rough check, and the\n * server will provide the definitive check.\n * @param propsSchema - The props schema to check\n * @returns True if the props schema is a JSON Schema, false otherwise\n */\nfunction isJSONSchema(propsSchema: any) {\n return (\n propsSchema &&\n typeof propsSchema === \"object\" &&\n propsSchema.type === \"object\" &&\n propsSchema.properties\n );\n}\n\n/**\n * Since we require a certain zod version, we need to check if the object is a ZodSchema\n * @param obj - The object to check\n * @returns True if the object is a ZodSchema, false otherwise\n */\nfunction isZodSchema(obj: unknown): obj is ZodSchema {\n if (obj instanceof ZodSchema) {\n return true;\n }\n // try to detect if the object is a ZodSchema\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n typeof (obj as any).safeParse === \"function\" &&\n typeof (obj as any)._def === \"object\"\n );\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tambo-thread-provider.d.ts","sourceRoot":"","sources":["../../src/providers/tambo-thread-provider.tsx"],"names":[],"mappings":"AACA,OAAO,OAA0B,MAAM,0BAA0B,CAAC;AAClE,OAAO,KAAK,EAAE,EAEZ,iBAAiB,EAMlB,MAAM,OAAO,CAAC;AACf,OAAO,EACL,eAAe,EAEf,kBAAkB,EACnB,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAYpD,MAAM,WAAW,uBAAuB;IACtC,yBAAyB;IACzB,MAAM,EAAE,WAAW,CAAC;IACpB,mCAAmC;IACnC,mBAAmB,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;IACjE,yBAAyB;IACzB,cAAc,EAAE,MAAM,IAAI,CAAC;IAC3B,0CAA0C;IAC1C,gBAAgB,EAAE,CAChB,OAAO,EAAE,kBAAkB,EAC3B,YAAY,EAAE,OAAO,KAClB,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC,CAAC;IACnD,6CAA6C;IAC7C,mBAAmB,EAAE,CACnB,EAAE,EAAE,MAAM,EACV,OAAO,EAAE,kBAAkB,EAC3B,YAAY,EAAE,OAAO,KAClB,OAAO,CAAC,IAAI,CAAC,CAAC;IACnB,4CAA4C;IAC5C,UAAU,EAAE,MAAM,CAAC;IACnB,gDAAgD;IAChD,aAAa,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IACvC,2CAA2C;IAC3C,iBAAiB,EAAE,CACjB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE;QACP,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,cAAc,CAAC,EAAE,OAAO,CAAC;QACzB,UAAU,CAAC,EAAE,MAAM,CAAC;KACrB,KACE,OAAO,CAAC,kBAAkB,CAAC,CAAC;IACjC,oFAAoF;IACpF,eAAe,EAAE,eAAe,CAAC;IACjC,6FAA6F;IAC7F,uBAAuB,EAAE,MAAM,CAAC;IAChC,iCAAiC;IACjC,MAAM,EAAE,OAAO,CAAC;CACjB;AAED;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,EAAE,WAOhC,CAAC;AAEF,eAAO,MAAM,kBAAkB,wCA0C7B,CAAC;AAEH;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB,EAAE,KAAK,CAAC,EAAE,CAAC,iBAAiB,
|
|
1
|
+
{"version":3,"file":"tambo-thread-provider.d.ts","sourceRoot":"","sources":["../../src/providers/tambo-thread-provider.tsx"],"names":[],"mappings":"AACA,OAAO,OAA0B,MAAM,0BAA0B,CAAC;AAClE,OAAO,KAAK,EAAE,EAEZ,iBAAiB,EAMlB,MAAM,OAAO,CAAC;AACf,OAAO,EACL,eAAe,EAEf,kBAAkB,EACnB,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAA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,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,cAAc,+BAM1B,CAAC"}
|
|
@@ -136,13 +136,23 @@ export const TamboThreadProvider = ({ children, }) => {
|
|
|
136
136
|
createdAt,
|
|
137
137
|
};
|
|
138
138
|
const threadId = message.threadId;
|
|
139
|
+
const messageId = chatMessage.id;
|
|
139
140
|
// optimistically update the thread in the local state
|
|
140
141
|
setThreadMap((prevMap) => {
|
|
141
142
|
if (!threadId) {
|
|
142
143
|
return prevMap;
|
|
143
144
|
}
|
|
144
145
|
const prevMessages = prevMap[threadId]?.messages || [];
|
|
145
|
-
const
|
|
146
|
+
const haveMessage = prevMessages.find((msg) => msg.id === messageId);
|
|
147
|
+
// Update in place if the message already exists
|
|
148
|
+
const updatedMessages = haveMessage
|
|
149
|
+
? prevMessages.map((msg) => {
|
|
150
|
+
if (msg.id === messageId) {
|
|
151
|
+
return chatMessage;
|
|
152
|
+
}
|
|
153
|
+
return msg;
|
|
154
|
+
})
|
|
155
|
+
: [...prevMessages, chatMessage];
|
|
146
156
|
const updatedThreadMap = {
|
|
147
157
|
...prevMap,
|
|
148
158
|
[threadId]: {
|
|
@@ -195,17 +205,6 @@ export const TamboThreadProvider = ({ children, }) => {
|
|
|
195
205
|
});
|
|
196
206
|
}
|
|
197
207
|
}, [client.beta.threads.messages]);
|
|
198
|
-
const deleteThreadMessage = useCallback((messageId, threadId) => {
|
|
199
|
-
if (!threadMap[threadId])
|
|
200
|
-
return;
|
|
201
|
-
setThreadMap((prevMap) => ({
|
|
202
|
-
...prevMap,
|
|
203
|
-
[threadId]: {
|
|
204
|
-
...prevMap[threadId],
|
|
205
|
-
messages: prevMap[threadId].messages.filter((msg) => msg.id !== messageId),
|
|
206
|
-
},
|
|
207
|
-
}));
|
|
208
|
-
}, [threadMap]);
|
|
209
208
|
const startNewThread = useCallback(() => {
|
|
210
209
|
setCurrentThreadId(PLACEHOLDER_THREAD.id);
|
|
211
210
|
setThreadMap((prevMap) => {
|
|
@@ -238,7 +237,7 @@ export const TamboThreadProvider = ({ children, }) => {
|
|
|
238
237
|
if (fetch) {
|
|
239
238
|
await fetchThread(threadId);
|
|
240
239
|
}
|
|
241
|
-
}, [fetchThread
|
|
240
|
+
}, [fetchThread]);
|
|
242
241
|
const updateThreadStatus = useCallback((threadId, stage, statusMessage) => {
|
|
243
242
|
setThreadMap((prevMap) => {
|
|
244
243
|
const updatedThreadMap = {
|
|
@@ -252,16 +251,11 @@ export const TamboThreadProvider = ({ children, }) => {
|
|
|
252
251
|
return updatedThreadMap;
|
|
253
252
|
});
|
|
254
253
|
}, []);
|
|
255
|
-
const handleAdvanceStream = useCallback(async (stream, params, threadId
|
|
254
|
+
const handleAdvanceStream = useCallback(async (stream, params, threadId) => {
|
|
256
255
|
let finalMessage;
|
|
257
256
|
let hasSetThreadId = false;
|
|
258
|
-
let isFirstChunk = true;
|
|
259
257
|
updateThreadStatus(threadId, GenerationStage.STREAMING_RESPONSE);
|
|
260
258
|
for await (const chunk of stream) {
|
|
261
|
-
if (isFirstChunk && messageIdToRemove) {
|
|
262
|
-
deleteThreadMessage(messageIdToRemove, threadId);
|
|
263
|
-
}
|
|
264
|
-
isFirstChunk = false;
|
|
265
259
|
if (chunk.responseMessageDto.toolCallRequest) {
|
|
266
260
|
updateThreadStatus(chunk.responseMessageDto.threadId, GenerationStage.FETCHING_CONTEXT);
|
|
267
261
|
const toolCallResponse = await handleToolCall(chunk.responseMessageDto, toolRegistry);
|
|
@@ -287,20 +281,26 @@ export const TamboThreadProvider = ({ children, }) => {
|
|
|
287
281
|
chunk.responseMessageDto.threadId &&
|
|
288
282
|
chunk.responseMessageDto.threadId !== currentThread?.id) {
|
|
289
283
|
hasSetThreadId = true;
|
|
290
|
-
switchCurrentThread(chunk.responseMessageDto.threadId, false);
|
|
284
|
+
await switchCurrentThread(chunk.responseMessageDto.threadId, false);
|
|
291
285
|
}
|
|
292
286
|
if (!finalMessage) {
|
|
293
287
|
finalMessage = chunk.responseMessageDto.component?.componentName
|
|
294
288
|
? renderComponentIntoMessage(chunk.responseMessageDto, componentList)
|
|
295
289
|
: chunk.responseMessageDto;
|
|
296
|
-
addThreadMessage(finalMessage, false);
|
|
290
|
+
await addThreadMessage(finalMessage, false);
|
|
297
291
|
}
|
|
298
292
|
else {
|
|
299
|
-
|
|
293
|
+
// if we start getting a new message mid-stream, put the previous one on screen
|
|
294
|
+
const isNewMessage = chunk.responseMessageDto.id !== finalMessage.id;
|
|
300
295
|
finalMessage = chunk.responseMessageDto.component?.componentName
|
|
301
296
|
? renderComponentIntoMessage(chunk.responseMessageDto, componentList)
|
|
302
297
|
: chunk.responseMessageDto;
|
|
303
|
-
|
|
298
|
+
if (isNewMessage) {
|
|
299
|
+
await addThreadMessage(finalMessage, false);
|
|
300
|
+
}
|
|
301
|
+
else {
|
|
302
|
+
await updateThreadMessage(finalMessage.id, finalMessage, false);
|
|
303
|
+
}
|
|
304
304
|
}
|
|
305
305
|
}
|
|
306
306
|
}
|
|
@@ -308,7 +308,7 @@ export const TamboThreadProvider = ({ children, }) => {
|
|
|
308
308
|
return (finalMessage ?? {
|
|
309
309
|
threadId: "",
|
|
310
310
|
content: [{ type: "text", text: `Error processing stream` }],
|
|
311
|
-
role: "
|
|
311
|
+
role: "assistant",
|
|
312
312
|
createdAt: new Date().toISOString(),
|
|
313
313
|
id: crypto.randomUUID(),
|
|
314
314
|
componentState: {},
|
|
@@ -318,8 +318,6 @@ export const TamboThreadProvider = ({ children, }) => {
|
|
|
318
318
|
client,
|
|
319
319
|
componentList,
|
|
320
320
|
currentThread?.id,
|
|
321
|
-
deleteThreadMessage,
|
|
322
|
-
fetchThread,
|
|
323
321
|
switchCurrentThread,
|
|
324
322
|
toolRegistry,
|
|
325
323
|
updateThreadMessage,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tambo-thread-provider.js","sourceRoot":"","sources":["../../src/providers/tambo-thread-provider.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;AACb,OAAgB,EAAE,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E;YAC3D,MAAM,EAAE,WAAW,CACjB,CAAC,aAAa,EAAE,eAAe;gBAC7B,eAAe,CAAC,IAAI,CAAoB,CAC3C;SACF,IAEA,QAAQ,CACmB,CAC/B,CAAC;AACJ,CAAC,CAAC;AAEF;;;;GAIG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,GAAG,EAAE;IACjC,MAAM,OAAO,GAAG,UAAU,CAAC,kBAAkB,CAAC,CAAC;IAC/C,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC;IAC9E,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC,CAAC","sourcesContent":["\"use client\";\nimport TamboAI, { advanceStream } from \"@tambo-ai/typescript-sdk\";\nimport React, {\n createContext,\n PropsWithChildren,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from \"react\";\nimport {\n GenerationStage,\n isIdleStage,\n TamboThreadMessage,\n} from \"../model/generate-component-response\";\nimport { TamboThread } from \"../model/tambo-thread\";\nimport { renderComponentIntoMessage } from \"../util/generate-component\";\nimport {\n getAvailableComponents,\n getClientContext,\n getUnassociatedTools,\n mapTamboToolToContextTool,\n} from \"../util/registry\";\nimport { handleToolCall } from \"../util/tool-caller\";\nimport { useTamboClient } from \"./tambo-client-provider\";\nimport { useTamboRegistry } from \"./tambo-registry-provider\";\n\nexport interface TamboThreadContextProps {\n /** The current thread */\n thread: TamboThread;\n /** Switch to a different thread */\n switchCurrentThread: (threadId: string, fetch?: boolean) => void;\n /** Start a new thread */\n startNewThread: () => void;\n /** Add a message to the current thread */\n addThreadMessage: (\n message: TamboThreadMessage,\n sendToServer: boolean,\n ) => Promise<TamboAI.Beta.Threads.ThreadMessage[]>;\n /** Update a message in the current thread */\n updateThreadMessage: (\n id: string,\n message: TamboThreadMessage,\n sendToServer: boolean,\n ) => Promise<void>;\n /** The input value of the current thread */\n inputValue: string;\n /** Set the input value of the current thread */\n setInputValue: (value: string) => void;\n /** Send a message to the current thread */\n sendThreadMessage: (\n message: string,\n options: {\n threadId?: string;\n streamResponse?: boolean;\n contextKey?: string;\n },\n ) => Promise<TamboThreadMessage>;\n /** The generation stage of the current thread - updated as the thread progresses */\n generationStage: GenerationStage;\n /** The generation status message of the current thread - updated as the thread progresses */\n generationStatusMessage: string;\n /** Whether the thread is idle */\n isIdle: boolean;\n}\n\n/**\n * This is a stub entry for when the thread is not yet created, the first time\n * the user sends a message\n *\n * Note that the consumer needs to be careful never to send `PLACEHOLDER_THREAD.id` to the server,\n * as this doesn't really exist on the server side.\n */\nexport const PLACEHOLDER_THREAD: TamboThread = {\n id: \"placeholder\",\n messages: [],\n createdAt: \"\",\n projectId: \"\",\n updatedAt: \"\",\n metadata: {},\n};\n\nexport const TamboThreadContext = createContext<TamboThreadContextProps>({\n thread: PLACEHOLDER_THREAD,\n /**\n *\n */\n switchCurrentThread: () => {\n throw new Error(\"switchCurrentThread not implemented\");\n },\n /**\n *\n */\n startNewThread: () => {\n throw new Error(\"startNewThread not implemented\");\n },\n /**\n *\n */\n addThreadMessage: () => {\n throw new Error(\"updateThreadMessageHistory not implemented\");\n },\n inputValue: \"\",\n /**\n *\n */\n setInputValue: () => {\n throw new Error(\"setInputValue not implemented\");\n },\n /**\n *\n */\n updateThreadMessage: () => {\n throw new Error(\"updateThreadMessage not implemented\");\n },\n /**\n *\n */\n sendThreadMessage: () => {\n throw new Error(\"advance not implemented\");\n },\n generationStage: GenerationStage.IDLE,\n generationStatusMessage: \"\",\n isIdle: true,\n});\n\n/**\n * The TamboThreadProvider is a React provider that provides a thread context\n * to the descendants of the provider.\n * @param props - The props for the TamboThreadProvider\n * @param props.children - The children to wrap\n * @returns The TamboThreadProvider component\n */\nexport const TamboThreadProvider: React.FC<PropsWithChildren> = ({\n children,\n}) => {\n const [threadMap, setThreadMap] = useState<Record<string, TamboThread>>({\n [PLACEHOLDER_THREAD.id]: PLACEHOLDER_THREAD,\n });\n const client = useTamboClient();\n const { componentList, toolRegistry, componentToolAssociations } =\n useTamboRegistry();\n const [inputValue, setInputValue] = useState(\"\");\n\n const [currentThreadId, setCurrentThreadId] = useState<string>(\n PLACEHOLDER_THREAD.id,\n );\n const currentThread: TamboThread | undefined = threadMap[currentThreadId];\n\n // Use existing messages from the current thread to avoid re-generating any components\n const currentMessageCache = useMemo(() => {\n const messageCache = new Map<string, TamboThreadMessage>();\n if (currentThread) {\n for (const message of currentThread.messages) {\n messageCache.set(message.id, message);\n }\n }\n return messageCache;\n }, [currentThread]);\n\n const fetchThread = useCallback(\n async (threadId: string) => {\n const thread = await client.beta.threads.retrieve(threadId);\n const threadWithRenderedComponents = {\n ...thread,\n messages: thread.messages.map((message) => {\n if (currentMessageCache.has(message.id)) {\n const renderedMessage = currentMessageCache.get(message.id);\n return {\n ...renderedMessage,\n ...message,\n };\n }\n if (message.component?.componentName) {\n const messageWithComponent = renderComponentIntoMessage(\n message,\n componentList,\n );\n return messageWithComponent;\n }\n return message;\n }),\n };\n\n setThreadMap((prevMap) => {\n const updatedThreadMap = {\n ...prevMap,\n [threadId]: threadWithRenderedComponents,\n };\n return updatedThreadMap;\n });\n },\n [client.beta.threads, componentList, currentMessageCache],\n );\n\n useEffect(() => {\n if (\n currentThreadId &&\n currentThreadId !== PLACEHOLDER_THREAD.id &&\n !threadMap[currentThreadId]\n ) {\n fetchThread(currentThreadId);\n }\n }, [currentThreadId, fetchThread, threadMap]);\n\n const addThreadMessage = useCallback(\n async (\n message: TamboThreadMessage,\n sendToServer = true,\n createdAt: string = new Date().toISOString(),\n ) => {\n if (!currentThread) {\n console.warn(\"Cannot add messages if we do not have a current thread\");\n return [];\n }\n const chatMessage: TamboThreadMessage & {\n additionalContext?: string;\n } = {\n ...message,\n additionalContext:\n message.role === \"user\" ? getClientContext() : undefined,\n createdAt,\n };\n const threadId = message.threadId;\n // optimistically update the thread in the local state\n setThreadMap((prevMap) => {\n if (!threadId) {\n return prevMap;\n }\n const prevMessages = prevMap[threadId]?.messages || [];\n const updatedMessages = [...prevMessages, chatMessage];\n\n const updatedThreadMap = {\n ...prevMap,\n [threadId]: {\n ...prevMap[threadId],\n messages: updatedMessages,\n },\n };\n return updatedThreadMap;\n });\n\n if (sendToServer) {\n // TODO: if this fails, we need to revert the local state update\n await client.beta.threads.messages.create(message.threadId, {\n content: message.content,\n role: message.role,\n // additionalContext: chatMessage.additionalContext,\n });\n }\n return threadMap[threadId]?.messages || [];\n },\n [client.beta.threads.messages, currentThread, threadMap],\n );\n\n const updateThreadMessage = useCallback(\n async (\n id: string,\n message: TamboThreadMessage,\n sendToServer = true,\n createdAt: string = new Date().toISOString(),\n ) => {\n const chatMessage: TamboThreadMessage = {\n ...message,\n createdAt,\n };\n\n setThreadMap((prevMap) => {\n if (!message.threadId) {\n return prevMap;\n }\n const prevMessages = prevMap[message.threadId]?.messages || [];\n const updatedMessages = prevMessages.map((msg) => {\n if (msg.id === id) {\n return chatMessage;\n }\n return msg;\n });\n return {\n ...prevMap,\n [message.threadId]: {\n ...prevMap[message.threadId],\n messages: updatedMessages,\n },\n };\n });\n if (sendToServer) {\n // TODO: if this fails, we need to revert the local state update\n await client.beta.threads.messages.create(message.threadId, {\n content: message.content,\n role: message.role,\n // additionalContext: chatMessage.additionalContext,\n });\n }\n },\n [client.beta.threads.messages],\n );\n\n const deleteThreadMessage = useCallback(\n (messageId: string, threadId: string) => {\n if (!threadMap[threadId]) return;\n\n setThreadMap((prevMap) => ({\n ...prevMap,\n [threadId]: {\n ...prevMap[threadId],\n messages: prevMap[threadId].messages.filter(\n (msg) => msg.id !== messageId,\n ),\n },\n }));\n },\n [threadMap],\n );\n\n const startNewThread = useCallback(() => {\n setCurrentThreadId(PLACEHOLDER_THREAD.id);\n setThreadMap((prevMap) => {\n return {\n ...prevMap,\n [PLACEHOLDER_THREAD.id]: PLACEHOLDER_THREAD,\n };\n });\n }, []);\n\n const switchCurrentThread = useCallback(\n async (threadId: string, fetch = true) => {\n if (threadId === PLACEHOLDER_THREAD.id) {\n console.warn(\"Switching to placeholder thread, may be a bug.\");\n return;\n }\n setCurrentThreadId(threadId);\n setThreadMap((prevMap) => {\n if (prevMap[threadId]) {\n return prevMap;\n }\n // If this is a new thread, add placeholder thread messages to the thread\n const updatedThreadMap = {\n ...prevMap,\n [threadId]: {\n ...prevMap[PLACEHOLDER_THREAD.id],\n id: threadId,\n },\n };\n return updatedThreadMap;\n });\n if (fetch) {\n await fetchThread(threadId);\n }\n },\n [fetchThread, threadMap],\n );\n\n const updateThreadStatus = useCallback(\n (threadId: string, stage: GenerationStage, statusMessage?: string) => {\n setThreadMap((prevMap) => {\n const updatedThreadMap = {\n ...prevMap,\n [threadId]: {\n ...prevMap[threadId],\n generationStage: stage,\n statusMessage: statusMessage,\n },\n };\n return updatedThreadMap;\n });\n },\n [],\n );\n\n const handleAdvanceStream = useCallback(\n async (\n stream: AsyncIterable<TamboAI.Beta.Threads.ThreadAdvanceResponse>,\n params: TamboAI.Beta.Threads.ThreadAdvanceParams,\n threadId: string,\n messageIdToRemove?: string,\n ): Promise<TamboThreadMessage> => {\n let finalMessage: TamboThreadMessage | undefined;\n let hasSetThreadId = false;\n let isFirstChunk = true;\n updateThreadStatus(threadId, GenerationStage.STREAMING_RESPONSE);\n\n for await (const chunk of stream) {\n if (isFirstChunk && messageIdToRemove) {\n deleteThreadMessage(messageIdToRemove, threadId);\n }\n isFirstChunk = false;\n\n if (chunk.responseMessageDto.toolCallRequest) {\n updateThreadStatus(\n chunk.responseMessageDto.threadId,\n GenerationStage.FETCHING_CONTEXT,\n );\n const toolCallResponse = await handleToolCall(\n chunk.responseMessageDto,\n toolRegistry,\n );\n const toolCallResponseString =\n typeof toolCallResponse === \"string\"\n ? toolCallResponse\n : JSON.stringify(toolCallResponse);\n const toolCallResponseParams: TamboAI.Beta.Threads.ThreadAdvanceParams =\n {\n ...params,\n messageToAppend: {\n content: [{ type: \"text\", text: toolCallResponseString }],\n role: \"tool\",\n actionType: \"tool_response\",\n component: chunk.responseMessageDto.component,\n tool_call_id: chunk.responseMessageDto.tool_call_id,\n },\n };\n updateThreadStatus(\n chunk.responseMessageDto.threadId,\n GenerationStage.STREAMING_RESPONSE,\n );\n const toolCallResponseStream = await advanceStream(\n client,\n toolCallResponseParams,\n chunk.responseMessageDto.threadId,\n );\n\n return await handleAdvanceStream(\n toolCallResponseStream,\n toolCallResponseParams,\n chunk.responseMessageDto.threadId,\n );\n } else {\n if (\n !hasSetThreadId &&\n chunk.responseMessageDto.threadId &&\n chunk.responseMessageDto.threadId !== currentThread?.id\n ) {\n hasSetThreadId = true;\n switchCurrentThread(chunk.responseMessageDto.threadId, false);\n }\n\n if (!finalMessage) {\n finalMessage = chunk.responseMessageDto.component?.componentName\n ? renderComponentIntoMessage(\n chunk.responseMessageDto,\n componentList,\n )\n : chunk.responseMessageDto;\n addThreadMessage(finalMessage, false);\n } else {\n const previousId = finalMessage.id;\n finalMessage = chunk.responseMessageDto.component?.componentName\n ? renderComponentIntoMessage(\n chunk.responseMessageDto,\n componentList,\n )\n : chunk.responseMessageDto;\n updateThreadMessage(previousId, finalMessage, false);\n }\n }\n }\n\n updateThreadStatus(\n finalMessage?.threadId ?? threadId,\n GenerationStage.COMPLETE,\n );\n return (\n finalMessage ?? {\n threadId: \"\",\n content: [{ type: \"text\", text: `Error processing stream` }],\n role: \"hydra\",\n createdAt: new Date().toISOString(),\n id: crypto.randomUUID(),\n componentState: {},\n }\n );\n },\n [\n addThreadMessage,\n client,\n componentList,\n currentThread?.id,\n deleteThreadMessage,\n fetchThread,\n switchCurrentThread,\n toolRegistry,\n updateThreadMessage,\n updateThreadStatus,\n ],\n );\n\n const sendThreadMessage = useCallback(\n async (\n message: string,\n options: {\n threadId?: string;\n streamResponse?: boolean;\n contextKey?: string;\n } = { threadId: PLACEHOLDER_THREAD.id },\n ): Promise<TamboThreadMessage> => {\n const { threadId = currentThread.id, streamResponse } = options;\n updateThreadStatus(threadId, GenerationStage.CHOOSING_COMPONENT);\n\n addThreadMessage(\n {\n content: [{ type: \"text\", text: message }],\n renderedComponent: null,\n role: \"user\",\n threadId: threadId,\n id: crypto.randomUUID(),\n createdAt: new Date().toISOString(),\n componentState: {},\n },\n false,\n );\n\n const availableComponents = getAvailableComponents(\n componentList,\n toolRegistry,\n componentToolAssociations,\n );\n const unassociatedTools = getUnassociatedTools(\n toolRegistry,\n componentToolAssociations,\n );\n const params: TamboAI.Beta.Threads.ThreadAdvanceParams = {\n messageToAppend: {\n content: [{ type: \"text\", text: message }],\n role: \"user\",\n },\n contextKey: options.contextKey,\n availableComponents: availableComponents,\n clientTools: unassociatedTools.map((tool) =>\n mapTamboToolToContextTool(tool),\n ),\n };\n\n if (streamResponse) {\n const advanceStreamResponse = await advanceStream(\n client,\n params,\n threadId === PLACEHOLDER_THREAD.id ? undefined : threadId,\n );\n return await handleAdvanceStream(\n advanceStreamResponse,\n params,\n threadId,\n );\n }\n let advanceResponse = await (threadId === PLACEHOLDER_THREAD.id\n ? client.beta.threads.advance(params)\n : client.beta.threads.advanceById(threadId, params));\n\n //handle tool calls\n while (advanceResponse.responseMessageDto.toolCallRequest) {\n updateThreadStatus(threadId, GenerationStage.FETCHING_CONTEXT);\n const toolCallResponse = await handleToolCall(\n advanceResponse.responseMessageDto,\n toolRegistry,\n );\n const toolResponseString =\n typeof toolCallResponse === \"string\"\n ? toolCallResponse\n : JSON.stringify(toolCallResponse);\n const toolCallResponseParams: TamboAI.Beta.Threads.ThreadAdvanceParams =\n {\n ...params,\n messageToAppend: {\n ...params.messageToAppend,\n content: [{ type: \"text\", text: toolResponseString }],\n role: \"tool\",\n actionType: \"tool_response\",\n component: advanceResponse.responseMessageDto.component,\n tool_call_id: advanceResponse.responseMessageDto.tool_call_id,\n },\n };\n updateThreadStatus(threadId, GenerationStage.HYDRATING_COMPONENT);\n advanceResponse = await client.beta.threads.advanceById(\n advanceResponse.responseMessageDto.threadId,\n toolCallResponseParams,\n );\n }\n\n const finalMessage = advanceResponse.responseMessageDto.component\n ?.componentName\n ? renderComponentIntoMessage(\n advanceResponse.responseMessageDto,\n componentList,\n )\n : advanceResponse.responseMessageDto;\n await switchCurrentThread(advanceResponse.responseMessageDto.threadId);\n updateThreadStatus(\n advanceResponse.responseMessageDto.threadId,\n GenerationStage.COMPLETE,\n );\n return finalMessage;\n },\n [\n componentList,\n toolRegistry,\n componentToolAssociations,\n currentThread.id,\n switchCurrentThread,\n addThreadMessage,\n client,\n updateThreadStatus,\n handleAdvanceStream,\n ],\n );\n\n return (\n <TamboThreadContext.Provider\n value={{\n thread: currentThread,\n switchCurrentThread,\n startNewThread,\n addThreadMessage,\n updateThreadMessage,\n inputValue,\n setInputValue,\n sendThreadMessage,\n generationStage: (currentThread?.generationStage ??\n GenerationStage.IDLE) as GenerationStage,\n generationStatusMessage: currentThread?.statusMessage ?? \"\",\n isIdle: isIdleStage(\n (currentThread?.generationStage ??\n GenerationStage.IDLE) as GenerationStage,\n ),\n }}\n >\n {children}\n </TamboThreadContext.Provider>\n );\n};\n\n/**\n * The useTamboThread hook provides access to the current thread context\n * to the descendants of the TamboThreadProvider.\n * @returns All state and actions for the current thread\n */\nexport const useTamboThread = () => {\n const context = useContext(TamboThreadContext);\n if (context === undefined) {\n throw new Error(\"useTamboThread must be used within a TamboThreadProvider\");\n }\n return context;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"tambo-thread-provider.js","sourceRoot":"","sources":["../../src/providers/tambo-thread-provider.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;AACb,OAAgB,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,KAAK,EAAE,EACZ,aAAa,EAEb,WAAW,EACX,UAAU,EACV,SAAS,EACT,OAAO,EACP,QAAQ,GACT,MAAM,OAAO,CAAC;AACf,OAAO,EACL,eAAe,EACf,WAAW,GAEZ,MAAM,sCAAsC,CAAC;AAE9C,OAAO,EAAE,0BAA0B,EAAE,MAAM,4BAA4B,CAAC;AACxE,OAAO,EACL,sBAAsB,EACtB,gBAAgB,EAChB,oBA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AACjB,CAAC,CAAC","sourcesContent":["\"use client\";\nimport TamboAI, { advanceStream } from \"@tambo-ai/typescript-sdk\";\nimport React, {\n createContext,\n PropsWithChildren,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from \"react\";\nimport {\n GenerationStage,\n isIdleStage,\n TamboThreadMessage,\n} from \"../model/generate-component-response\";\nimport { TamboThread } from \"../model/tambo-thread\";\nimport { renderComponentIntoMessage } from \"../util/generate-component\";\nimport {\n getAvailableComponents,\n getClientContext,\n getUnassociatedTools,\n mapTamboToolToContextTool,\n} from \"../util/registry\";\nimport { handleToolCall } from \"../util/tool-caller\";\nimport { useTamboClient } from \"./tambo-client-provider\";\nimport { useTamboRegistry } from \"./tambo-registry-provider\";\n\nexport interface TamboThreadContextProps {\n /** The current thread */\n thread: TamboThread;\n /** Switch to a different thread */\n switchCurrentThread: (threadId: string, fetch?: boolean) => void;\n /** Start a new thread */\n startNewThread: () => void;\n /** Add a message to the current thread */\n addThreadMessage: (\n message: TamboThreadMessage,\n sendToServer: boolean,\n ) => Promise<TamboAI.Beta.Threads.ThreadMessage[]>;\n /** Update a message in the current thread */\n updateThreadMessage: (\n id: string,\n message: TamboThreadMessage,\n sendToServer: boolean,\n ) => Promise<void>;\n /** The input value of the current thread */\n inputValue: string;\n /** Set the input value of the current thread */\n setInputValue: (value: string) => void;\n /** Send a message to the current thread */\n sendThreadMessage: (\n message: string,\n options: {\n threadId?: string;\n streamResponse?: boolean;\n contextKey?: string;\n },\n ) => Promise<TamboThreadMessage>;\n /** The generation stage of the current thread - updated as the thread progresses */\n generationStage: GenerationStage;\n /** The generation status message of the current thread - updated as the thread progresses */\n generationStatusMessage: string;\n /** Whether the thread is idle */\n isIdle: boolean;\n}\n\n/**\n * This is a stub entry for when the thread is not yet created, the first time\n * the user sends a message\n *\n * Note that the consumer needs to be careful never to send `PLACEHOLDER_THREAD.id` to the server,\n * as this doesn't really exist on the server side.\n */\nexport const PLACEHOLDER_THREAD: TamboThread = {\n id: \"placeholder\",\n messages: [],\n createdAt: \"\",\n projectId: \"\",\n updatedAt: \"\",\n metadata: {},\n};\n\nexport const TamboThreadContext = createContext<TamboThreadContextProps>({\n thread: PLACEHOLDER_THREAD,\n /**\n *\n */\n switchCurrentThread: () => {\n throw new Error(\"switchCurrentThread not implemented\");\n },\n /**\n *\n */\n startNewThread: () => {\n throw new Error(\"startNewThread not implemented\");\n },\n /**\n *\n */\n addThreadMessage: () => {\n throw new Error(\"updateThreadMessageHistory not implemented\");\n },\n inputValue: \"\",\n /**\n *\n */\n setInputValue: () => {\n throw new Error(\"setInputValue not implemented\");\n },\n /**\n *\n */\n updateThreadMessage: () => {\n throw new Error(\"updateThreadMessage not implemented\");\n },\n /**\n *\n */\n sendThreadMessage: () => {\n throw new Error(\"advance not implemented\");\n },\n generationStage: GenerationStage.IDLE,\n generationStatusMessage: \"\",\n isIdle: true,\n});\n\n/**\n * The TamboThreadProvider is a React provider that provides a thread context\n * to the descendants of the provider.\n * @param props - The props for the TamboThreadProvider\n * @param props.children - The children to wrap\n * @returns The TamboThreadProvider component\n */\nexport const TamboThreadProvider: React.FC<PropsWithChildren> = ({\n children,\n}) => {\n const [threadMap, setThreadMap] = useState<Record<string, TamboThread>>({\n [PLACEHOLDER_THREAD.id]: PLACEHOLDER_THREAD,\n });\n const client = useTamboClient();\n const { componentList, toolRegistry, componentToolAssociations } =\n useTamboRegistry();\n const [inputValue, setInputValue] = useState(\"\");\n\n const [currentThreadId, setCurrentThreadId] = useState<string>(\n PLACEHOLDER_THREAD.id,\n );\n const currentThread: TamboThread | undefined = threadMap[currentThreadId];\n\n // Use existing messages from the current thread to avoid re-generating any components\n const currentMessageCache = useMemo(() => {\n const messageCache = new Map<string, TamboThreadMessage>();\n if (currentThread) {\n for (const message of currentThread.messages) {\n messageCache.set(message.id, message);\n }\n }\n return messageCache;\n }, [currentThread]);\n\n const fetchThread = useCallback(\n async (threadId: string) => {\n const thread = await client.beta.threads.retrieve(threadId);\n const threadWithRenderedComponents = {\n ...thread,\n messages: thread.messages.map((message) => {\n if (currentMessageCache.has(message.id)) {\n const renderedMessage = currentMessageCache.get(message.id);\n return {\n ...renderedMessage,\n ...message,\n };\n }\n if (message.component?.componentName) {\n const messageWithComponent = renderComponentIntoMessage(\n message,\n componentList,\n );\n return messageWithComponent;\n }\n return message;\n }),\n };\n\n setThreadMap((prevMap) => {\n const updatedThreadMap = {\n ...prevMap,\n [threadId]: threadWithRenderedComponents,\n };\n return updatedThreadMap;\n });\n },\n [client.beta.threads, componentList, currentMessageCache],\n );\n\n useEffect(() => {\n if (\n currentThreadId &&\n currentThreadId !== PLACEHOLDER_THREAD.id &&\n !threadMap[currentThreadId]\n ) {\n fetchThread(currentThreadId);\n }\n }, [currentThreadId, fetchThread, threadMap]);\n\n const addThreadMessage = useCallback(\n async (\n message: TamboThreadMessage,\n sendToServer = true,\n createdAt: string = new Date().toISOString(),\n ) => {\n if (!currentThread) {\n console.warn(\"Cannot add messages if we do not have a current thread\");\n return [];\n }\n const chatMessage: TamboThreadMessage & {\n additionalContext?: string;\n } = {\n ...message,\n additionalContext:\n message.role === \"user\" ? getClientContext() : undefined,\n createdAt,\n };\n const threadId = message.threadId;\n const messageId = chatMessage.id;\n // optimistically update the thread in the local state\n setThreadMap((prevMap) => {\n if (!threadId) {\n return prevMap;\n }\n const prevMessages = prevMap[threadId]?.messages || [];\n const haveMessage = prevMessages.find((msg) => msg.id === messageId);\n // Update in place if the message already exists\n const updatedMessages = haveMessage\n ? prevMessages.map((msg) => {\n if (msg.id === messageId) {\n return chatMessage;\n }\n return msg;\n })\n : [...prevMessages, chatMessage];\n\n const updatedThreadMap = {\n ...prevMap,\n [threadId]: {\n ...prevMap[threadId],\n messages: updatedMessages,\n },\n };\n return updatedThreadMap;\n });\n\n if (sendToServer) {\n // TODO: if this fails, we need to revert the local state update\n await client.beta.threads.messages.create(message.threadId, {\n content: message.content,\n role: message.role,\n // additionalContext: chatMessage.additionalContext,\n });\n }\n return threadMap[threadId]?.messages || [];\n },\n [client.beta.threads.messages, currentThread, threadMap],\n );\n\n const updateThreadMessage = useCallback(\n async (\n id: string,\n message: TamboThreadMessage,\n sendToServer = true,\n createdAt: string = new Date().toISOString(),\n ) => {\n const chatMessage: TamboThreadMessage = {\n ...message,\n createdAt,\n };\n\n setThreadMap((prevMap) => {\n if (!message.threadId) {\n return prevMap;\n }\n const prevMessages = prevMap[message.threadId]?.messages || [];\n const updatedMessages = prevMessages.map((msg) => {\n if (msg.id === id) {\n return chatMessage;\n }\n return msg;\n });\n return {\n ...prevMap,\n [message.threadId]: {\n ...prevMap[message.threadId],\n messages: updatedMessages,\n },\n };\n });\n if (sendToServer) {\n // TODO: if this fails, we need to revert the local state update\n await client.beta.threads.messages.create(message.threadId, {\n content: message.content,\n role: message.role,\n // additionalContext: chatMessage.additionalContext,\n });\n }\n },\n [client.beta.threads.messages],\n );\n\n const startNewThread = useCallback(() => {\n setCurrentThreadId(PLACEHOLDER_THREAD.id);\n setThreadMap((prevMap) => {\n return {\n ...prevMap,\n [PLACEHOLDER_THREAD.id]: PLACEHOLDER_THREAD,\n };\n });\n }, []);\n\n const switchCurrentThread = useCallback(\n async (threadId: string, fetch = true) => {\n if (threadId === PLACEHOLDER_THREAD.id) {\n console.warn(\"Switching to placeholder thread, may be a bug.\");\n return;\n }\n setCurrentThreadId(threadId);\n setThreadMap((prevMap) => {\n if (prevMap[threadId]) {\n return prevMap;\n }\n // If this is a new thread, add placeholder thread messages to the thread\n const updatedThreadMap = {\n ...prevMap,\n [threadId]: {\n ...prevMap[PLACEHOLDER_THREAD.id],\n id: threadId,\n },\n };\n return updatedThreadMap;\n });\n if (fetch) {\n await fetchThread(threadId);\n }\n },\n [fetchThread],\n );\n\n const updateThreadStatus = useCallback(\n (threadId: string, stage: GenerationStage, statusMessage?: string) => {\n setThreadMap((prevMap) => {\n const updatedThreadMap = {\n ...prevMap,\n [threadId]: {\n ...prevMap[threadId],\n generationStage: stage,\n statusMessage: statusMessage,\n },\n };\n return updatedThreadMap;\n });\n },\n [],\n );\n\n const handleAdvanceStream = useCallback(\n async (\n stream: AsyncIterable<TamboAI.Beta.Threads.ThreadAdvanceResponse>,\n params: TamboAI.Beta.Threads.ThreadAdvanceParams,\n threadId: string,\n ): Promise<TamboThreadMessage> => {\n let finalMessage: Readonly<TamboThreadMessage> | undefined;\n let hasSetThreadId = false;\n updateThreadStatus(threadId, GenerationStage.STREAMING_RESPONSE);\n\n for await (const chunk of stream) {\n if (chunk.responseMessageDto.toolCallRequest) {\n updateThreadStatus(\n chunk.responseMessageDto.threadId,\n GenerationStage.FETCHING_CONTEXT,\n );\n const toolCallResponse = await handleToolCall(\n chunk.responseMessageDto,\n toolRegistry,\n );\n const toolCallResponseString =\n typeof toolCallResponse === \"string\"\n ? toolCallResponse\n : JSON.stringify(toolCallResponse);\n const toolCallResponseParams: TamboAI.Beta.Threads.ThreadAdvanceParams =\n {\n ...params,\n messageToAppend: {\n content: [{ type: \"text\", text: toolCallResponseString }],\n role: \"tool\",\n actionType: \"tool_response\",\n component: chunk.responseMessageDto.component,\n tool_call_id: chunk.responseMessageDto.tool_call_id,\n },\n };\n updateThreadStatus(\n chunk.responseMessageDto.threadId,\n GenerationStage.STREAMING_RESPONSE,\n );\n const toolCallResponseStream = await advanceStream(\n client,\n toolCallResponseParams,\n chunk.responseMessageDto.threadId,\n );\n\n return await handleAdvanceStream(\n toolCallResponseStream,\n toolCallResponseParams,\n chunk.responseMessageDto.threadId,\n );\n } else {\n if (\n !hasSetThreadId &&\n chunk.responseMessageDto.threadId &&\n chunk.responseMessageDto.threadId !== currentThread?.id\n ) {\n hasSetThreadId = true;\n await switchCurrentThread(chunk.responseMessageDto.threadId, false);\n }\n\n if (!finalMessage) {\n finalMessage = chunk.responseMessageDto.component?.componentName\n ? renderComponentIntoMessage(\n chunk.responseMessageDto,\n componentList,\n )\n : chunk.responseMessageDto;\n await addThreadMessage(finalMessage, false);\n } else {\n // if we start getting a new message mid-stream, put the previous one on screen\n const isNewMessage =\n chunk.responseMessageDto.id !== finalMessage.id;\n\n finalMessage = chunk.responseMessageDto.component?.componentName\n ? renderComponentIntoMessage(\n chunk.responseMessageDto,\n componentList,\n )\n : chunk.responseMessageDto;\n\n if (isNewMessage) {\n await addThreadMessage(finalMessage, false);\n } else {\n await updateThreadMessage(finalMessage.id, finalMessage, false);\n }\n }\n }\n }\n\n updateThreadStatus(\n finalMessage?.threadId ?? threadId,\n GenerationStage.COMPLETE,\n );\n return (\n finalMessage ?? {\n threadId: \"\",\n content: [{ type: \"text\", text: `Error processing stream` }],\n role: \"assistant\",\n createdAt: new Date().toISOString(),\n id: crypto.randomUUID(),\n componentState: {},\n }\n );\n },\n [\n addThreadMessage,\n client,\n componentList,\n currentThread?.id,\n switchCurrentThread,\n toolRegistry,\n updateThreadMessage,\n updateThreadStatus,\n ],\n );\n\n const sendThreadMessage = useCallback(\n async (\n message: string,\n options: {\n threadId?: string;\n streamResponse?: boolean;\n contextKey?: string;\n } = { threadId: PLACEHOLDER_THREAD.id },\n ): Promise<TamboThreadMessage> => {\n const { threadId = currentThread.id, streamResponse } = options;\n updateThreadStatus(threadId, GenerationStage.CHOOSING_COMPONENT);\n\n addThreadMessage(\n {\n content: [{ type: \"text\", text: message }],\n renderedComponent: null,\n role: \"user\",\n threadId: threadId,\n id: crypto.randomUUID(),\n createdAt: new Date().toISOString(),\n componentState: {},\n },\n false,\n );\n\n const availableComponents = getAvailableComponents(\n componentList,\n toolRegistry,\n componentToolAssociations,\n );\n const unassociatedTools = getUnassociatedTools(\n toolRegistry,\n componentToolAssociations,\n );\n const params: TamboAI.Beta.Threads.ThreadAdvanceParams = {\n messageToAppend: {\n content: [{ type: \"text\", text: message }],\n role: \"user\",\n },\n contextKey: options.contextKey,\n availableComponents: availableComponents,\n clientTools: unassociatedTools.map((tool) =>\n mapTamboToolToContextTool(tool),\n ),\n };\n\n if (streamResponse) {\n const advanceStreamResponse = await advanceStream(\n client,\n params,\n threadId === PLACEHOLDER_THREAD.id ? undefined : threadId,\n );\n return await handleAdvanceStream(\n advanceStreamResponse,\n params,\n threadId,\n );\n }\n let advanceResponse = await (threadId === PLACEHOLDER_THREAD.id\n ? client.beta.threads.advance(params)\n : client.beta.threads.advanceById(threadId, params));\n\n //handle tool calls\n while (advanceResponse.responseMessageDto.toolCallRequest) {\n updateThreadStatus(threadId, GenerationStage.FETCHING_CONTEXT);\n const toolCallResponse = await handleToolCall(\n advanceResponse.responseMessageDto,\n toolRegistry,\n );\n const toolResponseString =\n typeof toolCallResponse === \"string\"\n ? toolCallResponse\n : JSON.stringify(toolCallResponse);\n const toolCallResponseParams: TamboAI.Beta.Threads.ThreadAdvanceParams =\n {\n ...params,\n messageToAppend: {\n ...params.messageToAppend,\n content: [{ type: \"text\", text: toolResponseString }],\n role: \"tool\",\n actionType: \"tool_response\",\n component: advanceResponse.responseMessageDto.component,\n tool_call_id: advanceResponse.responseMessageDto.tool_call_id,\n },\n };\n updateThreadStatus(threadId, GenerationStage.HYDRATING_COMPONENT);\n advanceResponse = await client.beta.threads.advanceById(\n advanceResponse.responseMessageDto.threadId,\n toolCallResponseParams,\n );\n }\n\n const finalMessage = advanceResponse.responseMessageDto.component\n ?.componentName\n ? renderComponentIntoMessage(\n advanceResponse.responseMessageDto,\n componentList,\n )\n : advanceResponse.responseMessageDto;\n await switchCurrentThread(advanceResponse.responseMessageDto.threadId);\n updateThreadStatus(\n advanceResponse.responseMessageDto.threadId,\n GenerationStage.COMPLETE,\n );\n return finalMessage;\n },\n [\n componentList,\n toolRegistry,\n componentToolAssociations,\n currentThread.id,\n switchCurrentThread,\n addThreadMessage,\n client,\n updateThreadStatus,\n handleAdvanceStream,\n ],\n );\n\n return (\n <TamboThreadContext.Provider\n value={{\n thread: currentThread,\n switchCurrentThread,\n startNewThread,\n addThreadMessage,\n updateThreadMessage,\n inputValue,\n setInputValue,\n sendThreadMessage,\n generationStage: (currentThread?.generationStage ??\n GenerationStage.IDLE) as GenerationStage,\n generationStatusMessage: currentThread?.statusMessage ?? \"\",\n isIdle: isIdleStage(\n (currentThread?.generationStage ??\n GenerationStage.IDLE) as GenerationStage,\n ),\n }}\n >\n {children}\n </TamboThreadContext.Provider>\n );\n};\n\n/**\n * The useTamboThread hook provides access to the current thread context\n * to the descendants of the TamboThreadProvider.\n * @returns All state and actions for the current thread\n */\nexport const useTamboThread = () => {\n const context = useContext(TamboThreadContext);\n if (context === undefined) {\n throw new Error(\"useTamboThread must be used within a TamboThreadProvider\");\n }\n return context;\n};\n"]}
|