@tambo-ai/react 0.19.8 → 0.20.1
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/model/component-metadata.d.ts +3 -1
- package/dist/model/component-metadata.d.ts.map +1 -1
- package/dist/model/component-metadata.js.map +1 -1
- package/dist/providers/tambo-registry-provider.d.ts.map +1 -1
- package/dist/providers/tambo-registry-provider.js +51 -9
- package/dist/providers/tambo-registry-provider.js.map +1 -1
- package/dist/providers/tambo-thread-provider.d.ts +1 -1
- package/dist/providers/tambo-thread-provider.d.ts.map +1 -1
- package/dist/providers/tambo-thread-provider.js +2 -2
- package/dist/providers/tambo-thread-provider.js.map +1 -1
- package/esm/model/component-metadata.d.ts +3 -1
- package/esm/model/component-metadata.d.ts.map +1 -1
- package/esm/model/component-metadata.js.map +1 -1
- package/esm/providers/tambo-registry-provider.d.ts.map +1 -1
- package/esm/providers/tambo-registry-provider.js +51 -9
- package/esm/providers/tambo-registry-provider.js.map +1 -1
- package/esm/providers/tambo-thread-provider.d.ts +1 -1
- package/esm/providers/tambo-thread-provider.d.ts.map +1 -1
- package/esm/providers/tambo-thread-provider.js +2 -2
- package/esm/providers/tambo-thread-provider.js.map +1 -1
- package/package.json +9 -9
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import TamboAI from "@tambo-ai/typescript-sdk";
|
|
2
|
+
import { JSONSchema7 } from "json-schema";
|
|
2
3
|
import { ComponentType } from "react";
|
|
3
4
|
import z from "zod";
|
|
4
5
|
import type zodToJsonSchema from "zod-to-json-schema";
|
|
@@ -62,10 +63,11 @@ export interface TamboComponent {
|
|
|
62
63
|
* A zod schema for the component props. (Recommended)
|
|
63
64
|
* Either this or propsDefinition must be provided, but not both.
|
|
64
65
|
*/
|
|
65
|
-
propsSchema?: z.ZodTypeAny;
|
|
66
|
+
propsSchema?: z.ZodTypeAny | JSONSchema7;
|
|
66
67
|
/**
|
|
67
68
|
* The props definition of the component as a JSON object.
|
|
68
69
|
* Either this or propsSchema must be provided, but not both.
|
|
70
|
+
* @deprecated Use propsSchema instead.
|
|
69
71
|
*/
|
|
70
72
|
propsDefinition?: any;
|
|
71
73
|
/** The loading component to render while the component is loading */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"component-metadata.d.ts","sourceRoot":"","sources":["../../src/model/component-metadata.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,0BAA0B,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AACtC,OAAO,CAAC,MAAM,KAAK,CAAC;AACpB,OAAO,KAAK,eAAe,MAAM,oBAAoB,CAAC;AACtD,+FAA+F;AAC/F,MAAM,MAAM,aAAa,GAAG,OAAO,CAAC,cAAc,GAAG;IACnD,MAAM,CAAC,EAAE,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC;CAC7C,CAAC;AAEF;;;GAGG;AACH,MAAM,WAAW,4BACf,SAAQ,OAAO,CAAC,4BAA4B;IAC5C,UAAU,EAAE,aAAa,EAAE,CAAC;CAC7B;AAED,MAAM,WAAW,oBAAoB;IACnC,mBAAmB,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC;IACtD,UAAU,EAAE,4BAA4B,CAAC;CAC1C;AAED,MAAM,WAAW,mBAAoB,SAAQ,OAAO,CAAC,kBAAkB;IACrE,SAAS,EAAE,aAAa,CAAC,GAAG,CAAC,CAAC;IAC9B,gBAAgB,CAAC,EAAE,aAAa,CAAC,GAAG,CAAC,CAAC;CACvC;AAED,MAAM,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC;AAEpE,MAAM,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;AAE1D,MAAM,WAAW,SAAS,CACxB,IAAI,SAAS,CAAC,CAAC,QAAQ,CAAC,GAAG,EAAE,GAAG,CAAC,GAA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;;OAkBG;IACH,SAAS,EAAE,aAAa,CAAC,GAAG,CAAC,CAAC;IAE9B;;;OAGG;IACH,WAAW,CAAC,EAAE,CAAC,CAAC,UAAU,GAAG,WAAW,CAAC;IACzC;;;;OAIG;IACH,eAAe,CAAC,EAAE,GAAG,CAAC;IACtB,qEAAqE;IACrE,gBAAgB,CAAC,EAAE,aAAa,CAAC,GAAG,CAAC,CAAC;IACtC,uDAAuD;IACvD,eAAe,CAAC,EAAE,SAAS,EAAE,CAAC;CAC/B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"component-metadata.js","sourceRoot":"","sources":["../../src/model/component-metadata.ts"],"names":[],"mappings":"","sourcesContent":["import TamboAI from \"@tambo-ai/typescript-sdk\";\nimport { ComponentType } from \"react\";\nimport z from \"zod\";\nimport type zodToJsonSchema from \"zod-to-json-schema\";\n/** Extension of the ToolParameters interface from Tambo AI to include JSONSchema definition */\nexport type ParameterSpec = TamboAI.ToolParameters & {\n schema?: ReturnType<typeof zodToJsonSchema>;\n};\n\n/**\n * Extends the base ContextTool interface from Tambo AI to include schema information\n * for parameter validation using zod-to-json-schema.\n */\nexport interface ComponentContextToolMetadata\n extends TamboAI.ComponentContextToolMetadata {\n parameters: ParameterSpec[];\n}\n\nexport interface ComponentContextTool {\n getComponentContext: (...args: any[]) => Promise<any>;\n definition: ComponentContextToolMetadata;\n}\n\nexport interface RegisteredComponent extends TamboAI.AvailableComponent {\n component: ComponentType<any>;\n loadingComponent?: ComponentType<any>;\n}\n\nexport type ComponentRegistry = Record<string, RegisteredComponent>;\n\nexport type TamboToolRegistry = Record<string, TamboTool>;\n\nexport interface TamboTool<\n Args extends z.ZodTuple<any, any> = z.ZodTuple<any, any>,\n Returns extends z.ZodTypeAny = z.ZodTypeAny,\n> {\n name: string;\n description: string;\n tool: (...args: z.infer<Args>) => z.infer<Returns>;\n toolSchema: z.ZodFunction<Args, Returns>;\n}\n\nexport type TamboToolAssociations = Record<string, string[]>;\n/**\n * A component that can be registered with the TamboRegistryProvider.\n */\n\nexport interface TamboComponent {\n /** The name of the component */\n name: string;\n /** The description of the component */\n description: string;\n /**\n * The React component to render.\n *\n * Make sure to pass the Component itself, not an instance of the component. For example,\n * if you have a component like this:\n *\n * ```tsx\n * const MyComponent = () => {\n * return <div>My Component</div>;\n * };\n * ```\n *\n * You should pass the `Component`:\n *\n * ```tsx\n * const components = [MyComponent];\n * <TamboRegistryProvider components={components} />\n * ```\n */\n component: ComponentType<any>;\n\n /**\n * A zod schema for the component props. (Recommended)\n * Either this or propsDefinition must be provided, but not both.\n */\n propsSchema?: z.ZodTypeAny;\n /**\n * The props definition of the component as a JSON object.\n * Either this or propsSchema must be provided, but not both.\n */\n propsDefinition?: any;\n /** The loading component to render while the component is loading */\n loadingComponent?: ComponentType<any>;\n /** The tools that are associated with the component */\n associatedTools?: TamboTool[];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"component-metadata.js","sourceRoot":"","sources":["../../src/model/component-metadata.ts"],"names":[],"mappings":"","sourcesContent":["import TamboAI from \"@tambo-ai/typescript-sdk\";\nimport { JSONSchema7 } from \"json-schema\";\nimport { ComponentType } from \"react\";\nimport z from \"zod\";\nimport type zodToJsonSchema from \"zod-to-json-schema\";\n/** Extension of the ToolParameters interface from Tambo AI to include JSONSchema definition */\nexport type ParameterSpec = TamboAI.ToolParameters & {\n schema?: ReturnType<typeof zodToJsonSchema>;\n};\n\n/**\n * Extends the base ContextTool interface from Tambo AI to include schema information\n * for parameter validation using zod-to-json-schema.\n */\nexport interface ComponentContextToolMetadata\n extends TamboAI.ComponentContextToolMetadata {\n parameters: ParameterSpec[];\n}\n\nexport interface ComponentContextTool {\n getComponentContext: (...args: any[]) => Promise<any>;\n definition: ComponentContextToolMetadata;\n}\n\nexport interface RegisteredComponent extends TamboAI.AvailableComponent {\n component: ComponentType<any>;\n loadingComponent?: ComponentType<any>;\n}\n\nexport type ComponentRegistry = Record<string, RegisteredComponent>;\n\nexport type TamboToolRegistry = Record<string, TamboTool>;\n\nexport interface TamboTool<\n Args extends z.ZodTuple<any, any> = z.ZodTuple<any, any>,\n Returns extends z.ZodTypeAny = z.ZodTypeAny,\n> {\n name: string;\n description: string;\n tool: (...args: z.infer<Args>) => z.infer<Returns>;\n toolSchema: z.ZodFunction<Args, Returns>;\n}\n\nexport type TamboToolAssociations = Record<string, string[]>;\n/**\n * A component that can be registered with the TamboRegistryProvider.\n */\n\nexport interface TamboComponent {\n /** The name of the component */\n name: string;\n /** The description of the component */\n description: string;\n /**\n * The React component to render.\n *\n * Make sure to pass the Component itself, not an instance of the component. For example,\n * if you have a component like this:\n *\n * ```tsx\n * const MyComponent = () => {\n * return <div>My Component</div>;\n * };\n * ```\n *\n * You should pass the `Component`:\n *\n * ```tsx\n * const components = [MyComponent];\n * <TamboRegistryProvider components={components} />\n * ```\n */\n component: ComponentType<any>;\n\n /**\n * A zod schema for the component props. (Recommended)\n * Either this or propsDefinition must be provided, but not both.\n */\n propsSchema?: z.ZodTypeAny | JSONSchema7;\n /**\n * The props definition of the component as a JSON object.\n * Either this or propsSchema must be provided, but not both.\n * @deprecated Use propsSchema instead.\n */\n propsDefinition?: any;\n /** The loading component to render while the component is loading */\n loadingComponent?: ComponentType<any>;\n /** The tools that are associated with the component */\n associatedTools?: TamboTool[];\n}\n"]}
|
|
@@ -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;
|
|
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;CAC/B;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,qBAAqB,EAAE,KAAK,CAAC,EAAE,CAC1C,iBAAiB,CAAC,0BAA0B,CAAC,CA2H9C,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,4BAE5B,CAAC"}
|
|
@@ -39,6 +39,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
39
39
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
40
40
|
exports.useTamboRegistry = exports.TamboRegistryProvider = void 0;
|
|
41
41
|
const react_1 = __importStar(require("react"));
|
|
42
|
+
const zod_1 = __importStar(require("zod"));
|
|
42
43
|
const zod_to_json_schema_1 = __importDefault(require("zod-to-json-schema"));
|
|
43
44
|
const TamboRegistryContext = (0, react_1.createContext)({
|
|
44
45
|
componentList: {},
|
|
@@ -107,15 +108,7 @@ const TamboRegistryProvider = ({ children, components: userComponents }) => {
|
|
|
107
108
|
throw new Error(`Component ${name} cannot have both propsSchema and propsDefinition defined. Use only one. We recommend using propsSchema.`);
|
|
108
109
|
}
|
|
109
110
|
// Convert propsSchema to JSON Schema if it exists
|
|
110
|
-
|
|
111
|
-
if (propsSchema) {
|
|
112
|
-
try {
|
|
113
|
-
props = (0, zod_to_json_schema_1.default)(propsSchema);
|
|
114
|
-
}
|
|
115
|
-
catch (error) {
|
|
116
|
-
console.error(`Error converting ${name} props schema to JSON Schema:`, error);
|
|
117
|
-
}
|
|
118
|
-
}
|
|
111
|
+
const props = getSerializedProps(propsDefinition, propsSchema, name);
|
|
119
112
|
setComponentList((prev) => {
|
|
120
113
|
if (prev[name] && warnOnOverwrite) {
|
|
121
114
|
console.warn(`overwriting component ${name}`);
|
|
@@ -168,4 +161,53 @@ const useTamboRegistry = () => {
|
|
|
168
161
|
return (0, react_1.useContext)(TamboRegistryContext);
|
|
169
162
|
};
|
|
170
163
|
exports.useTamboRegistry = useTamboRegistry;
|
|
164
|
+
function getSerializedProps(propsDefinition, propsSchema, name) {
|
|
165
|
+
if (propsDefinition) {
|
|
166
|
+
console.warn(`propsDefinition is deprecated. Use propsSchema instead.`);
|
|
167
|
+
return propsDefinition;
|
|
168
|
+
}
|
|
169
|
+
if (propsSchema instanceof zod_1.ZodSchema || propsSchema instanceof zod_1.default.ZodObject) {
|
|
170
|
+
return (0, zod_to_json_schema_1.default)(propsSchema);
|
|
171
|
+
}
|
|
172
|
+
if (isZodSchema(propsSchema)) {
|
|
173
|
+
try {
|
|
174
|
+
return (0, zod_to_json_schema_1.default)(propsSchema);
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
console.error(`Error converting ${name} props schema to JSON Schema:`, error);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
// try to roughly detect JSONSchema, should always be an object with a properties key
|
|
181
|
+
if (isJSONSchema(propsSchema)) {
|
|
182
|
+
return propsSchema;
|
|
183
|
+
}
|
|
184
|
+
throw new Error(`Invalid props schema for ${name}`);
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Checks if the propsSchema is a JSON Schema. This is a rough check, and the
|
|
188
|
+
* server will provide the definitive check.
|
|
189
|
+
* @param propsSchema - The props schema to check
|
|
190
|
+
* @returns True if the props schema is a JSON Schema, false otherwise
|
|
191
|
+
*/
|
|
192
|
+
function isJSONSchema(propsSchema) {
|
|
193
|
+
return (propsSchema &&
|
|
194
|
+
typeof propsSchema === "object" &&
|
|
195
|
+
propsSchema.type === "object" &&
|
|
196
|
+
propsSchema.properties);
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Since we require a certain zod version, we need to check if the object is a ZodSchema
|
|
200
|
+
* @param obj - The object to check
|
|
201
|
+
* @returns True if the object is a ZodSchema, false otherwise
|
|
202
|
+
*/
|
|
203
|
+
function isZodSchema(obj) {
|
|
204
|
+
if (obj instanceof zod_1.ZodSchema) {
|
|
205
|
+
return true;
|
|
206
|
+
}
|
|
207
|
+
// try to detect if the object is a ZodSchema
|
|
208
|
+
return (typeof obj === "object" &&
|
|
209
|
+
obj !== null &&
|
|
210
|
+
typeof obj.safeParse === "function" &&
|
|
211
|
+
typeof obj._def === "object");
|
|
212
|
+
}
|
|
171
213
|
//# sourceMappingURL=tambo-registry-provider.js.map
|
|
@@ -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,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,EAA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AAC,CAAC;AAC1C,CAAC,CAAC;AAFW,QAAA,gBAAgB,oBAE3B","sourcesContent":["\"use client\";\nimport React, {\n createContext,\n PropsWithChildren,\n useCallback,\n useContext,\n useEffect,\n useState,\n} from \"react\";\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 let props = propsDefinition;\n if (propsSchema) {\n try {\n props = zodToJsonSchema(propsSchema);\n } catch (error) {\n console.error(\n `Error converting ${name} props schema to JSON Schema:`,\n error,\n );\n }\n }\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};\n"]}
|
|
1
|
+
{"version":3,"file":"tambo-registry-provider.js","sourceRoot":"","sources":["../../src/providers/tambo-registry-provider.tsx"],"names":[],"mappings":";AAAA,YAAY,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACb,+CAOe;AACf,2CAAmC;AACnC,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,CAA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I,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,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 z, { 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 if (propsSchema instanceof ZodSchema || propsSchema instanceof z.ZodObject) {\n return zodToJsonSchema(propsSchema);\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"]}
|
|
@@ -19,7 +19,7 @@ export interface TamboThreadContextProps {
|
|
|
19
19
|
setInputValue: (value: string) => void;
|
|
20
20
|
/** Send a message to the current thread */
|
|
21
21
|
sendThreadMessage: (message: string, options: {
|
|
22
|
-
threadId
|
|
22
|
+
threadId?: string;
|
|
23
23
|
streamResponse?: boolean;
|
|
24
24
|
contextKey?: string;
|
|
25
25
|
}) => Promise<TamboThreadMessage>;
|
|
@@ -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;AAOpD,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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C5C,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,CA6d3D,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,cAAc,+BAM1B,CAAC"}
|
|
@@ -358,7 +358,7 @@ const TamboThreadProvider = ({ children, }) => {
|
|
|
358
358
|
updateThreadStatus,
|
|
359
359
|
]);
|
|
360
360
|
const sendThreadMessage = (0, react_1.useCallback)(async (message, options = { threadId: exports.PLACEHOLDER_THREAD.id }) => {
|
|
361
|
-
const { threadId, streamResponse } = options;
|
|
361
|
+
const { threadId = currentThread.id, streamResponse } = options;
|
|
362
362
|
updateThreadStatus(threadId, generate_component_response_1.GenerationStage.CHOOSING_COMPONENT);
|
|
363
363
|
addThreadMessage({
|
|
364
364
|
content: [{ type: "text", text: message }],
|
|
@@ -417,7 +417,7 @@ const TamboThreadProvider = ({ children, }) => {
|
|
|
417
417
|
componentList,
|
|
418
418
|
toolRegistry,
|
|
419
419
|
componentToolAssociations,
|
|
420
|
-
currentThread,
|
|
420
|
+
currentThread.id,
|
|
421
421
|
switchCurrentThread,
|
|
422
422
|
addThreadMessage,
|
|
423
423
|
client,
|
|
@@ -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,+CAA4E;AAC5E,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,+BAA+B,CAAC,CAAC;IACnD,CAAC;IACD;;OAEG;IACH,mBAAmB,EAAE,GAAG,EAAE;QACxB,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;IACzD,CAAC;IACD;;OAEG;IACH,iBAAiB,EAAE,GAAG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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 { getAvailableComponents, getClientContext } 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 ...prevMap,\n [threadId]: threadWithRenderedComponents,\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 return {\n ...prevMap,\n [threadId]: {\n ...prevMap[threadId],\n messages: updatedMessages,\n },\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 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\n setCurrentThreadId(threadId);\n if (!threadMap[threadId]) {\n setThreadMap((prevMap) => {\n return {\n ...prevMap,\n [threadId]: {\n ...prevMap[PLACEHOLDER_THREAD.id],\n id: threadId,\n },\n };\n });\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 return {\n ...prevMap,\n [threadId]: {\n ...prevMap[threadId],\n generationStage: stage,\n statusMessage: statusMessage,\n },\n };\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(threadId, GenerationStage.FETCHING_CONTEXT);\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(threadId, GenerationStage.STREAMING_RESPONSE);\n const toolCallResponseStream = await advanceStream(\n client,\n toolCallResponseParams,\n chunk.responseMessageDto.threadId,\n );\n\n // Pass the current message's ID to be removed when the new stream starts, since we now know it is a tool call request message\n return await handleAdvanceStream(\n toolCallResponseStream,\n toolCallResponseParams,\n threadId,\n finalMessage?.id,\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(threadId, GenerationStage.COMPLETE);\n if (finalMessage) {\n await fetchThread(finalMessage.threadId);\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, 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 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 };\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,\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,+CAA4E;AAC5E,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,+BAA+B,CAAC,CAAC;IACnD,CAAC;IACD;;OAEG;IACH,mBAAmB,EAAE,GAAG,EAAE;QACxB,MAAM,IAAI,K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,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 { getAvailableComponents, getClientContext } 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 ...prevMap,\n [threadId]: threadWithRenderedComponents,\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 return {\n ...prevMap,\n [threadId]: {\n ...prevMap[threadId],\n messages: updatedMessages,\n },\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 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\n setCurrentThreadId(threadId);\n if (!threadMap[threadId]) {\n setThreadMap((prevMap) => {\n return {\n ...prevMap,\n [threadId]: {\n ...prevMap[PLACEHOLDER_THREAD.id],\n id: threadId,\n },\n };\n });\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 return {\n ...prevMap,\n [threadId]: {\n ...prevMap[threadId],\n generationStage: stage,\n statusMessage: statusMessage,\n },\n };\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(threadId, GenerationStage.FETCHING_CONTEXT);\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(threadId, GenerationStage.STREAMING_RESPONSE);\n const toolCallResponseStream = await advanceStream(\n client,\n toolCallResponseParams,\n chunk.responseMessageDto.threadId,\n );\n\n // Pass the current message's ID to be removed when the new stream starts, since we now know it is a tool call request message\n return await handleAdvanceStream(\n toolCallResponseStream,\n toolCallResponseParams,\n threadId,\n finalMessage?.id,\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(threadId, GenerationStage.COMPLETE);\n if (finalMessage) {\n await fetchThread(finalMessage.threadId);\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 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 };\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,4 +1,5 @@
|
|
|
1
1
|
import TamboAI from "@tambo-ai/typescript-sdk";
|
|
2
|
+
import { JSONSchema7 } from "json-schema";
|
|
2
3
|
import { ComponentType } from "react";
|
|
3
4
|
import z from "zod";
|
|
4
5
|
import type zodToJsonSchema from "zod-to-json-schema";
|
|
@@ -62,10 +63,11 @@ export interface TamboComponent {
|
|
|
62
63
|
* A zod schema for the component props. (Recommended)
|
|
63
64
|
* Either this or propsDefinition must be provided, but not both.
|
|
64
65
|
*/
|
|
65
|
-
propsSchema?: z.ZodTypeAny;
|
|
66
|
+
propsSchema?: z.ZodTypeAny | JSONSchema7;
|
|
66
67
|
/**
|
|
67
68
|
* The props definition of the component as a JSON object.
|
|
68
69
|
* Either this or propsSchema must be provided, but not both.
|
|
70
|
+
* @deprecated Use propsSchema instead.
|
|
69
71
|
*/
|
|
70
72
|
propsDefinition?: any;
|
|
71
73
|
/** The loading component to render while the component is loading */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"component-metadata.d.ts","sourceRoot":"","sources":["../../src/model/component-metadata.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,0BAA0B,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AACtC,OAAO,CAAC,MAAM,KAAK,CAAC;AACpB,OAAO,KAAK,eAAe,MAAM,oBAAoB,CAAC;AACtD,+FAA+F;AAC/F,MAAM,MAAM,aAAa,GAAG,OAAO,CAAC,c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M,iBAAiB,GAAG,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;AAE1D,MAAM,WAAW,SAAS,CACxB,IAAI,SAAS,CAAC,CAAC,QAAQ,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,GAAG,EAAE,GAAG,CAAC,EACxD,OAAO,SAAS,CAAC,CAAC,UAAU,GAAG,CAAC,CAAC,UAAU;IAE3C,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACnD,UAAU,EAAE,CAAC,CAAC,WAAW,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;CAC1C;AAED,MAAM,MAAM,qBAAqB,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;AAC7D;;GAEG;AAEH,MAAM,WAAW,cAAc;IAC7B,gCAAgC;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,uCAAuC;IACvC,WAAW,EAAE,MAAM,CAAC;IACpB;;;;;;;;;;;;;;;;;;OAkBG;IACH,SAAS,EAAE,aAAa,CAAC,GAAG,CAAC,CAAC;IAE9B;;;OAGG;IACH,WAAW,CAAC,EAAE,CAAC,CAAC,UAAU,GAAG,WAAW,CAAC;IACzC;;;;OAIG;IACH,eAAe,CAAC,EAAE,GAAG,CAAC;IACtB,qEAAqE;IACrE,gBAAgB,CAAC,EAAE,aAAa,CAAC,GAAG,CAAC,CAAC;IACtC,uDAAuD;IACvD,eAAe,CAAC,EAAE,SAAS,EAAE,CAAC;CAC/B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"component-metadata.js","sourceRoot":"","sources":["../../src/model/component-metadata.ts"],"names":[],"mappings":"","sourcesContent":["import TamboAI from \"@tambo-ai/typescript-sdk\";\nimport { ComponentType } from \"react\";\nimport z from \"zod\";\nimport type zodToJsonSchema from \"zod-to-json-schema\";\n/** Extension of the ToolParameters interface from Tambo AI to include JSONSchema definition */\nexport type ParameterSpec = TamboAI.ToolParameters & {\n schema?: ReturnType<typeof zodToJsonSchema>;\n};\n\n/**\n * Extends the base ContextTool interface from Tambo AI to include schema information\n * for parameter validation using zod-to-json-schema.\n */\nexport interface ComponentContextToolMetadata\n extends TamboAI.ComponentContextToolMetadata {\n parameters: ParameterSpec[];\n}\n\nexport interface ComponentContextTool {\n getComponentContext: (...args: any[]) => Promise<any>;\n definition: ComponentContextToolMetadata;\n}\n\nexport interface RegisteredComponent extends TamboAI.AvailableComponent {\n component: ComponentType<any>;\n loadingComponent?: ComponentType<any>;\n}\n\nexport type ComponentRegistry = Record<string, RegisteredComponent>;\n\nexport type TamboToolRegistry = Record<string, TamboTool>;\n\nexport interface TamboTool<\n Args extends z.ZodTuple<any, any> = z.ZodTuple<any, any>,\n Returns extends z.ZodTypeAny = z.ZodTypeAny,\n> {\n name: string;\n description: string;\n tool: (...args: z.infer<Args>) => z.infer<Returns>;\n toolSchema: z.ZodFunction<Args, Returns>;\n}\n\nexport type TamboToolAssociations = Record<string, string[]>;\n/**\n * A component that can be registered with the TamboRegistryProvider.\n */\n\nexport interface TamboComponent {\n /** The name of the component */\n name: string;\n /** The description of the component */\n description: string;\n /**\n * The React component to render.\n *\n * Make sure to pass the Component itself, not an instance of the component. For example,\n * if you have a component like this:\n *\n * ```tsx\n * const MyComponent = () => {\n * return <div>My Component</div>;\n * };\n * ```\n *\n * You should pass the `Component`:\n *\n * ```tsx\n * const components = [MyComponent];\n * <TamboRegistryProvider components={components} />\n * ```\n */\n component: ComponentType<any>;\n\n /**\n * A zod schema for the component props. (Recommended)\n * Either this or propsDefinition must be provided, but not both.\n */\n propsSchema?: z.ZodTypeAny;\n /**\n * The props definition of the component as a JSON object.\n * Either this or propsSchema must be provided, but not both.\n */\n propsDefinition?: any;\n /** The loading component to render while the component is loading */\n loadingComponent?: ComponentType<any>;\n /** The tools that are associated with the component */\n associatedTools?: TamboTool[];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"component-metadata.js","sourceRoot":"","sources":["../../src/model/component-metadata.ts"],"names":[],"mappings":"","sourcesContent":["import TamboAI from \"@tambo-ai/typescript-sdk\";\nimport { JSONSchema7 } from \"json-schema\";\nimport { ComponentType } from \"react\";\nimport z from \"zod\";\nimport type zodToJsonSchema from \"zod-to-json-schema\";\n/** Extension of the ToolParameters interface from Tambo AI to include JSONSchema definition */\nexport type ParameterSpec = TamboAI.ToolParameters & {\n schema?: ReturnType<typeof zodToJsonSchema>;\n};\n\n/**\n * Extends the base ContextTool interface from Tambo AI to include schema information\n * for parameter validation using zod-to-json-schema.\n */\nexport interface ComponentContextToolMetadata\n extends TamboAI.ComponentContextToolMetadata {\n parameters: ParameterSpec[];\n}\n\nexport interface ComponentContextTool {\n getComponentContext: (...args: any[]) => Promise<any>;\n definition: ComponentContextToolMetadata;\n}\n\nexport interface RegisteredComponent extends TamboAI.AvailableComponent {\n component: ComponentType<any>;\n loadingComponent?: ComponentType<any>;\n}\n\nexport type ComponentRegistry = Record<string, RegisteredComponent>;\n\nexport type TamboToolRegistry = Record<string, TamboTool>;\n\nexport interface TamboTool<\n Args extends z.ZodTuple<any, any> = z.ZodTuple<any, any>,\n Returns extends z.ZodTypeAny = z.ZodTypeAny,\n> {\n name: string;\n description: string;\n tool: (...args: z.infer<Args>) => z.infer<Returns>;\n toolSchema: z.ZodFunction<Args, Returns>;\n}\n\nexport type TamboToolAssociations = Record<string, string[]>;\n/**\n * A component that can be registered with the TamboRegistryProvider.\n */\n\nexport interface TamboComponent {\n /** The name of the component */\n name: string;\n /** The description of the component */\n description: string;\n /**\n * The React component to render.\n *\n * Make sure to pass the Component itself, not an instance of the component. For example,\n * if you have a component like this:\n *\n * ```tsx\n * const MyComponent = () => {\n * return <div>My Component</div>;\n * };\n * ```\n *\n * You should pass the `Component`:\n *\n * ```tsx\n * const components = [MyComponent];\n * <TamboRegistryProvider components={components} />\n * ```\n */\n component: ComponentType<any>;\n\n /**\n * A zod schema for the component props. (Recommended)\n * Either this or propsDefinition must be provided, but not both.\n */\n propsSchema?: z.ZodTypeAny | JSONSchema7;\n /**\n * The props definition of the component as a JSON object.\n * Either this or propsSchema must be provided, but not both.\n * @deprecated Use propsSchema instead.\n */\n propsDefinition?: any;\n /** The loading component to render while the component is loading */\n loadingComponent?: ComponentType<any>;\n /** The tools that are associated with the component */\n associatedTools?: TamboTool[];\n}\n"]}
|
|
@@ -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;
|
|
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;CAC/B;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,qBAAqB,EAAE,KAAK,CAAC,EAAE,CAC1C,iBAAiB,CAAC,0BAA0B,CAAC,CA2H9C,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,4BAE5B,CAAC"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import React, { createContext, useCallback, useContext, useEffect, useState, } from "react";
|
|
3
|
+
import z, { ZodSchema } from "zod";
|
|
3
4
|
import zodToJsonSchema from "zod-to-json-schema";
|
|
4
5
|
const TamboRegistryContext = createContext({
|
|
5
6
|
componentList: {},
|
|
@@ -68,15 +69,7 @@ export const TamboRegistryProvider = ({ children, components: userComponents })
|
|
|
68
69
|
throw new Error(`Component ${name} cannot have both propsSchema and propsDefinition defined. Use only one. We recommend using propsSchema.`);
|
|
69
70
|
}
|
|
70
71
|
// Convert propsSchema to JSON Schema if it exists
|
|
71
|
-
|
|
72
|
-
if (propsSchema) {
|
|
73
|
-
try {
|
|
74
|
-
props = zodToJsonSchema(propsSchema);
|
|
75
|
-
}
|
|
76
|
-
catch (error) {
|
|
77
|
-
console.error(`Error converting ${name} props schema to JSON Schema:`, error);
|
|
78
|
-
}
|
|
79
|
-
}
|
|
72
|
+
const props = getSerializedProps(propsDefinition, propsSchema, name);
|
|
80
73
|
setComponentList((prev) => {
|
|
81
74
|
if (prev[name] && warnOnOverwrite) {
|
|
82
75
|
console.warn(`overwriting component ${name}`);
|
|
@@ -127,4 +120,53 @@ export const TamboRegistryProvider = ({ children, components: userComponents })
|
|
|
127
120
|
export const useTamboRegistry = () => {
|
|
128
121
|
return useContext(TamboRegistryContext);
|
|
129
122
|
};
|
|
123
|
+
function getSerializedProps(propsDefinition, propsSchema, name) {
|
|
124
|
+
if (propsDefinition) {
|
|
125
|
+
console.warn(`propsDefinition is deprecated. Use propsSchema instead.`);
|
|
126
|
+
return propsDefinition;
|
|
127
|
+
}
|
|
128
|
+
if (propsSchema instanceof ZodSchema || propsSchema instanceof z.ZodObject) {
|
|
129
|
+
return zodToJsonSchema(propsSchema);
|
|
130
|
+
}
|
|
131
|
+
if (isZodSchema(propsSchema)) {
|
|
132
|
+
try {
|
|
133
|
+
return zodToJsonSchema(propsSchema);
|
|
134
|
+
}
|
|
135
|
+
catch (error) {
|
|
136
|
+
console.error(`Error converting ${name} props schema to JSON Schema:`, error);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
// try to roughly detect JSONSchema, should always be an object with a properties key
|
|
140
|
+
if (isJSONSchema(propsSchema)) {
|
|
141
|
+
return propsSchema;
|
|
142
|
+
}
|
|
143
|
+
throw new Error(`Invalid props schema for ${name}`);
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Checks if the propsSchema is a JSON Schema. This is a rough check, and the
|
|
147
|
+
* server will provide the definitive check.
|
|
148
|
+
* @param propsSchema - The props schema to check
|
|
149
|
+
* @returns True if the props schema is a JSON Schema, false otherwise
|
|
150
|
+
*/
|
|
151
|
+
function isJSONSchema(propsSchema) {
|
|
152
|
+
return (propsSchema &&
|
|
153
|
+
typeof propsSchema === "object" &&
|
|
154
|
+
propsSchema.type === "object" &&
|
|
155
|
+
propsSchema.properties);
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Since we require a certain zod version, we need to check if the object is a ZodSchema
|
|
159
|
+
* @param obj - The object to check
|
|
160
|
+
* @returns True if the object is a ZodSchema, false otherwise
|
|
161
|
+
*/
|
|
162
|
+
function isZodSchema(obj) {
|
|
163
|
+
if (obj instanceof ZodSchema) {
|
|
164
|
+
return true;
|
|
165
|
+
}
|
|
166
|
+
// try to detect if the object is a ZodSchema
|
|
167
|
+
return (typeof obj === "object" &&
|
|
168
|
+
obj !== null &&
|
|
169
|
+
typeof obj.safeParse === "function" &&
|
|
170
|
+
typeof obj._def === "object");
|
|
171
|
+
}
|
|
130
172
|
//# sourceMappingURL=tambo-registry-provider.js.map
|
|
@@ -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,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;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAE9B,CAAC,EAAE,QAAQ,EAAE,UAAU,EAAE,cAAc,EAAE,EAAE,EAAE;IAC/C,MAAM,CAAC,aAAa,EAAE,gBAAgB,CAAC,GAAG,QAAQ,CAAoB,EAAE,CAAC,CAAC;IAC1E,MAAM,CAAC,YAAY,EAAE,eAAe,CAAC,GAAG,QAAQ,CAC9C,EAAE,CACH,CAAC;IACF,MAAM,CAAC,yBAAyB,EAAE,4BAA4B,CAAC,GAAG,QAAQ,CAExE,EAAE,CAAC,CAAC;IAEN,MAAM,YAAY,GAAG,WAAW,CAC9B,CAAC,IAAe,EAAE,eAAe,GAAG,IAAI,EAAE,EAAE;QAC1C,eAAe,CAAC,CAAC,IAAI,EAAE,EAAE;YACvB,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI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G,EAAE;QACb,IAAI,cAAc,EAAE,CAAC;YACnB,cAAc,CAAC,OAAO,CAAC,CAAC,SAAS,EAAE,EAAE;gBACnC,iBAAiB,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;YACtC,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC,EAAE,CAAC,iBAAiB,EAAE,cAAc,CAAC,CAAC,CAAC;IAExC,MAAM,KAAK,GAAG;QACZ,aAAa;QACb,YAAY;QACZ,yBAAyB;QACzB,iBAAiB;QACjB,YAAY;QACZ,aAAa;QACb,kBAAkB;KACnB,CAAC;IAEF,OAAO,CACL,oBAAC,oBAAoB,CAAC,QAAQ,IAAC,KAAK,EAAE,KAAK,IACxC,QAAQ,CACqB,CACjC,CAAC;AACJ,CAAC,CAAC;AAEF;;;;GAIG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,GAAG,EAAE;IACnC,OAAO,UAAU,CAAC,oBAAoB,CAAC,CAAC;AAC1C,CAAC,CAAC","sourcesContent":["\"use client\";\nimport React, {\n createContext,\n PropsWithChildren,\n useCallback,\n useContext,\n useEffect,\n useState,\n} from \"react\";\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 let props = propsDefinition;\n if (propsSchema) {\n try {\n props = zodToJsonSchema(propsSchema);\n } catch (error) {\n console.error(\n `Error converting ${name} props schema to JSON Schema:`,\n error,\n );\n }\n }\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};\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,CAAC,EAAE,EAAE,SAAS,EAAE,MAAM,KAAK,CAAC;AACnC,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;IAC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AAO,eAAe,CAAC;IACzB,CAAC;IACD,IAAI,WAAW,YAAY,SAAS,IAAI,WAAW,YAAY,CAAC,CAAC,SAAS,EAAE,CAAC;QAC3E,OAAO,eAAe,CAAC,WAAW,CAAC,CAAC;IACtC,CAAC;IAED,IAAI,WAAW,CAAC,WAAW,CAAC,EAAE,CAAC;QAC7B,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 z, { 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 if (propsSchema instanceof ZodSchema || propsSchema instanceof z.ZodObject) {\n return zodToJsonSchema(propsSchema);\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"]}
|
|
@@ -19,7 +19,7 @@ export interface TamboThreadContextProps {
|
|
|
19
19
|
setInputValue: (value: string) => void;
|
|
20
20
|
/** Send a message to the current thread */
|
|
21
21
|
sendThreadMessage: (message: string, options: {
|
|
22
|
-
threadId
|
|
22
|
+
threadId?: string;
|
|
23
23
|
streamResponse?: boolean;
|
|
24
24
|
contextKey?: string;
|
|
25
25
|
}) => Promise<TamboThreadMessage>;
|
|
@@ -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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AIG;AACH,eAAO,MAAM,cAAc,+BAM1B,CAAC"}
|
|
@@ -322,7 +322,7 @@ export const TamboThreadProvider = ({ children, }) => {
|
|
|
322
322
|
updateThreadStatus,
|
|
323
323
|
]);
|
|
324
324
|
const sendThreadMessage = useCallback(async (message, options = { threadId: PLACEHOLDER_THREAD.id }) => {
|
|
325
|
-
const { threadId, streamResponse } = options;
|
|
325
|
+
const { threadId = currentThread.id, streamResponse } = options;
|
|
326
326
|
updateThreadStatus(threadId, GenerationStage.CHOOSING_COMPONENT);
|
|
327
327
|
addThreadMessage({
|
|
328
328
|
content: [{ type: "text", text: message }],
|
|
@@ -381,7 +381,7 @@ export const TamboThreadProvider = ({ children, }) => {
|
|
|
381
381
|
componentList,
|
|
382
382
|
toolRegistry,
|
|
383
383
|
componentToolAssociations,
|
|
384
|
-
currentThread,
|
|
384
|
+
currentThread.id,
|
|
385
385
|
switchCurrentThread,
|
|
386
386
|
addThreadMessage,
|
|
387
387
|
client,
|
|
@@ -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,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,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA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AClB,mBAAmB;KACpB,CACF,CAAC;IAEF,OAAO,CACL,oBAAC,kBAAkB,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,eAAe,CAAC,IAAI,CAAoB;YAC1C,uBAAuB,EAAE,aAAa,EAAE,aAAa,IAAI,EAAE;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 { getAvailableComponents, getClientContext } 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 ...prevMap,\n [threadId]: threadWithRenderedComponents,\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 return {\n ...prevMap,\n [threadId]: {\n ...prevMap[threadId],\n messages: updatedMessages,\n },\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 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\n setCurrentThreadId(threadId);\n if (!threadMap[threadId]) {\n setThreadMap((prevMap) => {\n return {\n ...prevMap,\n [threadId]: {\n ...prevMap[PLACEHOLDER_THREAD.id],\n id: threadId,\n },\n };\n });\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 return {\n ...prevMap,\n [threadId]: {\n ...prevMap[threadId],\n generationStage: stage,\n statusMessage: statusMessage,\n },\n };\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(threadId, GenerationStage.FETCHING_CONTEXT);\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(threadId, GenerationStage.STREAMING_RESPONSE);\n const toolCallResponseStream = await advanceStream(\n client,\n toolCallResponseParams,\n chunk.responseMessageDto.threadId,\n );\n\n // Pass the current message's ID to be removed when the new stream starts, since we now know it is a tool call request message\n return await handleAdvanceStream(\n toolCallResponseStream,\n toolCallResponseParams,\n threadId,\n finalMessage?.id,\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(threadId, GenerationStage.COMPLETE);\n if (finalMessage) {\n await fetchThread(finalMessage.threadId);\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, 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 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 };\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,\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,OA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BAAkB,CAChB,eAAe,CAAC,kBAAkB,CAAC,QAAQ,EAC3C,eAAe,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,oBAAC,kBAAkB,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,eAAe,CAAC,IAAI,CAAoB;YAC1C,uBAAuB,EAAE,aAAa,EAAE,aAAa,IAAI,EAAE;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 { getAvailableComponents, getClientContext } 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 ...prevMap,\n [threadId]: threadWithRenderedComponents,\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 return {\n ...prevMap,\n [threadId]: {\n ...prevMap[threadId],\n messages: updatedMessages,\n },\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 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\n setCurrentThreadId(threadId);\n if (!threadMap[threadId]) {\n setThreadMap((prevMap) => {\n return {\n ...prevMap,\n [threadId]: {\n ...prevMap[PLACEHOLDER_THREAD.id],\n id: threadId,\n },\n };\n });\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 return {\n ...prevMap,\n [threadId]: {\n ...prevMap[threadId],\n generationStage: stage,\n statusMessage: statusMessage,\n },\n };\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(threadId, GenerationStage.FETCHING_CONTEXT);\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(threadId, GenerationStage.STREAMING_RESPONSE);\n const toolCallResponseStream = await advanceStream(\n client,\n toolCallResponseParams,\n chunk.responseMessageDto.threadId,\n );\n\n // Pass the current message's ID to be removed when the new stream starts, since we now know it is a tool call request message\n return await handleAdvanceStream(\n toolCallResponseStream,\n toolCallResponseParams,\n threadId,\n finalMessage?.id,\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(threadId, GenerationStage.COMPLETE);\n if (finalMessage) {\n await fetchThread(finalMessage.threadId);\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 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 };\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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tambo-ai/react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.20.1",
|
|
4
4
|
"description": "React client package for Tambo AI",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -62,8 +62,8 @@
|
|
|
62
62
|
"react-dom": "^18.0.0 || ^19.0.0"
|
|
63
63
|
},
|
|
64
64
|
"dependencies": {
|
|
65
|
-
"@tambo-ai/typescript-sdk": "^0.42.
|
|
66
|
-
"@tanstack/react-query": "^5.71.
|
|
65
|
+
"@tambo-ai/typescript-sdk": "^0.42.1",
|
|
66
|
+
"@tanstack/react-query": "^5.71.10",
|
|
67
67
|
"partial-json": "^0.1.7",
|
|
68
68
|
"react-fast-compare": "^3.2.2",
|
|
69
69
|
"use-debounce": "^10.0.4",
|
|
@@ -71,20 +71,20 @@
|
|
|
71
71
|
"zod-to-json-schema": "^3.24.5"
|
|
72
72
|
},
|
|
73
73
|
"devDependencies": {
|
|
74
|
-
"@eslint/js": "^9.
|
|
74
|
+
"@eslint/js": "^9.24.0",
|
|
75
75
|
"@tambo-ai/eslint-config": "*",
|
|
76
76
|
"@tambo-ai/typescript-config": "*",
|
|
77
77
|
"@testing-library/jest-dom": "^6.4.2",
|
|
78
|
-
"@testing-library/react": "^16.
|
|
78
|
+
"@testing-library/react": "^16.3.0",
|
|
79
79
|
"@types/jest": "^29.5.12",
|
|
80
80
|
"@types/json-schema": "^7.0.15",
|
|
81
|
-
"@types/node": "^20.17.
|
|
81
|
+
"@types/node": "^20.17.30",
|
|
82
82
|
"@types/react": "^18.3.12",
|
|
83
83
|
"@types/react-dom": "^18.3.5",
|
|
84
84
|
"concurrently": "^9.1.2",
|
|
85
|
-
"eslint": "^9.
|
|
85
|
+
"eslint": "^9.24.0",
|
|
86
86
|
"eslint-plugin-jsdoc": "^50.6.9",
|
|
87
|
-
"eslint-plugin-react": "^7.37.
|
|
87
|
+
"eslint-plugin-react": "^7.37.5",
|
|
88
88
|
"eslint-plugin-react-hooks": "^5.1.0",
|
|
89
89
|
"jest": "^29.7.0",
|
|
90
90
|
"jest-environment-jsdom": "^29.7.0",
|
|
@@ -93,7 +93,7 @@
|
|
|
93
93
|
"react": "^18.3.1",
|
|
94
94
|
"react-dom": "^18.3.1",
|
|
95
95
|
"ts-jest": "^29.3.1",
|
|
96
|
-
"typescript": "^5.
|
|
96
|
+
"typescript": "^5.8.3",
|
|
97
97
|
"typescript-eslint": "^8.29.0"
|
|
98
98
|
}
|
|
99
99
|
}
|