@tambo-ai/react 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -0
- package/dist/hooks/__tests__/use-suggestions.test.d.ts +1 -0
- package/dist/hooks/__tests__/use-suggestions.test.js +167 -0
- package/dist/hooks/__tests__/use-suggestions.test.js.map +1 -0
- package/dist/hooks/react-query-hooks.d.ts +21 -0
- package/dist/hooks/react-query-hooks.js +33 -0
- package/dist/hooks/react-query-hooks.js.map +1 -0
- package/dist/hooks/use-component-state.d.ts +8 -0
- package/dist/hooks/use-component-state.js +42 -0
- package/dist/hooks/use-component-state.js.map +1 -0
- package/dist/hooks/use-current-message.d.ts +18 -0
- package/dist/hooks/use-current-message.js +73 -0
- package/dist/hooks/use-current-message.js.map +1 -0
- package/dist/hooks/use-query-client.d.ts +0 -0
- package/dist/hooks/use-query-client.js +2 -0
- package/dist/hooks/use-query-client.js.map +1 -0
- package/dist/hooks/use-suggestions.d.ts +44 -0
- package/dist/hooks/use-suggestions.js +111 -0
- package/dist/hooks/use-suggestions.js.map +1 -0
- package/dist/hooks/use-tambo-threads.d.ts +137 -0
- package/dist/hooks/use-tambo-threads.js +33 -0
- package/dist/hooks/use-tambo-threads.js.map +1 -0
- package/dist/hooks/use-thread-input.d.ts +48 -0
- package/dist/hooks/use-thread-input.js +53 -0
- package/dist/hooks/use-thread-input.js.map +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +34 -0
- package/dist/index.js.map +1 -0
- package/dist/model/component-metadata.d.ts +32 -0
- package/dist/model/component-metadata.js +3 -0
- package/dist/model/component-metadata.js.map +1 -0
- package/dist/model/generate-component-response.d.ts +17 -0
- package/dist/model/generate-component-response.js +22 -0
- package/dist/model/generate-component-response.js.map +1 -0
- package/dist/model/tambo-thread.d.ts +7 -0
- package/dist/model/tambo-thread.js +3 -0
- package/dist/model/tambo-thread.js.map +1 -0
- package/dist/model/thread-input-error.d.ts +3 -0
- package/dist/model/thread-input-error.js +8 -0
- package/dist/model/thread-input-error.js.map +1 -0
- package/dist/model/validate-input.d.ts +6 -0
- package/dist/model/validate-input.js +27 -0
- package/dist/model/validate-input.js.map +1 -0
- package/dist/providers/index.d.ts +5 -0
- package/dist/providers/index.js +21 -0
- package/dist/providers/index.js.map +1 -0
- package/dist/providers/tambo-client-provider.d.ts +15 -0
- package/dist/providers/tambo-client-provider.js +66 -0
- package/dist/providers/tambo-client-provider.js.map +1 -0
- package/dist/providers/tambo-component-provider.d.ts +18 -0
- package/dist/providers/tambo-component-provider.js +129 -0
- package/dist/providers/tambo-component-provider.js.map +1 -0
- package/dist/providers/tambo-provider.d.ts +10 -0
- package/dist/providers/tambo-provider.js +70 -0
- package/dist/providers/tambo-provider.js.map +1 -0
- package/dist/providers/tambo-registry-provider.d.ts +21 -0
- package/dist/providers/tambo-registry-provider.js +117 -0
- package/dist/providers/tambo-registry-provider.js.map +1 -0
- package/dist/providers/tambo-thread-provider.d.ts +28 -0
- package/dist/providers/tambo-thread-provider.js +417 -0
- package/dist/providers/tambo-thread-provider.js.map +1 -0
- package/dist/setupTests.d.ts +1 -0
- package/dist/setupTests.js +20 -0
- package/dist/setupTests.js.map +1 -0
- package/dist/util/generate-component.d.ts +8 -0
- package/dist/util/generate-component.js +209 -0
- package/dist/util/generate-component.js.map +1 -0
- package/dist/util/messages.d.ts +2 -0
- package/dist/util/messages.js +12 -0
- package/dist/util/messages.js.map +1 -0
- package/dist/util/query-utils.d.ts +5 -0
- package/dist/util/query-utils.js +63 -0
- package/dist/util/query-utils.js.map +1 -0
- package/dist/util/registry.d.ts +7 -0
- package/dist/util/registry.js +99 -0
- package/dist/util/registry.js.map +1 -0
- package/dist/util/tool-caller.d.ts +3 -0
- package/dist/util/tool-caller.js +30 -0
- package/dist/util/tool-caller.js.map +1 -0
- package/esm/hooks/__tests__/use-suggestions.test.d.ts +1 -0
- package/esm/hooks/__tests__/use-suggestions.test.js +165 -0
- package/esm/hooks/__tests__/use-suggestions.test.js.map +1 -0
- package/esm/hooks/react-query-hooks.d.ts +21 -0
- package/esm/hooks/react-query-hooks.js +28 -0
- package/esm/hooks/react-query-hooks.js.map +1 -0
- package/esm/hooks/use-component-state.d.ts +8 -0
- package/esm/hooks/use-component-state.js +39 -0
- package/esm/hooks/use-component-state.js.map +1 -0
- package/esm/hooks/use-current-message.d.ts +18 -0
- package/esm/hooks/use-current-message.js +33 -0
- package/esm/hooks/use-current-message.js.map +1 -0
- package/esm/hooks/use-query-client.d.ts +0 -0
- package/esm/hooks/use-query-client.js +2 -0
- package/esm/hooks/use-query-client.js.map +1 -0
- package/esm/hooks/use-suggestions.d.ts +44 -0
- package/esm/hooks/use-suggestions.js +108 -0
- package/esm/hooks/use-suggestions.js.map +1 -0
- package/esm/hooks/use-tambo-threads.d.ts +137 -0
- package/esm/hooks/use-tambo-threads.js +30 -0
- package/esm/hooks/use-tambo-threads.js.map +1 -0
- package/esm/hooks/use-thread-input.d.ts +48 -0
- package/esm/hooks/use-thread-input.js +49 -0
- package/esm/hooks/use-thread-input.js.map +1 -0
- package/esm/index.d.ts +12 -0
- package/esm/index.js +10 -0
- package/esm/index.js.map +1 -0
- package/esm/model/component-metadata.d.ts +32 -0
- package/esm/model/component-metadata.js +2 -0
- package/esm/model/component-metadata.js.map +1 -0
- package/esm/model/generate-component-response.d.ts +17 -0
- package/esm/model/generate-component-response.js +18 -0
- package/esm/model/generate-component-response.js.map +1 -0
- package/esm/model/tambo-thread.d.ts +7 -0
- package/esm/model/tambo-thread.js +2 -0
- package/esm/model/tambo-thread.js.map +1 -0
- package/esm/model/thread-input-error.d.ts +3 -0
- package/esm/model/thread-input-error.js +4 -0
- package/esm/model/thread-input-error.js.map +1 -0
- package/esm/model/validate-input.d.ts +6 -0
- package/esm/model/validate-input.js +24 -0
- package/esm/model/validate-input.js.map +1 -0
- package/esm/providers/index.d.ts +5 -0
- package/esm/providers/index.js +6 -0
- package/esm/providers/index.js.map +1 -0
- package/esm/providers/tambo-client-provider.d.ts +15 -0
- package/esm/providers/tambo-client-provider.js +24 -0
- package/esm/providers/tambo-client-provider.js.map +1 -0
- package/esm/providers/tambo-component-provider.d.ts +18 -0
- package/esm/providers/tambo-component-provider.js +91 -0
- package/esm/providers/tambo-component-provider.js.map +1 -0
- package/esm/providers/tambo-provider.d.ts +10 -0
- package/esm/providers/tambo-provider.js +32 -0
- package/esm/providers/tambo-provider.js.map +1 -0
- package/esm/providers/tambo-registry-provider.d.ts +21 -0
- package/esm/providers/tambo-registry-provider.js +79 -0
- package/esm/providers/tambo-registry-provider.js.map +1 -0
- package/esm/providers/tambo-thread-provider.d.ts +28 -0
- package/esm/providers/tambo-thread-provider.js +379 -0
- package/esm/providers/tambo-thread-provider.js.map +1 -0
- package/esm/setupTests.d.ts +1 -0
- package/esm/setupTests.js +18 -0
- package/esm/setupTests.js.map +1 -0
- package/esm/util/generate-component.d.ts +8 -0
- package/esm/util/generate-component.js +202 -0
- package/esm/util/generate-component.js.map +1 -0
- package/esm/util/messages.d.ts +2 -0
- package/esm/util/messages.js +9 -0
- package/esm/util/messages.js.map +1 -0
- package/esm/util/query-utils.d.ts +5 -0
- package/esm/util/query-utils.js +59 -0
- package/esm/util/query-utils.js.map +1 -0
- package/esm/util/registry.d.ts +7 -0
- package/esm/util/registry.js +88 -0
- package/esm/util/registry.js.map +1 -0
- package/esm/util/tool-caller.d.ts +3 -0
- package/esm/util/tool-caller.js +26 -0
- package/esm/util/tool-caller.js.map +1 -0
- package/package.json +84 -0
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.generateAndHydrate = generateAndHydrate;
|
|
7
|
+
exports.renderComponentIntoMessage = renderComponentIntoMessage;
|
|
8
|
+
const typescript_sdk_1 = require("@tambo-ai/typescript-sdk");
|
|
9
|
+
const partial_json_1 = require("partial-json");
|
|
10
|
+
const react_1 = __importDefault(require("react"));
|
|
11
|
+
const zod_1 = require("zod");
|
|
12
|
+
const use_current_message_1 = require("../hooks/use-current-message");
|
|
13
|
+
const generate_component_response_1 = require("../model/generate-component-response");
|
|
14
|
+
const registry_1 = require("../util/registry");
|
|
15
|
+
const tool_caller_1 = require("../util/tool-caller");
|
|
16
|
+
async function generateAndHydrate(client, componentList, toolRegistry, toolAssociations, currentThreadId, content, params, onUpdateState, stream = false, options) {
|
|
17
|
+
const availableComponents = (0, registry_1.getAvailableComponents)(componentList, toolRegistry, toolAssociations);
|
|
18
|
+
let threadId = currentThreadId;
|
|
19
|
+
onUpdateState(generate_component_response_1.GenerationStage.CHOOSING_COMPONENT);
|
|
20
|
+
try {
|
|
21
|
+
if (stream) {
|
|
22
|
+
const streamResponse = await (0, typescript_sdk_1.generateStream)(client, {
|
|
23
|
+
availableComponents,
|
|
24
|
+
contextKey: params.contextKey,
|
|
25
|
+
content,
|
|
26
|
+
threadId: params.threadId === "placeholder" ? undefined : params.threadId,
|
|
27
|
+
}, options);
|
|
28
|
+
return processComponentDecisionStream(handleStream(streamResponse), componentList, toolRegistry, onUpdateState, client, options);
|
|
29
|
+
}
|
|
30
|
+
const response = await client.beta.components.generate({
|
|
31
|
+
availableComponents,
|
|
32
|
+
contextKey: params.contextKey,
|
|
33
|
+
content,
|
|
34
|
+
threadId: params.threadId === "placeholder" ? undefined : params.threadId,
|
|
35
|
+
}, options);
|
|
36
|
+
// Capture the current threadId in case the following processComponentDecision fails
|
|
37
|
+
threadId = response.message.threadId;
|
|
38
|
+
return await processComponentDecision(client, componentList, toolRegistry, response.message.threadId, content, response.message, onUpdateState, options);
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
console.error(error);
|
|
42
|
+
onUpdateState(generate_component_response_1.GenerationStage.ERROR);
|
|
43
|
+
// manually create a message with the error
|
|
44
|
+
const errorMessage = `Error generating component: ${error}`;
|
|
45
|
+
try {
|
|
46
|
+
const errorMessageResponse = await client.beta.threads.messages.create(threadId ?? currentThreadId ?? "", {
|
|
47
|
+
content: [{ type: "text", text: errorMessage }],
|
|
48
|
+
role: "hydra",
|
|
49
|
+
});
|
|
50
|
+
return errorMessageResponse;
|
|
51
|
+
}
|
|
52
|
+
catch (errorError) {
|
|
53
|
+
// Log to the console, there's nothing more we can do!
|
|
54
|
+
console.error(`Error creating error message: ${errorError}`);
|
|
55
|
+
console.error("Original error:", error);
|
|
56
|
+
}
|
|
57
|
+
return {
|
|
58
|
+
renderedComponent: null,
|
|
59
|
+
content: [{ type: "text", text: errorMessage }],
|
|
60
|
+
role: "hydra",
|
|
61
|
+
createdAt: new Date().toISOString(),
|
|
62
|
+
id: crypto.randomUUID(),
|
|
63
|
+
threadId: currentThreadId ?? "",
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
async function processComponentDecision(client, componentList, toolRegistry, currentThreadId, content, message, onUpdateState, options) {
|
|
68
|
+
if (!message.component?.componentName) {
|
|
69
|
+
const componentResponse = {
|
|
70
|
+
...message,
|
|
71
|
+
renderedComponent: null,
|
|
72
|
+
};
|
|
73
|
+
// no component to hydrate, just return the message
|
|
74
|
+
onUpdateState(generate_component_response_1.GenerationStage.COMPLETE);
|
|
75
|
+
return componentResponse;
|
|
76
|
+
}
|
|
77
|
+
if (message.toolCallRequest) {
|
|
78
|
+
onUpdateState(generate_component_response_1.GenerationStage.FETCHING_CONTEXT);
|
|
79
|
+
const toolResult = await (0, tool_caller_1.handleToolCall)(message, toolRegistry);
|
|
80
|
+
onUpdateState(generate_component_response_1.GenerationStage.HYDRATING_COMPONENT);
|
|
81
|
+
try {
|
|
82
|
+
const hydrationResponse = await client.beta.components.hydrate({
|
|
83
|
+
component: (0, registry_1.getComponentFromRegistry)(message.component.componentName, componentList),
|
|
84
|
+
threadId: message.threadId,
|
|
85
|
+
toolResponse: toolResult,
|
|
86
|
+
}, options);
|
|
87
|
+
return await processComponentDecision(client, componentList, toolRegistry, currentThreadId, content, hydrationResponse.message, onUpdateState, options);
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
console.error(error);
|
|
91
|
+
onUpdateState(generate_component_response_1.GenerationStage.ERROR);
|
|
92
|
+
return {
|
|
93
|
+
threadId: message.threadId,
|
|
94
|
+
renderedComponent: null,
|
|
95
|
+
content: [
|
|
96
|
+
{ type: "text", text: `Error hydrating component: ${error}` },
|
|
97
|
+
],
|
|
98
|
+
role: "hydra",
|
|
99
|
+
createdAt: new Date().toISOString(),
|
|
100
|
+
id: crypto.randomUUID(),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
const renderedComponent = react_1.default.createElement((0, registry_1.getComponentFromRegistry)(message.component.componentName, componentList)
|
|
105
|
+
.component, message.component.props);
|
|
106
|
+
const componentResponse = {
|
|
107
|
+
...message,
|
|
108
|
+
renderedComponent: (0, use_current_message_1.wrapWithTamboMessageProvider)(renderedComponent, message.threadId, message.id),
|
|
109
|
+
};
|
|
110
|
+
onUpdateState(generate_component_response_1.GenerationStage.COMPLETE);
|
|
111
|
+
return componentResponse;
|
|
112
|
+
}
|
|
113
|
+
async function* processComponentDecisionStream(stream, componentList, toolRegistry, onUpdateState, client, options) {
|
|
114
|
+
let accumulatedComponentResponse = null;
|
|
115
|
+
for await (const chunk of stream) {
|
|
116
|
+
if (!chunk.component?.componentName) {
|
|
117
|
+
onUpdateState(generate_component_response_1.GenerationStage.STREAMING_RESPONSE);
|
|
118
|
+
accumulatedComponentResponse = {
|
|
119
|
+
...chunk,
|
|
120
|
+
renderedComponent: null,
|
|
121
|
+
};
|
|
122
|
+
yield accumulatedComponentResponse;
|
|
123
|
+
}
|
|
124
|
+
if (chunk.toolCallRequest) {
|
|
125
|
+
if (!chunk.component?.componentName) {
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
onUpdateState(generate_component_response_1.GenerationStage.FETCHING_CONTEXT);
|
|
129
|
+
const toolResult = await (0, tool_caller_1.handleToolCall)(chunk, toolRegistry);
|
|
130
|
+
onUpdateState(generate_component_response_1.GenerationStage.HYDRATING_COMPONENT);
|
|
131
|
+
const streamResponse = await (0, typescript_sdk_1.hydrateStream)(client, {
|
|
132
|
+
component: (0, registry_1.getComponentFromRegistry)(chunk.component?.componentName ?? "", componentList),
|
|
133
|
+
threadId: chunk.threadId,
|
|
134
|
+
toolResponse: toolResult,
|
|
135
|
+
}, options);
|
|
136
|
+
yield* processComponentDecisionStream(handleStream(streamResponse), componentList, toolRegistry, onUpdateState, client, options);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
if (chunk.component?.componentName) {
|
|
140
|
+
try {
|
|
141
|
+
onUpdateState(generate_component_response_1.GenerationStage.STREAMING_RESPONSE);
|
|
142
|
+
// Try to parse and validate accumulated component choice props:
|
|
143
|
+
const messageWithComponent = renderComponentIntoMessage(chunk, componentList);
|
|
144
|
+
// TODO: do we have to do this now
|
|
145
|
+
accumulatedComponentResponse = {
|
|
146
|
+
...accumulatedComponentResponse,
|
|
147
|
+
...messageWithComponent,
|
|
148
|
+
};
|
|
149
|
+
yield messageWithComponent;
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
console.error(error);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
onUpdateState(generate_component_response_1.GenerationStage.COMPLETE);
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Generate a message that has a component rendered into it, if the message came with one
|
|
160
|
+
*/
|
|
161
|
+
function renderComponentIntoMessage(message, componentList) {
|
|
162
|
+
if (!message.component?.componentName) {
|
|
163
|
+
throw new Error("Component not found");
|
|
164
|
+
}
|
|
165
|
+
const parsedProps = (0, partial_json_1.parse)(JSON.stringify(message.component.props));
|
|
166
|
+
const registeredComponent = (0, registry_1.getComponentFromRegistry)(message.component.componentName, componentList);
|
|
167
|
+
const validatedProps = registeredComponent.props instanceof zod_1.z.ZodType
|
|
168
|
+
? registeredComponent.props.parse(parsedProps)
|
|
169
|
+
: parsedProps;
|
|
170
|
+
const renderedComponent = react_1.default.createElement(registeredComponent.component, validatedProps);
|
|
171
|
+
const wrappedComponent = (0, use_current_message_1.wrapWithTamboMessageProvider)(renderedComponent, message.threadId, message.id);
|
|
172
|
+
return {
|
|
173
|
+
...message,
|
|
174
|
+
component: {
|
|
175
|
+
...message.component,
|
|
176
|
+
props: validatedProps,
|
|
177
|
+
},
|
|
178
|
+
renderedComponent: wrappedComponent,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
async function* handleStream(stream) {
|
|
182
|
+
let threadMessage = {
|
|
183
|
+
threadId: "",
|
|
184
|
+
content: [],
|
|
185
|
+
role: "hydra",
|
|
186
|
+
createdAt: new Date().toISOString(),
|
|
187
|
+
id: crypto.randomUUID(),
|
|
188
|
+
};
|
|
189
|
+
try {
|
|
190
|
+
for await (const chunk of stream) {
|
|
191
|
+
threadMessage = {
|
|
192
|
+
...threadMessage,
|
|
193
|
+
...chunk,
|
|
194
|
+
};
|
|
195
|
+
yield threadMessage;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
catch (error) {
|
|
199
|
+
console.error("Error processing stream:", error);
|
|
200
|
+
yield {
|
|
201
|
+
threadId: "",
|
|
202
|
+
content: [{ type: "text", text: `Error processing stream: ${error}` }],
|
|
203
|
+
role: "hydra",
|
|
204
|
+
createdAt: new Date().toISOString(),
|
|
205
|
+
id: crypto.randomUUID(),
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
//# sourceMappingURL=generate-component.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generate-component.js","sourceRoot":"","sources":["../../src/util/generate-component.ts"],"names":[],"mappings":";;;;;AAuBA,gDA+FC;AAiKD,gEAoCC;AA3TD,6DAGkC;AAClC,+CAAqC;AACrC,kDAA0B;AAC1B,6BAAwB;A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CAAC;QACf,OAAO,CAAC,KAAK,CAAC,0BAA0B,EAAE,KAAK,CAAC,CAAC;QACjD,MAAM;YACJ,QAAQ,EAAE,EAAE;YACZ,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,4BAA4B,KAAK,EAAE,EAAE,CAAC;YACtE,IAAI,EAAE,OAAO;YACb,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACnC,EAAE,EAAE,MAAM,CAAC,UAAU,EAAE;SACxB,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import TamboAI, {\n generateStream,\n hydrateStream,\n} from \"@tambo-ai/typescript-sdk\";\nimport { parse } from \"partial-json\";\nimport React from \"react\";\nimport { z } from \"zod\";\nimport { wrapWithTamboMessageProvider } from \"../hooks/use-current-message\";\nimport {\n ComponentRegistry,\n TamboToolAssociations,\n TamboToolRegistry,\n} from \"../model/component-metadata\";\nimport {\n GenerationStage,\n TamboThreadMessage,\n} from \"../model/generate-component-response\";\nimport {\n getAvailableComponents,\n getComponentFromRegistry,\n} from \"../util/registry\";\nimport { handleToolCall } from \"../util/tool-caller\";\n\nexport async function generateAndHydrate(\n client: TamboAI,\n componentList: ComponentRegistry,\n toolRegistry: TamboToolRegistry,\n toolAssociations: TamboToolAssociations,\n currentThreadId: string | undefined,\n content: TamboAI.Beta.Threads.ChatCompletionContentPart[],\n params: TamboAI.Beta.Components.ComponentGenerateParams,\n onUpdateState: (state: GenerationStage) => void,\n stream = false,\n options?: TamboAI.RequestOptions,\n): Promise<TamboThreadMessage | AsyncIterable<TamboThreadMessage>> {\n const availableComponents = getAvailableComponents(\n componentList,\n toolRegistry,\n toolAssociations,\n );\n let threadId = currentThreadId;\n\n onUpdateState(GenerationStage.CHOOSING_COMPONENT);\n try {\n if (stream) {\n const streamResponse = await generateStream(\n client,\n {\n availableComponents,\n contextKey: params.contextKey,\n content,\n threadId:\n params.threadId === \"placeholder\" ? undefined : params.threadId,\n },\n options,\n );\n\n return processComponentDecisionStream(\n handleStream(\n streamResponse as AsyncIterable<TamboAI.ComponentGenerateResponse>,\n ),\n componentList,\n toolRegistry,\n onUpdateState,\n client,\n options,\n );\n }\n const response = await client.beta.components.generate(\n {\n availableComponents,\n contextKey: params.contextKey,\n content,\n threadId:\n params.threadId === \"placeholder\" ? undefined : params.threadId,\n },\n options,\n );\n // Capture the current threadId in case the following processComponentDecision fails\n threadId = response.message.threadId;\n return await processComponentDecision(\n client,\n componentList,\n toolRegistry,\n response.message.threadId,\n content,\n response.message,\n onUpdateState,\n options,\n );\n } catch (error) {\n console.error(error);\n onUpdateState(GenerationStage.ERROR);\n // manually create a message with the error\n const errorMessage = `Error generating component: ${error}`;\n try {\n const errorMessageResponse = await client.beta.threads.messages.create(\n threadId ?? currentThreadId ?? \"\",\n {\n content: [{ type: \"text\", text: errorMessage }],\n role: \"hydra\",\n },\n );\n return errorMessageResponse;\n } catch (errorError) {\n // Log to the console, there's nothing more we can do!\n console.error(`Error creating error message: ${errorError}`);\n console.error(\"Original error:\", error);\n }\n return {\n renderedComponent: null,\n content: [{ type: \"text\", text: errorMessage }],\n role: \"hydra\",\n createdAt: new Date().toISOString(),\n id: crypto.randomUUID(),\n threadId: currentThreadId ?? \"\",\n };\n }\n}\n\nasync function processComponentDecision(\n client: TamboAI,\n componentList: ComponentRegistry,\n toolRegistry: TamboToolRegistry,\n currentThreadId: string,\n content: TamboAI.Beta.Components.ComponentGenerateParams[\"content\"],\n message: TamboAI.Beta.Threads.ThreadMessage,\n onUpdateState: (state: GenerationStage) => void,\n options?: TamboAI.RequestOptions,\n): Promise<TamboThreadMessage> {\n if (!message.component?.componentName) {\n const componentResponse: TamboThreadMessage = {\n ...message,\n renderedComponent: null,\n };\n // no component to hydrate, just return the message\n onUpdateState(GenerationStage.COMPLETE);\n return componentResponse;\n }\n\n if (message.toolCallRequest) {\n onUpdateState(GenerationStage.FETCHING_CONTEXT);\n const toolResult = await handleToolCall(message, toolRegistry);\n onUpdateState(GenerationStage.HYDRATING_COMPONENT);\n try {\n const hydrationResponse = await client.beta.components.hydrate(\n {\n component: getComponentFromRegistry(\n message.component.componentName,\n componentList,\n ),\n threadId: message.threadId,\n\n toolResponse: toolResult,\n },\n options,\n );\n return await processComponentDecision(\n client,\n componentList,\n toolRegistry,\n currentThreadId,\n content,\n hydrationResponse.message,\n onUpdateState,\n options,\n );\n } catch (error) {\n console.error(error);\n onUpdateState(GenerationStage.ERROR);\n return {\n threadId: message.threadId,\n renderedComponent: null,\n content: [\n { type: \"text\", text: `Error hydrating component: ${error}` },\n ],\n role: \"hydra\",\n createdAt: new Date().toISOString(),\n id: crypto.randomUUID(),\n };\n }\n }\n\n const renderedComponent = React.createElement(\n getComponentFromRegistry(message.component.componentName, componentList)\n .component,\n message.component.props,\n );\n const componentResponse: TamboThreadMessage = {\n ...message,\n renderedComponent: wrapWithTamboMessageProvider(\n renderedComponent,\n message.threadId,\n message.id,\n ),\n };\n\n onUpdateState(GenerationStage.COMPLETE);\n return componentResponse;\n}\n\nasync function* processComponentDecisionStream(\n stream: AsyncIterable<TamboThreadMessage>,\n componentList: ComponentRegistry,\n toolRegistry: TamboToolRegistry,\n onUpdateState: (state: GenerationStage) => void,\n client: TamboAI,\n options?: TamboAI.RequestOptions,\n): AsyncGenerator<TamboThreadMessage> {\n let accumulatedComponentResponse: TamboThreadMessage | null = null;\n\n for await (const chunk of stream) {\n if (!chunk.component?.componentName) {\n onUpdateState(GenerationStage.STREAMING_RESPONSE);\n accumulatedComponentResponse = {\n ...chunk,\n renderedComponent: null,\n };\n yield accumulatedComponentResponse;\n }\n\n if (chunk.toolCallRequest) {\n if (!chunk.component?.componentName) {\n continue;\n }\n onUpdateState(GenerationStage.FETCHING_CONTEXT);\n const toolResult = await handleToolCall(chunk, toolRegistry);\n onUpdateState(GenerationStage.HYDRATING_COMPONENT);\n const streamResponse = await hydrateStream(\n client,\n {\n component: getComponentFromRegistry(\n chunk.component?.componentName ?? \"\",\n componentList,\n ),\n threadId: chunk.threadId,\n toolResponse: toolResult,\n },\n options,\n );\n\n yield* processComponentDecisionStream(\n handleStream(\n streamResponse as AsyncIterable<TamboAI.ComponentHydrateResponse>,\n ),\n componentList,\n toolRegistry,\n onUpdateState,\n client,\n options,\n );\n return;\n }\n\n if (chunk.component?.componentName) {\n try {\n onUpdateState(GenerationStage.STREAMING_RESPONSE);\n // Try to parse and validate accumulated component choice props:\n const messageWithComponent = renderComponentIntoMessage(\n chunk,\n componentList,\n );\n // TODO: do we have to do this now\n accumulatedComponentResponse = {\n ...accumulatedComponentResponse,\n ...messageWithComponent,\n };\n yield messageWithComponent;\n } catch (error) {\n console.error(error);\n }\n }\n }\n onUpdateState(GenerationStage.COMPLETE);\n}\n\n/**\n * Generate a message that has a component rendered into it, if the message came with one\n */\nexport function renderComponentIntoMessage(\n message: TamboAI.Beta.Threads.ThreadMessage,\n componentList: ComponentRegistry,\n): TamboThreadMessage {\n if (!message.component?.componentName) {\n throw new Error(\"Component not found\");\n }\n const parsedProps = parse(JSON.stringify(message.component.props));\n const registeredComponent = getComponentFromRegistry(\n message.component.componentName,\n componentList,\n );\n\n const validatedProps =\n registeredComponent.props instanceof z.ZodType\n ? registeredComponent.props.parse(parsedProps)\n : parsedProps;\n\n const renderedComponent = React.createElement(\n registeredComponent.component,\n validatedProps,\n );\n const wrappedComponent = wrapWithTamboMessageProvider(\n renderedComponent,\n message.threadId,\n message.id,\n );\n\n return {\n ...message,\n component: {\n ...message.component,\n props: validatedProps,\n },\n renderedComponent: wrappedComponent,\n };\n}\n\nasync function* handleStream(\n stream: AsyncIterable<\n TamboAI.ComponentGenerateResponse | TamboAI.ComponentHydrateResponse\n >,\n): AsyncGenerator<TamboAI.Beta.Threads.ThreadMessage> {\n let threadMessage: TamboAI.Beta.Threads.ThreadMessage = {\n threadId: \"\",\n content: [],\n role: \"hydra\",\n createdAt: new Date().toISOString(),\n id: crypto.randomUUID(),\n };\n\n try {\n for await (const chunk of stream) {\n threadMessage = {\n ...threadMessage,\n ...chunk,\n };\n yield threadMessage;\n }\n } catch (error) {\n console.error(\"Error processing stream:\", error);\n yield {\n threadId: \"\",\n content: [{ type: \"text\", text: `Error processing stream: ${error}` }],\n role: \"hydra\",\n createdAt: new Date().toISOString(),\n id: crypto.randomUUID(),\n };\n }\n}\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.threadMessagesToLegacyMessages = threadMessagesToLegacyMessages;
|
|
4
|
+
function threadMessagesToLegacyMessages(messages) {
|
|
5
|
+
return messages
|
|
6
|
+
.map((m) => ({
|
|
7
|
+
sender: m.role,
|
|
8
|
+
message: m.content[0].text ?? "",
|
|
9
|
+
}))
|
|
10
|
+
.filter((m) => !!m.message);
|
|
11
|
+
}
|
|
12
|
+
//# sourceMappingURL=messages.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"messages.js","sourceRoot":"","sources":["../../src/util/messages.ts"],"names":[],"mappings":";;AAEA,wEAWC;AAXD,SAAgB,8BAA8B,CAC5C,QAA8C;IAE9C,OAAO,QAAQ;SACZ,GAAG,CACF,CAAC,CAAC,EAAwC,EAAE,CAAC,CAAC;QAC5C,MAAM,EAAE,CAAC,CAAC,IAAwB;QAClC,OAAO,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE;KACjC,CAAC,CACH;SACA,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;AAChC,CAAC","sourcesContent":["import TamboAI from \"@tambo-ai/typescript-sdk\";\n\nexport function threadMessagesToLegacyMessages(\n messages: TamboAI.Beta.Threads.ThreadMessage[],\n) {\n return messages\n .map(\n (m): TamboAI.Components.LegacyChatMessage => ({\n sender: m.role as \"user\" | \"hydra\",\n message: m.content[0].text ?? \"\",\n }),\n )\n .filter((m) => !!m.message);\n}\n"]}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { UseMutationResult, UseQueryResult } from "@tanstack/react-query";
|
|
2
|
+
export type CombinedMutationResult<TData = unknown, TError = unknown, TVariables = unknown, TContext = unknown> = Omit<UseMutationResult<TData, TError, TVariables, TContext>, "mutate" | "mutateAsync" | "reset" | "data" | "variables" | "context">;
|
|
3
|
+
export declare function combineMutationResults<TData1, TData2, TError1, TError2>(resultA: UseMutationResult<TData1, TError1, any, any>, resultB: UseMutationResult<TData2, TError2, any, any>): CombinedMutationResult<TData1 | TData2, TError1 | TError2>;
|
|
4
|
+
export type CombinedQueryResult<TData1, TData2, TError1, TError2> = Omit<UseQueryResult<TData1 | TData2, TError1 | TError2>, "data" | "refetch" | "promise">;
|
|
5
|
+
export declare function combineQueryResults<TData1, TData2, TError1, TError2>(resultA: UseQueryResult<TData1, TError1>, resultB: UseQueryResult<TData2, TError2>): CombinedQueryResult<void, void, TError1, TError2>;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.combineMutationResults = combineMutationResults;
|
|
4
|
+
exports.combineQueryResults = combineQueryResults;
|
|
5
|
+
function combineMutationResults(resultA, resultB) {
|
|
6
|
+
{
|
|
7
|
+
return {
|
|
8
|
+
isPending: resultA.isPending || resultB.isPending,
|
|
9
|
+
isSuccess: resultA.isSuccess && resultB.isSuccess,
|
|
10
|
+
isError: resultA.isError || resultB.isError,
|
|
11
|
+
isIdle: resultA.isIdle && resultB.isIdle,
|
|
12
|
+
isPaused: resultA.isPaused || resultB.isPaused,
|
|
13
|
+
submittedAt: resultA.submittedAt || resultB.submittedAt,
|
|
14
|
+
status: resultA.isPending || resultB.isPending
|
|
15
|
+
? "pending"
|
|
16
|
+
: resultA.isError || resultB.isError
|
|
17
|
+
? "error"
|
|
18
|
+
: resultA.isSuccess && resultB.isSuccess
|
|
19
|
+
? "success"
|
|
20
|
+
: "idle",
|
|
21
|
+
error: resultA.error ?? resultB.error,
|
|
22
|
+
failureCount: resultA.failureCount + resultB.failureCount,
|
|
23
|
+
failureReason: resultA.failureReason ?? resultB.failureReason,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function combineQueryResults(resultA, resultB) {
|
|
28
|
+
return {
|
|
29
|
+
isPending: resultA.isPending || resultB.isPending,
|
|
30
|
+
isSuccess: resultA.isSuccess && resultB.isSuccess,
|
|
31
|
+
isError: resultA.isError || resultB.isError,
|
|
32
|
+
isLoading: resultA.isLoading || resultB.isLoading,
|
|
33
|
+
isFetched: resultA.isFetched && resultB.isFetched,
|
|
34
|
+
isFetchedAfterMount: resultA.isFetchedAfterMount && resultB.isFetchedAfterMount,
|
|
35
|
+
isInitialLoading: resultA.isInitialLoading || resultB.isInitialLoading,
|
|
36
|
+
isPaused: resultA.isPaused || resultB.isPaused,
|
|
37
|
+
isLoadingError: resultA.isLoadingError || resultB.isLoadingError,
|
|
38
|
+
isRefetchError: resultA.isRefetchError || resultB.isRefetchError,
|
|
39
|
+
isPlaceholderData: resultA.isPlaceholderData || resultB.isPlaceholderData,
|
|
40
|
+
isStale: resultA.isStale || resultB.isStale,
|
|
41
|
+
isRefetching: resultA.isRefetching || resultB.isRefetching,
|
|
42
|
+
isFetching: resultA.isFetching || resultB.isFetching,
|
|
43
|
+
status: resultA.isPending || resultB.isPending
|
|
44
|
+
? "pending"
|
|
45
|
+
: resultA.isError || resultB.isError
|
|
46
|
+
? "error"
|
|
47
|
+
: resultA.isSuccess && resultB.isSuccess
|
|
48
|
+
? "success"
|
|
49
|
+
: "pending",
|
|
50
|
+
error: resultA.error ?? resultB.error,
|
|
51
|
+
failureCount: resultA.failureCount + resultB.failureCount,
|
|
52
|
+
failureReason: resultA.failureReason ?? resultB.failureReason,
|
|
53
|
+
errorUpdateCount: resultA.errorUpdateCount + resultB.errorUpdateCount,
|
|
54
|
+
fetchStatus: resultA.isFetching || resultB.isFetching
|
|
55
|
+
? "fetching"
|
|
56
|
+
: resultA.isPaused || resultB.isPaused
|
|
57
|
+
? "paused"
|
|
58
|
+
: "idle",
|
|
59
|
+
dataUpdatedAt: Math.max(resultA.dataUpdatedAt, resultB.dataUpdatedAt),
|
|
60
|
+
errorUpdatedAt: Math.max(resultA.errorUpdatedAt, resultB.errorUpdatedAt),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
//# sourceMappingURL=query-utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"query-utils.js","sourceRoot":"","sources":["../../src/util/query-utils.ts"],"names":[],"mappings":";;AAYA,wDAyBC;AAMD,kDAyCC;AAxED,SAAgB,sBAAsB,CACpC,OAAqD,EACrD,OAAqD;IAErD,CAAC;QACC,OAAO;YACL,SAAS,EAAE,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,SAAS;YACjD,SAAS,EAAE,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,SAAS;YACjD,OAAO,EAAE,OAAO,CAAC,OAAO,IAAI,OAAO,CAAC,OAAO;YAC3C,MAAM,EAAE,OAAO,CAAC,MAAM,IAAI,OAAO,CAAC,MAAM;YACxC,QAAQ,EAAE,OAAO,CAAC,QAAQ,IAAI,OAAO,CAAC,QAAQ;YAC9C,WAAW,EAAE,OAAO,CAAC,WAAW,IAAI,OAAO,CAAC,WAAW;YACvD,MAAM,EACJ,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,SAAS;gBACpC,CAAC,CAAC,SAAS;gBACX,CAAC,CAAC,OAAO,CAAC,OAAO,IAAI,OAAO,CAAC,OAAO;oBAClC,CAAC,CAAC,OAAO;oBACT,CAAC,CAAC,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,SAAS;wBACtC,CAAC,CAAC,SAAS;wBACX,CAAC,CAAC,MAAM;YAChB,KAAK,EAAE,OAAO,CAAC,KAAK,IAAI,OAAO,CAAC,KAAK;YACrC,YAAY,EAAE,OAAO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O;gBACT,CAAC,CAAC,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,SAAS;oBACtC,CAAC,CAAC,SAAS;oBACX,CAAC,CAAC,SAAS;QACnB,KAAK,EAAE,OAAO,CAAC,KAAK,IAAI,OAAO,CAAC,KAAK;QACrC,YAAY,EAAE,OAAO,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY;QACzD,aAAa,EAAE,OAAO,CAAC,aAAa,IAAI,OAAO,CAAC,aAAa;QAC7D,gBAAgB,EAAE,OAAO,CAAC,gBAAgB,GAAG,OAAO,CAAC,gBAAgB;QACrE,WAAW,EACT,OAAO,CAAC,UAAU,IAAI,OAAO,CAAC,UAAU;YACtC,CAAC,CAAC,UAAU;YACZ,CAAC,CAAC,OAAO,CAAC,QAAQ,IAAI,OAAO,CAAC,QAAQ;gBACpC,CAAC,CAAC,QAAQ;gBACV,CAAC,CAAC,MAAM;QACd,aAAa,EAAE,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,aAAa,EAAE,OAAO,CAAC,aAAa,CAAC;QACrE,cAAc,EAAE,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,cAAc,EAAE,OAAO,CAAC,cAAc,CAAC;KACzE,CAAC;AACJ,CAAC","sourcesContent":["import { UseMutationResult, UseQueryResult } from \"@tanstack/react-query\";\n\nexport type CombinedMutationResult<\n TData = unknown,\n TError = unknown,\n TVariables = unknown,\n TContext = unknown,\n> = Omit<\n UseMutationResult<TData, TError, TVariables, TContext>,\n \"mutate\" | \"mutateAsync\" | \"reset\" | \"data\" | \"variables\" | \"context\"\n>;\n\nexport function combineMutationResults<TData1, TData2, TError1, TError2>(\n resultA: UseMutationResult<TData1, TError1, any, any>,\n resultB: UseMutationResult<TData2, TError2, any, any>,\n): CombinedMutationResult<TData1 | TData2, TError1 | TError2> {\n {\n return {\n isPending: resultA.isPending || resultB.isPending,\n isSuccess: resultA.isSuccess && resultB.isSuccess,\n isError: resultA.isError || resultB.isError,\n isIdle: resultA.isIdle && resultB.isIdle,\n isPaused: resultA.isPaused || resultB.isPaused,\n submittedAt: resultA.submittedAt || resultB.submittedAt,\n status:\n resultA.isPending || resultB.isPending\n ? \"pending\"\n : resultA.isError || resultB.isError\n ? \"error\"\n : resultA.isSuccess && resultB.isSuccess\n ? \"success\"\n : \"idle\",\n error: resultA.error ?? resultB.error,\n failureCount: resultA.failureCount + resultB.failureCount,\n failureReason: resultA.failureReason ?? resultB.failureReason,\n };\n }\n}\n\nexport type CombinedQueryResult<TData1, TData2, TError1, TError2> = Omit<\n UseQueryResult<TData1 | TData2, TError1 | TError2>,\n \"data\" | \"refetch\" | \"promise\"\n>;\nexport function combineQueryResults<TData1, TData2, TError1, TError2>(\n resultA: UseQueryResult<TData1, TError1>,\n resultB: UseQueryResult<TData2, TError2>,\n): CombinedQueryResult<void, void, TError1, TError2> {\n return {\n isPending: resultA.isPending || resultB.isPending,\n isSuccess: resultA.isSuccess && resultB.isSuccess,\n isError: resultA.isError || resultB.isError,\n isLoading: resultA.isLoading || resultB.isLoading,\n isFetched: resultA.isFetched && resultB.isFetched,\n isFetchedAfterMount:\n resultA.isFetchedAfterMount && resultB.isFetchedAfterMount,\n isInitialLoading: resultA.isInitialLoading || resultB.isInitialLoading,\n isPaused: resultA.isPaused || resultB.isPaused,\n isLoadingError: resultA.isLoadingError || resultB.isLoadingError,\n isRefetchError: resultA.isRefetchError || resultB.isRefetchError,\n isPlaceholderData: resultA.isPlaceholderData || resultB.isPlaceholderData,\n isStale: resultA.isStale || resultB.isStale,\n isRefetching: resultA.isRefetching || resultB.isRefetching,\n isFetching: resultA.isFetching || resultB.isFetching,\n status:\n resultA.isPending || resultB.isPending\n ? \"pending\"\n : resultA.isError || resultB.isError\n ? \"error\"\n : resultA.isSuccess && resultB.isSuccess\n ? \"success\"\n : \"pending\",\n error: resultA.error ?? resultB.error,\n failureCount: resultA.failureCount + resultB.failureCount,\n failureReason: resultA.failureReason ?? resultB.failureReason,\n errorUpdateCount: resultA.errorUpdateCount + resultB.errorUpdateCount,\n fetchStatus:\n resultA.isFetching || resultB.isFetching\n ? \"fetching\"\n : resultA.isPaused || resultB.isPaused\n ? \"paused\"\n : \"idle\",\n dataUpdatedAt: Math.max(resultA.dataUpdatedAt, resultB.dataUpdatedAt),\n errorUpdatedAt: Math.max(resultA.errorUpdatedAt, resultB.errorUpdatedAt),\n };\n}\n"]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import TamboAI from "@tambo-ai/typescript-sdk";
|
|
2
|
+
import { ComponentContextToolMetadata, ComponentRegistry, RegisteredComponent, TamboTool, TamboToolAssociations, TamboToolRegistry } from "../model/component-metadata";
|
|
3
|
+
export declare const getAvailableComponents: (componentRegistry: ComponentRegistry, toolRegistry: TamboToolRegistry, toolAssociations: TamboToolAssociations) => TamboAI.AvailableComponent[];
|
|
4
|
+
export declare const getComponentFromRegistry: (componentName: string, componentRegistry: ComponentRegistry) => RegisteredComponent;
|
|
5
|
+
export declare const getDefaultContextAdditions: () => string[];
|
|
6
|
+
export declare const getClientContext: () => string;
|
|
7
|
+
export declare const mapTamboToolToContextTool: (tool: TamboTool) => ComponentContextToolMetadata;
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.mapTamboToolToContextTool = exports.getClientContext = exports.getDefaultContextAdditions = exports.getComponentFromRegistry = exports.getAvailableComponents = void 0;
|
|
7
|
+
const zod_to_json_schema_1 = __importDefault(require("zod-to-json-schema"));
|
|
8
|
+
const getAvailableComponents = (componentRegistry, toolRegistry, toolAssociations) => {
|
|
9
|
+
const availableComponents = [];
|
|
10
|
+
for (const [name, componentEntry] of Object.entries(componentRegistry)) {
|
|
11
|
+
const associatedToolNames = toolAssociations[name] || [];
|
|
12
|
+
const contextTools = [
|
|
13
|
+
...associatedToolNames.map((toolName) => {
|
|
14
|
+
const tool = toolRegistry[toolName];
|
|
15
|
+
if (!tool)
|
|
16
|
+
return null;
|
|
17
|
+
return (0, exports.mapTamboToolToContextTool)(tool);
|
|
18
|
+
}),
|
|
19
|
+
].filter((tool) => tool !== null);
|
|
20
|
+
availableComponents.push({
|
|
21
|
+
name: componentEntry.name,
|
|
22
|
+
description: componentEntry.description,
|
|
23
|
+
props: componentEntry.props,
|
|
24
|
+
contextTools,
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
return availableComponents;
|
|
28
|
+
};
|
|
29
|
+
exports.getAvailableComponents = getAvailableComponents;
|
|
30
|
+
const getComponentFromRegistry = (componentName, componentRegistry) => {
|
|
31
|
+
const componentEntry = componentRegistry[componentName];
|
|
32
|
+
if (!componentEntry) {
|
|
33
|
+
throw new Error(`Tambo tried to use Component ${componentName}, but it was not found.`);
|
|
34
|
+
}
|
|
35
|
+
return componentEntry;
|
|
36
|
+
};
|
|
37
|
+
exports.getComponentFromRegistry = getComponentFromRegistry;
|
|
38
|
+
const getDefaultContextAdditions = () => {
|
|
39
|
+
const utcOffsetHours = new Date().getTimezoneOffset() / 60;
|
|
40
|
+
const utcOffset = `(UTC${utcOffsetHours > 0 ? "+" : ""}${utcOffsetHours})`;
|
|
41
|
+
return [
|
|
42
|
+
`The current time in user's timezone (${utcOffset}) is: ${new Date().toLocaleString()}`,
|
|
43
|
+
];
|
|
44
|
+
};
|
|
45
|
+
exports.getDefaultContextAdditions = getDefaultContextAdditions;
|
|
46
|
+
const getClientContext = () => {
|
|
47
|
+
const contextAdditions = (0, exports.getDefaultContextAdditions)();
|
|
48
|
+
return contextAdditions.join("\n");
|
|
49
|
+
};
|
|
50
|
+
exports.getClientContext = getClientContext;
|
|
51
|
+
const mapTamboToolToContextTool = (tool) => {
|
|
52
|
+
const parameters = getParametersFromZodFunction(tool.toolSchema);
|
|
53
|
+
return {
|
|
54
|
+
name: tool.name,
|
|
55
|
+
description: tool.description,
|
|
56
|
+
parameters,
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
exports.mapTamboToolToContextTool = mapTamboToolToContextTool;
|
|
60
|
+
const getParametersFromZodFunction = (schema) => {
|
|
61
|
+
const parameters = schema.parameters();
|
|
62
|
+
return parameters.items.map((param, index) => {
|
|
63
|
+
const name = `param${index + 1}`;
|
|
64
|
+
const type = getZodBaseType(param);
|
|
65
|
+
const description = param.description ?? "";
|
|
66
|
+
const isRequired = !param.isOptional();
|
|
67
|
+
const schema = (0, zod_to_json_schema_1.default)(param);
|
|
68
|
+
return {
|
|
69
|
+
name,
|
|
70
|
+
type,
|
|
71
|
+
description,
|
|
72
|
+
isRequired,
|
|
73
|
+
schema,
|
|
74
|
+
};
|
|
75
|
+
});
|
|
76
|
+
};
|
|
77
|
+
const getZodBaseType = (schema) => {
|
|
78
|
+
const typeName = schema._def.typeName;
|
|
79
|
+
switch (typeName) {
|
|
80
|
+
case "ZodString":
|
|
81
|
+
return "string";
|
|
82
|
+
case "ZodNumber":
|
|
83
|
+
return "number";
|
|
84
|
+
case "ZodBoolean":
|
|
85
|
+
return "boolean";
|
|
86
|
+
case "ZodArray":
|
|
87
|
+
return "array";
|
|
88
|
+
case "ZodEnum":
|
|
89
|
+
return "enum";
|
|
90
|
+
case "ZodDate":
|
|
91
|
+
return "date";
|
|
92
|
+
case "ZodObject":
|
|
93
|
+
return "object";
|
|
94
|
+
default:
|
|
95
|
+
console.warn("falling back to string for", typeName);
|
|
96
|
+
return "string";
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
//# sourceMappingURL=registry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"registry.js","sourceRoot":"","sources":["../../src/util/registry.ts"],"names":[],"mappings":";;;;;;AAEA,4EAAiD;AAW1C,MAAM,sBAAsB,GAAG,CACpC,iBAAoC,EACpC,YAA+B,EAC/B,gBAAuC,EACT,EAAE;IAChC,MAAM,mBAAmB,GAAiC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,IAAI;YACJ,WAAW;YACX,UAAU;YACV,MAAM;SACP,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC,CAAC;AAEF,MAAM,cAAc,GAAG,CAAC,MAAoB,EAAU,EAAE;IACtD,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC;IACtC,QAAQ,QAAQ,EAAE,CAAC;QACjB,KAAK,WAAW;YACd,OAAO,QAAQ,CAAC;QAClB,KAAK,WAAW;YACd,OAAO,QAAQ,CAAC;QAClB,KAAK,YAAY;YACf,OAAO,SAAS,CAAC;QACnB,KAAK,UAAU;YACb,OAAO,OAAO,CAAC;QACjB,KAAK,SAAS;YACZ,OAAO,MAAM,CAAC;QAChB,KAAK,SAAS;YACZ,OAAO,MAAM,CAAC;QAChB,KAAK,WAAW;YACd,OAAO,QAAQ,CAAC;QAClB;YACE,OAAO,CAAC,IAAI,CAAC,4BAA4B,EAAE,QAAQ,CAAC,CAAC;YACrD,OAAO,QAAQ,CAAC;IACpB,CAAC;AACH,CAAC,CAAC","sourcesContent":["import TamboAI from \"@tambo-ai/typescript-sdk\";\nimport { z } from \"zod\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\nimport {\n ComponentContextToolMetadata,\n ComponentRegistry,\n ParameterSpec,\n RegisteredComponent,\n TamboTool,\n TamboToolAssociations,\n TamboToolRegistry,\n} from \"../model/component-metadata\";\n\nexport const getAvailableComponents = (\n componentRegistry: ComponentRegistry,\n toolRegistry: TamboToolRegistry,\n toolAssociations: TamboToolAssociations,\n): TamboAI.AvailableComponent[] => {\n const availableComponents: TamboAI.AvailableComponent[] = [];\n\n for (const [name, componentEntry] of Object.entries(componentRegistry)) {\n const associatedToolNames = toolAssociations[name] || [];\n\n const contextTools = [\n ...associatedToolNames.map((toolName) => {\n const tool = toolRegistry[toolName];\n if (!tool) return null;\n return mapTamboToolToContextTool(tool);\n }),\n ].filter((tool): tool is ComponentContextToolMetadata => tool !== null);\n\n availableComponents.push({\n name: componentEntry.name,\n description: componentEntry.description,\n props: componentEntry.props,\n contextTools,\n });\n }\n\n return availableComponents;\n};\n\nexport const getComponentFromRegistry = (\n componentName: string,\n componentRegistry: ComponentRegistry,\n): RegisteredComponent => {\n const componentEntry = componentRegistry[componentName];\n\n if (!componentEntry) {\n throw new Error(\n `Tambo tried to use Component ${componentName}, but it was not found.`,\n );\n }\n\n return componentEntry;\n};\n\nexport const getDefaultContextAdditions = (): string[] => {\n const utcOffsetHours = new Date().getTimezoneOffset() / 60;\n const utcOffset = `(UTC${utcOffsetHours > 0 ? \"+\" : \"\"}${utcOffsetHours})`;\n return [\n `The current time in user's timezone (${utcOffset}) is: ${new Date().toLocaleString()}`,\n ];\n};\n\nexport const getClientContext = (): string => {\n const contextAdditions = getDefaultContextAdditions();\n return contextAdditions.join(\"\\n\");\n};\n\nexport const mapTamboToolToContextTool = (\n tool: TamboTool,\n): ComponentContextToolMetadata => {\n const parameters = getParametersFromZodFunction(tool.toolSchema);\n\n return {\n name: tool.name,\n description: tool.description,\n parameters,\n };\n};\n\nconst getParametersFromZodFunction = (\n schema: z.ZodFunction<any, any>,\n): ParameterSpec[] => {\n const parameters: z.ZodTuple = schema.parameters();\n return parameters.items.map((param, index): ParameterSpec => {\n const name = `param${index + 1}`;\n const type = getZodBaseType(param);\n const description = param.description ?? \"\";\n const isRequired = !param.isOptional();\n const schema = zodToJsonSchema(param);\n\n return {\n name,\n type,\n description,\n isRequired,\n schema,\n };\n });\n};\n\nconst getZodBaseType = (schema: z.ZodTypeAny): string => {\n const typeName = schema._def.typeName;\n switch (typeName) {\n case \"ZodString\":\n return \"string\";\n case \"ZodNumber\":\n return \"number\";\n case \"ZodBoolean\":\n return \"boolean\";\n case \"ZodArray\":\n return \"array\";\n case \"ZodEnum\":\n return \"enum\";\n case \"ZodDate\":\n return \"date\";\n case \"ZodObject\":\n return \"object\";\n default:\n console.warn(\"falling back to string for\", typeName);\n return \"string\";\n }\n};\n"]}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.handleToolCall = void 0;
|
|
4
|
+
const registry_1 = require("./registry");
|
|
5
|
+
const handleToolCall = async (message, toolRegistry) => {
|
|
6
|
+
if (!message?.toolCallRequest?.toolName) {
|
|
7
|
+
throw new Error("Tool name is required");
|
|
8
|
+
}
|
|
9
|
+
const tool = findTool(message.toolCallRequest.toolName, toolRegistry);
|
|
10
|
+
const toolResult = await runToolChoice(message.toolCallRequest, tool);
|
|
11
|
+
return toolResult;
|
|
12
|
+
};
|
|
13
|
+
exports.handleToolCall = handleToolCall;
|
|
14
|
+
const findTool = (toolName, toolRegistry) => {
|
|
15
|
+
const registryTool = toolRegistry[toolName];
|
|
16
|
+
if (!registryTool) {
|
|
17
|
+
throw new Error(`Tool ${toolName} not found in registry`);
|
|
18
|
+
}
|
|
19
|
+
const contextTool = (0, registry_1.mapTamboToolToContextTool)(registryTool);
|
|
20
|
+
return {
|
|
21
|
+
getComponentContext: registryTool.tool,
|
|
22
|
+
definition: contextTool,
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
const runToolChoice = async (toolCallRequest, tool) => {
|
|
26
|
+
// Assumes parameters are in the order they are defined in the tool
|
|
27
|
+
const parameterValues = toolCallRequest.parameters?.map((param) => param.parameterValue) ?? [];
|
|
28
|
+
return tool.getComponentContext(...parameterValues);
|
|
29
|
+
};
|
|
30
|
+
//# sourceMappingURL=tool-caller.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool-caller.js","sourceRoot":"","sources":["../../src/util/tool-caller.ts"],"names":[],"mappings":";;;AAKA,yCAAuD;AAChD,MAAM,cAAc,GAAG,KAAK,EACjC,OAAmC,EACnC,YAA+B,EAC/B,EAAE;IACF,IAAI,CAAC,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,CAAC;QACxC,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;IAC3C,CAAC;IAED,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,eAAe,CAAC,QAAQ,EAAE,YAAY,CAAC,CAAC;IACtE,MAAM,UAAU,GAAG,MAAM,aAAa,CAAC,OAAO,CAAC,eAAe,EAAE,IAAI,CAAC,CAAC;IAEtE,OAAO,UAAU,CAAC;AACpB,CAAC,CAAC;AAZW,QAAA,cAAc,kBAYzB;AAEF,MAAM,QAAQ,GAAG,CAAC,QAAgB,EAAE,YAA+B,EAAE,EAAE;IACrE,MAAM,YAAY,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC;IAE5C,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,MAAM,IAAI,KAAK,CAAC,QAAQ,QAAQ,wBAAwB,CAAC,CAAC;IAC5D,CAAC;IAED,MAAM,WAAW,GAAG,IAAA,oCAAyB,EAAC,YAAY,CAAC,CAAC;IAC5D,OAAO;QACL,mBAAmB,EAAE,YAAY,CAAC,IAAI;QACtC,UAAU,EAAE,WAAW;KACxB,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,aAAa,GAAG,KAAK,EACzB,eAAwC,EACxC,IAA0B,EACZ,EAAE;IAChB,mEAAmE;IACnE,MAAM,eAAe,GACnB,eAAe,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC;IAEzE,OAAO,IAAI,CAAC,mBAAmB,CAAC,GAAG,eAAe,CAAC,CAAC;AACtD,CAAC,CAAC","sourcesContent":["import TamboAI from \"@tambo-ai/typescript-sdk\";\nimport {\n ComponentContextTool,\n TamboToolRegistry,\n} from \"../model/component-metadata\";\nimport { mapTamboToolToContextTool } from \"./registry\";\nexport const handleToolCall = async (\n message: TamboAI.Beta.ThreadMessage,\n toolRegistry: TamboToolRegistry,\n) => {\n if (!message?.toolCallRequest?.toolName) {\n throw new Error(\"Tool name is required\");\n }\n\n const tool = findTool(message.toolCallRequest.toolName, toolRegistry);\n const toolResult = await runToolChoice(message.toolCallRequest, tool);\n\n return toolResult;\n};\n\nconst findTool = (toolName: string, toolRegistry: TamboToolRegistry) => {\n const registryTool = toolRegistry[toolName];\n\n if (!registryTool) {\n throw new Error(`Tool ${toolName} not found in registry`);\n }\n\n const contextTool = mapTamboToolToContextTool(registryTool);\n return {\n getComponentContext: registryTool.tool,\n definition: contextTool,\n };\n};\n\nconst runToolChoice = async (\n toolCallRequest: TamboAI.ToolCallRequest,\n tool: ComponentContextTool,\n): Promise<any> => {\n // Assumes parameters are in the order they are defined in the tool\n const parameterValues =\n toolCallRequest.parameters?.map((param) => param.parameterValue) ?? [];\n\n return tool.getComponentContext(...parameterValues);\n};\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|