@santillana-ai/typescript-tutor-sdk
v5.9.0
Published
TypeScript SDK for integrating Santillana's AI-powered tutoring system into educational applications.
Readme
Santillana AI Tutor SDK
TypeScript SDK for integrating Santillana's AI-powered tutoring system into educational applications.
📚 Table of Contents
- Introduction
- Installation
- Configuration
- Quick Start
- Core Features
- Implementation Examples
- API Reference
- Error Handling
- Support
Introduction
Santillana AI Tutor SDK provides a simple, type-safe interface for interacting with the intelligent tutoring system. It enables management of learning activities, personalized tutoring sessions, and real-time communication with the AI agent.
🚀 Key Features
- Pedagogical AI Tutor: Specialized tutoring system with Socratic method
- Flexible Sessions: With structured activities or free-form
- Content Adaptation: Universal Design for Learning (DUA) principles for inclusive content
- Native TypeScript: Full autocomplete and type-safety
- Easy Integration: Compatible with Next.js, React, and Node.js
Installation
🎯 Quick Start with Template
The fastest way to get started is using our Next.js template:
npx @santillana-ai/create-tutor-app@latest my-tutor-app
cd my-tutor-app
npm run dev📦 Manual Installation
NPM
npm install @santillana-ai/typescript-tutor-sdkPNPM
pnpm add @santillana-ai/typescript-tutor-sdkBun
bun add @santillana-ai/typescript-tutor-sdkYarn
yarn add @santillana-ai/typescript-tutor-sdk zodNote: Yarn requires manually installing
zodas a peer dependency.
Configuration
1. Get API Key
Request your API Key from the Santillana AI Tutor administration system.
2. Environment Variables Setup
Create a .env.local file in your project:
SANTILLANA_API_KEY=sk_live_your_api_key_here
SANTILLANA_API_URL=https://ai-tutor-sdk-api.vercel.app3. Initialize SDK
import { SDK } from '@santillana-ai/typescript-tutor-sdk';
const sdk = new SDK({
apiKey: process.env.SANTILLANA_API_KEY!,
serverURL: process.env.SANTILLANA_API_URL || 'https://ai-tutor-sdk-api.vercel.app'
});Quick Start
Basic Example
// 1. List available activities
const activities = await sdk.activities.findAll({
limit: 10,
offset: 0
});
// 2. Start session with an activity
const session = await sdk.sessions.startSession({
activityId: activities.data[0].id,
studentId: 'student-123'
});
// 3. Send message to tutor
const response = await sdk.sessions.sendMessage({
sessionId: session.data.session.id,
content: 'Can you help me with this exercise?'
});
console.log('Tutor:', response.data.assistantMessage.content);Core Features
Activity Management
Activities are structured learning units with objectives, exercises, and evaluation.
// Get all activities
const activities = await sdk.activities.findAll({
limit: 20,
offset: 0
});
// Get specific activity with exercises
const activity = await sdk.activities.findOne({
id: 'activity-id'
});
// Get exercises from an activity
const exercises = await sdk.activities.getExercises({
activityId: 'activity-id'
});Activity Sessions
Activity sessions provide a structured and guided learning experience.
// Start session with activity
const session = await sdk.sessions.startSession({
activityId: 'activity-id',
studentId: 'student-123'
});
// Send message to the tutor
const response = await sdk.sessions.sendMessage({
sessionId: session.data.session.id,
content: "I don't understand this concept"
});
// View student progress
const progress = await sdk.sessions.getSessionProgress({
sessionId: session.data.session.id
});Free Sessions
Perfect for quick questions, topic exploration, or self-directed learning.
// Start free session with custom configuration
const freeSession = await sdk.freeSessions.startFreeSession({
userId: 'student-123',
config: {
enableSocraticMethod: true, // Guide with reflective questions
enableBloomTaxonomy: true, // Gradual progression
topic: 'Mathematics',
learningObjective: 'Understand fractions'
}
});
// Send message in free session
const response = await sdk.freeSessions.sendFreeSessionMessage({
sessionId: freeSession.data.session.id,
sendFreeSessionMessageDto: {
content: 'What is a fraction?'
}
});Content Adaptation Tool
Adapt any educational content using Universal Design for Learning (DUA) principles to make it more accessible and inclusive.
Available DUA Features
Representation (Multiple ways to present information):
r1_simplifiedLanguage: Simplify vocabulary and sentence structurer2_visualSupports: Add visual aids and diagrams suggestionsr3_audioSupports: Include detailed audio descriptionsr4_languageScaffolds: Add definitions and language support
Engagement (Multiple ways to motivate):
e5_chunkingTime: Break content into manageable segmentse6_interestsChoice: Provide choices based on interestse7_collaboration: Include collaborative elements
Action & Expression (Multiple ways to demonstrate learning):
a8_guidedSteps: Provide step-by-step instructionsa9_alternativeOutputs: Allow different response formatsa10_fineMotorSupports: Adapt for motor difficultiesa11_processingSpeed: Adjust for different processing speeds
Basic Usage
// Simple content adaptation
const adaptedContent = await sdk.tools.adaptContent({
content: "The water cycle consists of evaporation, condensation, and precipitation.",
duaFeatures: {
representation: {
r1_simplifiedLanguage: true,
r2_visualSupports: true
}
},
metadata: {
subject: "Science",
grade: "4th grade",
language: "es"
}
});
// Access the adapted content
console.log(adaptedContent.adaptedContent);
console.log(adaptedContent.appliedFeatures);
console.log(adaptedContent.suggestions);Comprehensive Adaptation
// Apply multiple DUA features for inclusive content
const fullAdaptation = await sdk.tools.adaptContent({
content: "Photosynthesis is the process by which plants convert light energy into chemical energy stored in glucose.",
duaFeatures: {
representation: {
r1_simplifiedLanguage: true,
r2_visualSupports: true,
r4_languageScaffolds: true
},
engagement: {
e5_chunkingTime: true,
e6_interestsChoice: true
},
actionExpression: {
a8_guidedSteps: true,
a9_alternativeOutputs: true
}
},
metadata: {
subject: "Biology",
grade: "7th grade",
context: "Students with diverse learning needs"
}
});Example Use Cases
For Visual Learners
const adapted = await sdk.tools.adaptContent({
content: "Complex mathematical concepts...",
duaFeatures: {
representation: {
r2_visualSupports: true,
r4_languageScaffolds: true
}
}
});For Students with Attention Challenges
const adapted = await sdk.tools.adaptContent({
content: "Long historical text...",
duaFeatures: {
engagement: {
e5_chunkingTime: true,
e6_interestsChoice: true
},
representation: {
r1_simplifiedLanguage: true
}
}
});For Diverse Learning Styles
const adapted = await sdk.tools.adaptContent({
content: "Science experiment instructions...",
duaFeatures: {
actionExpression: {
a8_guidedSteps: true,
a9_alternativeOutputs: true,
a11_processingSpeed: true
}
}
});Implementation Examples
Next.js: Chat Component
'use client';
import { useState } from 'react';
import { SDK } from '@santillana-ai/typescript-tutor-sdk';
const sdk = new SDK({
apiKey: process.env.NEXT_PUBLIC_SANTILLANA_API_KEY!
});
export function ChatTutor({ studentId }: { studentId: string }) {
const [sessionId, setSessionId] = useState<string>('');
const [messages, setMessages] = useState<any[]>([]);
const [input, setInput] = useState('');
// Start free session
const startSession = async () => {
const session = await sdk.freeSessions.startFreeSession({
userId: studentId,
config: {
enableSocraticMethod: true,
enableBloomTaxonomy: true
}
});
setSessionId(session.data.session.id);
};
// Send message
const sendMessage = async () => {
if (!input.trim() || !sessionId) return;
const response = await sdk.freeSessions.sendFreeSessionMessage({
sessionId,
sendFreeSessionMessageDto: {
content: input
}
});
setMessages([
...messages,
{ role: 'user', content: input },
{ role: 'assistant', content: response.data.assistantMessage.content }
]);
setInput('');
};
return (
<div className="chat-container">
{!sessionId ? (
<button onClick={startSession}>Start Session</button>
) : (
<>
{/* Messages */}
<div className="messages">
{messages.map((msg, idx) => (
<div key={idx} className={`message ${msg.role}`}>
{msg.content}
</div>
))}
</div>
{/* Input */}
<div className="input-area">
<input
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
placeholder="Type your question..."
/>
<button onClick={sendMessage}>Send</button>
</div>
</>
)}
</div>
);
}API Route in Next.js
// app/api/sessions/start/route.ts
import { NextResponse } from 'next/server';
import { SDK } from '@santillana-ai/typescript-tutor-sdk';
const sdk = new SDK({
apiKey: process.env.SANTILLANA_API_KEY!
});
export async function POST(request: Request) {
const body = await request.json();
const { userId, accessibilityProfile } = body;
try {
const session = await sdk.freeSessions.startFreeSession({
userId,
config: {
enableSocraticMethod: true,
enableBloomTaxonomy: true,
// Content adaptation now available via sdk.tools.adaptContent()
}
});
return NextResponse.json(session);
} catch (error) {
return NextResponse.json(
{ error: 'Error starting session' },
{ status: 500 }
);
}
}API Reference
Available Modules
Activities
findAll()- List activities with paginationfindOne()- Get activity by IDcreate()- Create new activityupdate()- Update activityremove()- Delete activitygetExercises()- Get exercisesaddExercise()- Add exerciseupdateExercise()- Update exerciseremoveExercise()- Remove exercise
Sessions
startSession()- Start/resume session with activitysendMessage()- Send message to AI tutorgetMessages()- Get message historygetSession()- Get session detailsgetSessionProgress()- View progressresetSession()- Reset session
FreeSessions
startFreeSession()- Start free session with configurationsendFreeSessionMessage()- Send message to AI tutorgetFreeSessionMessages()- Get historygetFreeSession()- Get details
Configuration Types
// Free session configuration
interface SessionConfig {
enableSocraticMethod?: boolean;
enableBloomTaxonomy?: boolean;
topic?: string;
learningObjective?: string;
// Note: For content adaptation use sdk.tools.adaptContent() with DUA features
}Error Handling
Error Catching
import { SDK } from '@santillana-ai/typescript-tutor-sdk';
import * as errors from '@santillana-ai/typescript-tutor-sdk/models/errors';
const sdk = new SDK({ apiKey: 'your-api-key' });
try {
const activities = await sdk.activities.findAll();
} catch (error) {
if (error instanceof errors.SDKError) {
switch (error.httpMeta.response.status) {
case 401:
console.error('Invalid API Key');
break;
case 403:
console.error('No permissions');
break;
case 404:
console.error('Resource not found');
break;
case 429:
console.error('Request limit exceeded');
break;
case 500:
console.error('Server error');
break;
}
}
}Retry Configuration
const sdk = new SDK({
apiKey: 'your-api-key',
retryConfig: {
strategy: 'backoff',
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: true,
},
});Support
Resources
Recommended Use Cases
Use Activity Sessions when:
- ✅ You need formal structure and evaluation
- ✅ Following a defined curriculum
- ✅ Requiring specific progress measurement
- ✅ Students need clear guidance
Use Free Sessions when:
- ✅ Solving quick questions
- ✅ Exploring topics of interest
- ✅ Review without rigid structure
- ✅ Self-directed learning
Use Accessibility Profiles when:
- ✅ Students with special educational needs
- ✅ Personalizing the learning experience
- ✅ Adapting to different cognitive styles
- ✅ Complete educational inclusion
License
MIT © Santillana
Changelog
v0.3.0 (Current)
- ✨ Accessibility options with 9 predefined profiles
- ✨ Custom accessibility configuration
- 📝 Complete documentation in English
- 🔧 SDK structure improvements
v0.2.3
- ✨ Free sessions without activities
- ✨ Socratic method and Bloom's taxonomy configuration
- 🎯 Customizable topics and objectives
v0.2.0
- 🚀 Initial SDK release
- 📚 Activity and exercise management
- 💬 AI tutor chat system
Summary
Santillana AI Tutor API: Unified API Gateway for Santillana AI Tutor - Combines all microservices
Table of Contents
- Santillana AI Tutor SDK
- 📚 Table of Contents
- Introduction
- Installation
- Configuration
- Quick Start
- Core Features
- Implementation Examples
- API Reference
- Error Handling
- Support
- License
- Changelog
- SDK Installation
- Requirements
- SDK Example Usage
- Authentication
- Available Resources and Operations
- Standalone functions
- Retries
- Error Handling
- Server Selection
- Custom HTTP Client
- Debugging
SDK Installation
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
NPM
npm add @santillana-ai/typescript-tutor-sdkPNPM
pnpm add @santillana-ai/typescript-tutor-sdkBun
bun add @santillana-ai/typescript-tutor-sdkYarn
yarn add @santillana-ai/typescript-tutor-sdk[!NOTE] This package is published with CommonJS and ES Modules (ESM) support.
Requirements
For supported JavaScript runtimes, please consult RUNTIMES.md.
SDK Example Usage
Example
import { SDK } from "@santillana-ai/typescript-tutor-sdk";
const sdk = new SDK({
apiKey: "<YOUR_API_KEY_HERE>",
});
async function run() {
const result = await sdk.activities.listActivities();
console.log(result);
}
run();
Authentication
Per-Client Security Schemes
This SDK supports the following security scheme globally:
| Name | Type | Scheme |
| -------- | ------ | ------- |
| apiKey | apiKey | API key |
To authenticate with the API the apiKey parameter must be set when initializing the SDK client instance. For example:
import { SDK } from "@santillana-ai/typescript-tutor-sdk";
const sdk = new SDK({
apiKey: "<YOUR_API_KEY_HERE>",
});
async function run() {
const result = await sdk.activities.listActivities();
console.log(result);
}
run();
Available Resources and Operations
activities
- listActivities - List activities with pagination and filtering
- createActivity - Create a new activity
- getActivity - Get activity by ID with relations
- updateActivity - Update activity by ID
- deleteActivity - Delete activity by ID
- getActivityExercises - Get all exercises for an activity
- addExercise - Add a new exercise to an activity
- getExercisesByStep - Get exercises for a specific step
- updateExercise - Update an existing exercise
- removeExercise - Remove an exercise from an activity
metrics
- getMetricsSummary - Get metrics summary for the current API key
- getMetricsTimeseries - Get time series metrics for the current API key
- getMetricsByEndpoint - Get endpoint metrics for the current API key
- getUserMetricsSummary - Get comprehensive user metrics summary
- getUserSubjectProgress - Get user progress by subject
- getUserWeeklyProgress - Get user weekly progress (last 7 days)
- getUserSessionMetrics - Get user session metrics
- getUserStreakMetrics - Get user streak metrics
- getUserActivityHeatmap - Get user activity heatmap data
- getUserBloomProgress - Get user Bloom taxonomy progress
sessions
- createSession - Create a new learning session
- listSessions - List all sessions for the authenticated user
- listUserSessions - List all sessions for a specific user
- getSession - Get session details
- getSessionMessages - Get all messages in a session
- sendMessage - Send a message to the session and get AI response
- getSessionProgress - Get session progress
- resetSession - Reset a session
tools
- adaptContent - Adapt content using Universal Design for Learning (DUA) principles
- previewAdaptationPrompt - Preview the prompts that will be used for content adaptation
- getDefaultDUAFeatures - Get all available DUA features with their default descriptions
- previewSessionPrompt - Preview the system prompt generated for a tutoring session
users
- createUser - Create a new user
- findUserByEmail - Find user by email
- findUser - Get user details
- getUserSessions - Get user with their sessions
Standalone functions
All the methods listed above are available as standalone functions. These functions are ideal for use in applications running in the browser, serverless runtimes or other environments where application bundle size is a primary concern. When using a bundler to build your application, all unused functionality will be either excluded from the final bundle or tree-shaken away.
To read more about standalone functions, check FUNCTIONS.md.
activitiesAddExercise- Add a new exercise to an activityactivitiesCreateActivity- Create a new activityactivitiesDeleteActivity- Delete activity by IDactivitiesGetActivity- Get activity by ID with relationsactivitiesGetActivityExercises- Get all exercises for an activityactivitiesGetExercisesByStep- Get exercises for a specific stepactivitiesListActivities- List activities with pagination and filteringactivitiesRemoveExercise- Remove an exercise from an activityactivitiesUpdateActivity- Update activity by IDactivitiesUpdateExercise- Update an existing exercisemetricsGetMetricsByEndpoint- Get endpoint metrics for the current API keymetricsGetMetricsSummary- Get metrics summary for the current API keymetricsGetMetricsTimeseries- Get time series metrics for the current API keymetricsGetUserActivityHeatmap- Get user activity heatmap datametricsGetUserBloomProgress- Get user Bloom taxonomy progressmetricsGetUserMetricsSummary- Get comprehensive user metrics summarymetricsGetUserSessionMetrics- Get user session metricsmetricsGetUserStreakMetrics- Get user streak metricsmetricsGetUserSubjectProgress- Get user progress by subjectmetricsGetUserWeeklyProgress- Get user weekly progress (last 7 days)sessionsCreateSession- Create a new learning sessionsessionsGetSession- Get session detailssessionsGetSessionMessages- Get all messages in a sessionsessionsGetSessionProgress- Get session progresssessionsListSessions- List all sessions for the authenticated usersessionsListUserSessions- List all sessions for a specific usersessionsResetSession- Reset a sessionsessionsSendMessage- Send a message to the session and get AI responsetoolsAdaptContent- Adapt content using Universal Design for Learning (DUA) principlestoolsGetDefaultDUAFeatures- Get all available DUA features with their default descriptionstoolsPreviewAdaptationPrompt- Preview the prompts that will be used for content adaptationtoolsPreviewSessionPrompt- Preview the system prompt generated for a tutoring sessionusersCreateUser- Create a new userusersFindUser- Get user detailsusersFindUserByEmail- Find user by emailusersGetUserSessions- Get user with their sessions
Retries
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
import { SDK } from "@santillana-ai/typescript-tutor-sdk";
const sdk = new SDK({
apiKey: "<YOUR_API_KEY_HERE>",
});
async function run() {
const result = await sdk.activities.listActivities({
retries: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
console.log(result);
}
run();
If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
import { SDK } from "@santillana-ai/typescript-tutor-sdk";
const sdk = new SDK({
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
apiKey: "<YOUR_API_KEY_HERE>",
});
async function run() {
const result = await sdk.activities.listActivities();
console.log(result);
}
run();
Error Handling
SDKError is the base class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
| ------------------- | ---------- | ------------------------------------------------------ |
| error.message | string | Error message |
| error.statusCode | number | HTTP response status code eg 404 |
| error.headers | Headers | HTTP response headers |
| error.body | string | HTTP body. Can be empty string if no body is returned. |
| error.rawResponse | Response | Raw HTTP response |
Example
import { SDK } from "@santillana-ai/typescript-tutor-sdk";
import * as errors from "@santillana-ai/typescript-tutor-sdk/models/errors";
const sdk = new SDK({
apiKey: "<YOUR_API_KEY_HERE>",
});
async function run() {
try {
const result = await sdk.activities.listActivities();
console.log(result);
} catch (error) {
if (error instanceof errors.SDKError) {
console.log(error.message);
console.log(error.statusCode);
console.log(error.body);
console.log(error.headers);
}
}
}
run();
Error Classes
Primary error:
SDKError: The base class for HTTP error responses.
Network errors:
ConnectionError: HTTP client was unable to make a request to a server.RequestTimeoutError: HTTP request timed out due to an AbortSignal signal.RequestAbortedError: HTTP request was aborted by the client.InvalidRequestError: Any input used to create a request is invalid.UnexpectedClientError: Unrecognised or unexpected error.
Inherit from SDKError:
ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. Seeerror.rawValuefor the raw value anderror.pretty()for a nicely formatted multi-line string.
Server Selection
Select Server by Index
You can override the default server globally by passing a server index to the serverIdx: number optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the indexes associated with the available servers:
| # | Server | Variables | Description |
| --- | ----------------------------------------------------------------------------- | ------------- | ------------------------ |
| 0 | https://dx14o9a9s8.execute-api.us-east-1.amazonaws.com/{environment}/api/v1 | environment | AWS Lambda API Gateway |
| 1 | http://localhost:3000/api/v1 | | Local Development Server |
If the selected server has variables, you may override its default values through the additional parameters made available in the SDK constructor:
| Variable | Parameter | Supported Values | Default | Description |
| ------------- | --------------------------------------- | ---------------------------------- | ----------- | ---------------------------------------------- |
| environment | environment: models.ServerEnvironment | - "staging"- "production" | "staging" | Deployment environment (staging or production) |
Example
import { SDK } from "@santillana-ai/typescript-tutor-sdk";
const sdk = new SDK({
environment: "production",
apiKey: "<YOUR_API_KEY_HERE>",
});
async function run() {
const result = await sdk.activities.listActivities();
console.log(result);
}
run();
Override Server URL Per-Client
The default server can also be overridden globally by passing a URL to the serverURL: string optional parameter when initializing the SDK client instance. For example:
import { SDK } from "@santillana-ai/typescript-tutor-sdk";
const sdk = new SDK({
serverURL: "http://localhost:3000/api/v1",
apiKey: "<YOUR_API_KEY_HERE>",
});
async function run() {
const result = await sdk.activities.listActivities();
console.log(result);
}
run();
Custom HTTP Client
The TypeScript SDK makes API calls using an HTTPClient that wraps the native
Fetch API. This
client is a thin wrapper around fetch and provides the ability to attach hooks
around the request lifecycle that can be used to modify the request or handle
errors and response.
The HTTPClient constructor takes an optional fetcher argument that can be
used to integrate a third-party HTTP client or when writing tests to mock out
the HTTP client and feed in fixtures.
The following example shows how to use the "beforeRequest" hook to to add a
custom header and a timeout to requests and how to use the "requestError" hook
to log errors:
import { SDK } from "@santillana-ai/typescript-tutor-sdk";
import { HTTPClient } from "@santillana-ai/typescript-tutor-sdk/lib/http";
const httpClient = new HTTPClient({
// fetcher takes a function that has the same signature as native `fetch`.
fetcher: (request) => {
return fetch(request);
}
});
httpClient.addHook("beforeRequest", (request) => {
const nextRequest = new Request(request, {
signal: request.signal || AbortSignal.timeout(5000)
});
nextRequest.headers.set("x-custom-header", "custom value");
return nextRequest;
});
httpClient.addHook("requestError", (error, request) => {
console.group("Request Error");
console.log("Reason:", `${error}`);
console.log("Endpoint:", `${request.method} ${request.url}`);
console.groupEnd();
});
const sdk = new SDK({ httpClient: httpClient });Debugging
You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass a logger that matches console's interface as an SDK option.
[!WARNING] Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.
import { SDK } from "@santillana-ai/typescript-tutor-sdk";
const sdk = new SDK({ debugLogger: console });