ttc-ai-chat-sdk
v1.3.0
Published
TypeScript client sdk for TTC AI services with decorators and schema validation.
Maintainers
Readme
TTC AI Chat SDK
A TypeScript/JavaScript SDK for building custom chat interfaces and integrating AI capabilities into your applications.
Overview
The ttc-ai-chat-sdk provides the core tools for integrating Tentarcles AI into your applications. Use it to send messages, subscribe to real-time events, trigger AI actions, and expose your app's functions to the AI.
Installation
Install the SDK using your preferred package manager:
npm install ttc-ai-chat-sdkQuick Start
Create a Module (Class-based)
Define a module with functions that the AI can call. Use the ttc.describe decorator to document each function and optionally specify an action for UI feedback:
import { ttc } from "ttc-ai-chat-sdk";
import { z } from "zod";
export class MyAppModule {
@ttc.describe({
doc: "Add an item to the user's shopping cart",
action: "Adding item to cart...",
inputSchema: z.object({
productId: z.string(),
quantity: z.number()
})
})
async addToCart(productId: string, quantity: number) {
// Your implementation here
return { success: true, itemsInCart: 3 };
}
@ttc.describe({
doc: "Search for products in the catalog",
action: "Searching products..."
})
async searchProducts(query: string) {
// Your implementation here
return [{ id: "123", name: "Example Product" }];
}
}The action parameter provides a user-friendly message that you can display in your UI while the function executes. Subscribe to action_log event to capture it.
Create a Module (Functional Approach)
Alternatively, you can define modules and functions using a functional approach:
import { ttc } from "ttc-ai-chat-sdk";
import { z } from "zod";
// Create a module
const footballModule = ttc.module('Football');
// Define your function
const shootBall = async (direction: 'left' | 'right' | 'center', power: number) => {
return `Kicked the ball to the ${direction} with power ${power}`;
}
// Add the function to the module
footballModule.add_function({
name: 'kick',
input_schema: z.object({
direction: z.enum(['left', 'right', 'center']),
power: z.number().min(1).max(100)
}),
output_schema: z.string(),
doc: 'Kicks the football in a specified direction with a given power',
func: shootBall
});Initialize the Assistant
Set up the assistant with your chat token and modules. The ttc.assistant() method returns an Assistant instance that you'll use to interact with the AI:
import { ttc } from "ttc-ai-chat-sdk";
import { MyAppModule } from "./modules";
const chatToken = "your-chat-token";
const assistant = ttc.assistant(chatToken, [MyAppModule]);Subscribe to Events
Listen for real-time events like messages, function calls, and status changes using the assistant instance:
// Subscribe to incoming messages
assistant.subscribe("message", (data) => {
const { id, payload } = data;
console.log("New message:", payload);
});
// Subscribe to function calls
assistant.subscribe("function_call", (data) => {
const { id, payload } = data;
console.log("Function called:", payload);
});
// Subscribe to permission requests
assistant.subscribe("permission", async (data) => {
const { id, payload } = data;
console.log("Permission requested:", payload);
await assistant.approveFunction(id, true); // true to approve, false to deny
});
// Subscribe to action_logs to show UI feedback
assistant.subscribe("action_log", (data) => {
const { id, payload } = data;
console.log(payload);
});Send a Message
Send messages to the AI using the assistant's message method:
// Send a message to the AI
assistant.message("Hello, how can you help me today?");Get Chat History
Retrieve previous messages from the conversation:
// Get chat history (limit, page)
const messages = await assistant.history(50, 1);
console.log(messages);Trigger the AI
Programmatically trigger the AI to act based on a message:
// Trigger the AI to perform an action
await assistant.trigger("Check the user's cart and suggest related products");Additional Assistant Methods
// Clear chat messages (soft reset)
await assistant.clearMessages();
// Wipe all assistant memory and chat messages (hard reset)
await assistant.reset();
// Get assistant statistics
const stats = await assistant.stats();
// Set application context for the AI to reference
await assistant.selectContext("User is on the checkout page with 3 items in cart");
// Get available AI models
const models = await assistant.getModels();
// Switch to a different model
await assistant.selectModel("model-id", "llm"); // type: 'llm' | 'stt' | 'tts'Assistant API (Server-Side)
The AssistantAPI allows you to manage assistants from your backend. Use it to create assistants, generate tokens, and manage assistant metadata.
Initialize the Assistant API
import { ttc } from "ttc-ai-chat-sdk";
const apiKey = "your-api-key";
const assistantAPI = ttc.assistantAPI(apiKey);Create an Assistant
Create a new assistant for a user and get a chat token for the frontend:
const result = await assistantAPI.create(
"My Assistant", // name
"user-unique-id-123", // cuid (custom user ID)
{
backstory: "You are a helpful shopping assistant",
emote: "friendly",
traits: "helpful, knowledgeable",
metadata: { theme: "dark" }
}
);
if (result.status === "success") {
const { chatId, token } = result.data;
// Send token to frontend
}Generate a New Token
Generate a fresh token for an existing assistant:
const result = await assistantAPI.generateToken(
"user-unique-id-123", // cuid
"30d" // expiry duration
);
if (result.status === "success") {
const { token } = result.data;
}Validate a Token
Check if a token is still valid:
const result = await assistantAPI.validateToken(token);
if (result.status === "success") {
// result.data.status: 'valid' | 'expired' | 'error' | 'notFound'
console.log("Token status:", result.data.status);
}Fetch Assistants
Get a list of all assistants or fetch a specific one:
// Fetch all assistants (paginated)
const list = await assistantAPI.fetchMany(1, 10, {});
// Fetch a specific assistant by ID or cuid
const assistant = await assistantAPI.fetch({ cuid: "user-unique-id-123" });
// or
const assistant = await assistantAPI.fetch({ id: "assistant-id" });Update an Assistant
Update assistant metadata or persona:
await assistantAPI.update("assistant-id", {
name: "Updated Name",
backstory: "New backstory",
metadata: { theme: "light" }
});Delete an Assistant
await assistantAPI.delete("assistant-id");Express Integration (Auth Server)
For seamless token management, you can integrate with Express to automatically handle token creation and validation:
import express from "express";
import { ttc } from "ttc-ai-chat-sdk";
const app = express();
ttc.assistantAPI("your-api-key", {
express: app,
endpoint: "/ttc-auth",
userData: async (req) => {
// Extract user info from your auth system
const user = await getUserFromRequest(req);
return {
cuid: user.id,
name: user.name,
option: {
backstory: "Helpful assistant for " + user.name,
metadata: { userId: user.id }
}
};
}
});
app.listen(3000);Then on the frontend, initialize the assistant with the auth URL:
const assistant = await ttc.assistant({
modules: [MyAppModule],
url: "http://localhost:3000/ttc-auth",
tokenCb: async () => {
// Return your platform's auth token
return localStorage.getItem("authToken");
}
});Full Documentation
For complete API reference, all available methods, and advanced configuration, check out the full SDK documentation.
