@solomei-ai/thamyr
v3.1.4
Published
JavaScript package for Thamyr
Readme
Thamyr SDK Documentation
Overview
Thamyr is the AI agent within Callimacus that is designed to generate and arrange dynamic, intuitive user interfaces that adapt to user intent and context. By leveraging proprietary AI algorithms, Thamyr transcends traditional typographic approaches to website design, creating a more immersive and context-sensitive experience for users.
Core Concepts
1. Story
A Story is the overarching structure that encapsulates a user's journey, intent, and context. It is made up of multiple Chapters, each representing a distinct part of the interaction. Stories ensure continuity by preserving the user's intent and context, allowing Thamyr to maintain relevance across different interactions.
2. Chapter
A Chapter is a component of a Story that responds to specific user actions or inputs. Each chapter is generated in response to an inputEvent and can evolve based on prior interactions.
3. InputEvent
An inputEvent is any user interaction that triggers Thamyr to respond. Input events can be:
- A click on an element of the website.
- A user query (written or audio).
4. Response
Thamyr processes input events to produce a response, which is made up of different types of blocks. These blocks are the building blocks of the UI and represent different forms of content.
Blocks
A Block is a unit of content generated by Thamyr in response to a user input. Each block can be one of the following types:
- Text Block: A simple textual response or message.
- Image: A visual representation, such as a single image.
- Gallery: A collection of images displayed together.
- Video: A media block containing a video.
- Rich Media: A block that can contain complex content, such as embedded elements or interactive features.
- Topic: A block that introduces a new subject or theme related to the context.
- Custom Element: A user-defined block type that can be customized to meet specific needs or functionalities.
How Thamyr Works
Receiving Input: When an inputEvent occurs (e.g., a user clicks on a button or asks a question), Thamyr receives and processes it. Generating the Story: Based on the input event, Thamyr identifies the appropriate Chapter within the Story and produces a relevant response. Creating Blocks: Thamyr's response consists of one or more blocks, which are then arranged to create the best possible user interface for the given context.
Technical Setup
Prerequisites
Before you begin, ensure that you have the following:
- GitHub Account: You must have a GitHub account to access and contribute to the project.
- Git and Node.js: Ensure you have Git and Node.js installed on your local machine.
- nvm (Node Version Manager): This project uses
nvmto manage Node.js versions. Make sure you have nvm installed.
Cloning the Repository
Access the Repository: After being granted access to the repository, you will receive a link to clone it. Use the following command to clone the repository to your local machine:
git clone https://github.com/your-org/your-repo.gitNavigate to the Repository:
cd your-repo
Installing the Correct Node Version
Install Node Version: The repository contains a
.nvmrcfile that specifies the Node.js version to be used. To install the correct version, run the following command:nvm installThis will automatically install the version of Node.js specified in the
.nvmrcfile.Use the Correct Version: Once the installation is complete, you can use the specified Node version by running:
nvm use
Branching and Development Workflow
Create a Development Branch: The main branch is used for production, so create a new branch for any feature or bug fix. Branches must follow the naming convention:
branch.repo.gymnasium.callimacus.aiExample:
git checkout -b new-feature.repo.gymnasium.callimacus.aiThis ensures that each branch has a unique URL when deployed.
Make Changes: Develop and test your changes locally. Be sure to follow the project's coding conventions.
Commit Messages: Commit messages must follow the guidelines outlined in the Conventional Commits specification. This helps ensure a consistent commit history and automated versioning.
Example commit message:
feat(button): add primary button stylePush Changes: After completing your work, commit your changes and push them to GitHub:
git add . git commit -m "feat(new-feature): implement new feature" git push origin new-feature.repo.gymnasium.callimacus.ai
Credentials Management
Basic HTTP Authentication: All deployed URLs are protected by basic HTTP authentication. You can manage the credentials for these URLs via the Callimacus Backoffice.
Client ID: Callimacus requires a Client ID (
cal-pk-…) for authentication to function properly. To use it, initialize the Callimacus instance with your Client ID as shown below:const instance = new Thamyr({ clientId: import.meta.env.VITE_CALLIMACUS_CLIENT_ID, });You can manage and retrieve your Client ID via the Callimacus Backoffice. Make sure to securely store the Client ID and use it in the appropriate environment variables (
VITE_CALLIMACUS_CLIENT_ID).
Code Quality Checks
Before merging your code into the main branch, ensure that your code passes the quality checks. These checks include:
- Linting: To check the code style and ensure best practices.
- Code Coverage: To ensure adequate testing and test coverage for your changes.
The quality checks are automatically run through the CI pipeline when a pull request (PR) is created. However, you can run them locally before pushing your changes:
npm run build && npm run lint && npm run test- Linting: This command will check for code style issues.
- Testing: This command will run tests to verify that your code behaves as expected.
Creating a Pull Request (PR)
Open a PR: Once your code is ready, create a pull request (PR) from your branch (e.g.,
new-feature.repo.gymnasium.callimacus.ai) to themainbranch.Passing Quality Checks: Ensure that the CI pipeline passes all checks (linting, tests, and coverage) before merging. You can monitor the PR’s status for any errors or failed checks.
Merge to Main: After the PR passes all checks and gets reviewed, you can merge it into the
mainbranch. This will trigger the deployment to production.
Deployment
- Frontend Hosting: The frontend is automatically hosted by Callimacus. Once merged to the
mainbranch, the latest changes will be deployed to the production environment. - Preview Environments: Each branch you create will automatically have a unique preview URL under the format
branch.repo.gymnasium.callimacus.ai.
Troubleshooting
Quality Check Failures: If your PR fails any quality checks, review the error messages in the CI pipeline. Typically, these errors are related to linting or failing tests. Run
npm run lintandnpm run testlocally to identify and fix issues before pushing again.Branch Naming Issues: Ensure that your branch name follows the correct format. If the branch name does not match the required pattern, it may not be deployed to a preview environment.
Merge Conflicts: If you encounter merge conflicts, resolve them by pulling the latest changes from the
mainbranch and updating your feature branch:git pull origin main
How to Use the Thamyr SDK
Setup and Initialization
To use the Thamyr SDK in your project, follow these steps:
Install the SDK: First, you need to install the Thamyr SDK package. Run the following command in your project directory:
npm install @solomei-ai/thamyrInitialize Thamyr: In your React component, initialize the
Thamyrinstance with your Client ID, which is required for API interaction. The Client ID is typically stored in an environment variable for security purposes.Example:
import { useEffect, useRef, useState } from 'react'; import { Thamyr, ThamyrResponseType } from '@solomei-ai/thamyr'; function App() { const [chapters, setChapters] = useState([]); const thamyrRef = useRef(null); useEffect(() => { const instance = new Thamyr({ clientId: import.meta.env.VITE_CALLIMACUS_CLIENT_ID, }); thamyrRef.current = instance; instance.onResponse(response => { if (response.type === ThamyrResponseType.CHAPTER_EVENT) { setChapters(prev => { const existingIndex = prev.findIndex(c => c.id === response.chapter.id); if (existingIndex !== -1) { const updated = [...prev]; updated[existingIndex] = response.chapter; return updated; } else { return [...prev, response.chapter]; } }); } }); }, []); }Tip: Building with React?
@solomei-ai/thamyr-reactwraps this SDK in hooks (useInitThamyr({clientId}),useThamyr,useConnection,useOnResponse,useOnConnectionChange,useOnError,useApi,useCart,useSkesis,useSitemap,useCallimacusStore, plususeVoiceRecorderanduseTtsAudiofor voice input and text-to-speech playback) so you never manage the instance yourself.
Sending User Input
To trigger interactions and send user input, you'll need to handle user events like text input or clicks. In the example below, we send a question as an input event.
Handle User Input: Collect user input (e.g., from a text box) and send it to Thamyr as an input event.
import { UserInteractionType, SLInputEventType } from '@solomei-ai/thamyr'; const handleAsk = () => { const inputSL = { type: SLInputEventType.question, // Type of input event data: { value: inputText } // User's input text }; setInputText("Type your next question"); thamyrRef.current?.sendUserInteraction(UserInteractionType.CREATE_ROUND, { inputEvent: inputSL, }); };Triggering User Interaction: When the user presses the Enter key, you send the question to Thamyr.
const handleKeyDown = (e) => { if (e.key === "Enter") { e.preventDefault(); handleAsk(); } };
Rendering Blocks
Thamyr responds with different types of content blocks based on the input events. You can render these blocks in your UI using a switch-case structure or dynamic rendering.
In the provided code, blocks are rendered based on their type. For example:
- Text Block: Displayed as plain text.
- Image Block: Displayed as an image.
- Video Block: Displayed as a video.
Here's an example of how to render different block types:
const BlockRenderer = ({ block }) => {
switch (block.type) {
case "demosthenesResponse":
return <TextBlock data={block.data} />;
case "image":
return <ImageBlock data={block.data} />;
case "video":
return <VideoBlock data={block.data} />;
case "gallery":
return <GalleryNew data={block.data} />;
default:
return <div>Unsupported block type: {block.type}</div>;
}
};Full Example of Block Rendering in Action
return (
<div className="App">
<div>
{chapters.length > 0 ? (
chapters.map((item, idx) => (
item.status === ChapterStatus.understandingQuery ? (
<p key={idx + 1}>Loading...</p>
) : (
<div key={idx + 1}>
{item.blocks?.map(block => (
<BlockRenderer key={block.id} block={block} />
))}
</div>
)
))
) : <p key={0}></p>}
</div>
<input
type="text"
value={inputText}
onChange={e => setInputText(e.target.value)}
placeholder="Type your question"
onKeyDown={handleKeyDown}
/>
</div>
);(ChapterStatus is exported from @solomei-ai/thamyr.)
Example of a Block Component (ImageBlock)
const ImageBlock = ({ data }) => {
return <img src={data.url} alt={data.content} className="rounded-lg shadow-lg" />;
};
export default ImageBlock;API Namespaces
The Thamyr SDK organizes its APIs into logical namespaces for better code organization and discoverability.
Available Namespaces
content- Pages, topics, and documentsstories- Story sharingproducts- Product recommendations and similaritywhisper- Whisper messagesanalytics- Event tracking and analyticscart- Shopping cart operationsskesis- Similar and related skesis itemssitemap- Site map retrieval
The content, stories, products, whisper, analytics, and cart methods mirror the platform API one-to-one: each takes a single parameters object (parameterless reads like cart.getCart take none), resolves {data, error, response}, and new endpoints appear as methods automatically with SDK releases. The skesis and sitemap namespaces keep their classic signatures (positional arguments, promises that resolve to the value directly).
Working with Results
Platform API calls resolve {data, error, response} and never throw on HTTP errors — check error (or response.status) instead of wrapping calls in try/catch:
const thamyr = new Thamyr({
clientId: import.meta.env.VITE_CALLIMACUS_CLIENT_ID,
});
const { data: page, error } = await thamyr.content.getPage({ language: 'en', id: 'home' });
if (error) {
console.error('Could not load page:', error);
} else {
renderPage(page);
}"Not found" is a value too: on a 404, data is undefined and response.status === 404. If you prefer exceptions, opt in per call with the second options argument:
const { data } = await thamyr.content.getPage({ language: 'en', id: 'home' }, { throwOnError: true });Content API
Access pages, topics, and documents. language is required — pass your locale explicitly:
// Get a page by ID
const { data: page } = await thamyr.content.getPage({ language: 'en', id: 'home' });
// List topics
const { data: topics } = await thamyr.content.listTopics({ language: 'en' });
// Get the contents of a topic
const { data: contents } = await thamyr.content.getTopicContents({ language: 'en', idOrSlug: 'running' });
// Get a document by slug, group, or sitemap path
const { data: bySlug } = await thamyr.content.getDocumentBySlug({ language: 'en', slug: 'about-us' });
const { data: byGroup } = await thamyr.content.getDocumentByGroup({ language: 'en', groupId: 'group-42' });
const { data: byPath } = await thamyr.content.getDocumentByPath({ path: '/en/about-us' });Stories API
Share a story and retrieve shared stories:
// Create a shareable link for a story
const { data: share } = await thamyr.stories.share({ id: 'story-123' });
// Get a shared story
const { data: shared } = await thamyr.stories.getShared({ id: 'share-id-123' });Products API
Get product recommendations and similar items:
// Get similar products
const { data: similar } = await thamyr.products.getSimilar({ productId: 'product-123', topK: 10 });
// Get product recommendations
const { data: recommendations } = await thamyr.products.getRecommendations({ productId: 'product-123' });Whisper API
Fetch the latest whisper for a story (a 404 simply means there is none yet):
const { data, response } = await thamyr.whisper.getLast({ storyId: 'story-123' });
if (response.status !== 404) {
showWhisper(data?.whisper);
}Analytics API
Track an event for a single content item:
void thamyr.analytics.trackEvent({
storyId: 'story-123',
eventName: 'content_click',
content: 'doc-42',
});Track a “generic” event (no content id) — omit content if you don’t have content associated with the event:
void thamyr.analytics.trackEvent({
storyId: 'story-123',
eventName: 'button_click',
payload: { buttonId: 'cta-primary', timestamp: Date.now() },
});Track both content and custom payload:
void thamyr.analytics.trackEvent({
storyId: 'story-123',
eventName: 'content_click',
content: 'doc-42',
payload: {
source: 'carousel',
position: 2,
highlighted: true,
},
});Cart API
Manage shopping cart operations. Like every contract namespace, cart methods take a flat parameters object and resolve the {data, error, response} envelope — the basket is data, and HTTP failures arrive as error, never as a rejection. The basket shape is Salesforce's own published SFCC schema (Basket).
// Get current cart
const {data: cart, error} = await thamyr.cart.getCart();
// Add item to cart
const {data: updated} = await thamyr.cart.addItemToCart({productId: 'product-123'});
// Remove item from cart
await thamyr.cart.removeItemFromCart({productId: 'product-123'});
// Update product quantity
await thamyr.cart.updateProductQuantity({productId: 'product-123', quantity: 5});Skesis and Sitemap APIs
// Similar and related skesis items
const similar = await thamyr.skesis.similar('item-123', { topK: 4 });
const related = await thamyr.skesis.related('item-123');
// Full site map
const sitemap = await thamyr.sitemap.getSitemap();Upgrading from v1
v2 removes the deprecated accessToken initialization key, the flat instance-level wrappers (thamyr.getPage(...), thamyr.getCart(), and friends), and likeResponse. See MIGRATION.md for the full v1 → v2 mapping.
