npm package: @santillana-ai/typescript-tutor-sdk
Description: TypeScript SDK for integrating Santillana's AI-powered tutoring system into educational applications.
Author: santillana-sumun
Latest version: 5.9.0

# Santillana AI Tutor SDK

TypeScript SDK for integrating Santillana's AI-powered tutoring system into educational applications.

<div align="left">
    <a href="https://opensource.org/licenses/MIT">
        <img src="https://img.shields.io/badge/License-MIT-blue.svg" style="width: 100px; height: 28px;" />
    </a>
    <a href="https://www.npmjs.com/package/@santillana-ai/typescript-tutor-sdk">
        <img src="https://img.shields.io/npm/v/@santillana-ai/typescript-tutor-sdk.svg" />
    </a>
</div>

## 📚 Table of Contents

- [Introduction](#introduction)
- [Installation](#installation)
- [Configuration](#configuration)
- [Quick Start](#quick-start)
- [Core Features](#core-features)
  - [Activity Management](#activity-management)
  - [Activity Sessions](#activity-sessions)
  - [Free Sessions](#free-sessions)
  - [Content Adaptation Tool](#content-adaptation-tool)
- [Implementation Examples](#implementation-examples)
- [API Reference](#api-reference)
- [Error Handling](#error-handling)
- [Support](#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:

```bash
npx @santillana-ai/create-tutor-app@latest my-tutor-app
cd my-tutor-app
npm run dev
```

### 📦 Manual Installation

#### NPM
```bash
npm install @santillana-ai/typescript-tutor-sdk
```

#### PNPM
```bash
pnpm add @santillana-ai/typescript-tutor-sdk
```

#### Bun
```bash
bun add @santillana-ai/typescript-tutor-sdk
```

#### Yarn
```bash
yarn add @santillana-ai/typescript-tutor-sdk zod
```

> **Note**: Yarn requires manually installing `zod` as 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:

```env
SANTILLANA_API_KEY=sk_live_your_api_key_here
SANTILLANA_API_URL=https://ai-tutor-sdk-api.vercel.app
```

### 3. Initialize SDK

```typescript
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

```typescript
// 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.

```typescript
// 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.

```typescript
// 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.

```typescript
// 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 structure
- `r2_visualSupports`: Add visual aids and diagrams suggestions
- `r3_audioSupports`: Include detailed audio descriptions
- `r4_languageScaffolds`: Add definitions and language support

**Engagement** (Multiple ways to motivate):
- `e5_chunkingTime`: Break content into manageable segments
- `e6_interestsChoice`: Provide choices based on interests
- `e7_collaboration`: Include collaborative elements

**Action & Expression** (Multiple ways to demonstrate learning):
- `a8_guidedSteps`: Provide step-by-step instructions
- `a9_alternativeOutputs`: Allow different response formats
- `a10_fineMotorSupports`: Adapt for motor difficulties
- `a11_processingSpeed`: Adjust for different processing speeds

#### Basic Usage

```typescript
// 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

```typescript
// 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
```typescript
const adapted = await sdk.tools.adaptContent({
  content: "Complex mathematical concepts...",
  duaFeatures: {
    representation: {
      r2_visualSupports: true,
      r4_languageScaffolds: true
    }
  }
});
```

##### For Students with Attention Challenges
```typescript
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
```typescript
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

```typescript
'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

```typescript
// 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 pagination
- `findOne()` - Get activity by ID
- `create()` - Create new activity
- `update()` - Update activity
- `remove()` - Delete activity
- `getExercises()` - Get exercises
- `addExercise()` - Add exercise
- `updateExercise()` - Update exercise
- `removeExercise()` - Remove exercise

#### Sessions
- `startSession()` - Start/resume session with activity
- `sendMessage()` - Send message to AI tutor
- `getMessages()` - Get message history
- `getSession()` - Get session details
- `getSessionProgress()` - View progress
- `resetSession()` - Reset session

#### FreeSessions
- `startFreeSession()` - Start free session with configuration
- `sendFreeSessionMessage()` - Send message to AI tutor
- `getFreeSessionMessages()` - Get history
- `getFreeSession()` - Get details

### Configuration Types

```typescript
// 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

```typescript
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

```typescript
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
- 📚 [Full Documentation](https://docs.santillana.com/ai-tutor)
- 💬 [Discord Community](https://discord.gg/santillana-ai)
- 🐛 [Report Issues](https://github.com/santillana/ai-tutor-sdk/issues)
- 📧 [Technical Support](mailto:support@santillana.com)

### 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
<!-- Start Summary [summary] -->
## Summary

Santillana AI Tutor API: Unified API Gateway for Santillana AI Tutor - Combines all microservices
<!-- End Summary [summary] -->

<!-- Start Table of Contents [toc] -->
## Table of Contents
<!-- $toc-max-depth=2 -->
* [Santillana AI Tutor SDK](#santillana-ai-tutor-sdk)
  * [📚 Table of Contents](#table-of-contents)
  * [Introduction](#introduction)
  * [Installation](#installation)
  * [Configuration](#configuration)
  * [Quick Start](#quick-start)
  * [Core Features](#core-features)
  * [Implementation Examples](#implementation-examples)
  * [API Reference](#api-reference)
  * [Error Handling](#error-handling)
  * [Support](#support)
  * [License](#license)
  * [Changelog](#changelog)
  * [SDK Installation](#sdk-installation)
  * [Requirements](#requirements)
  * [SDK Example Usage](#sdk-example-usage)
  * [Authentication](#authentication)
  * [Available Resources and Operations](#available-resources-and-operations)
  * [Standalone functions](#standalone-functions)
  * [Retries](#retries)
  * [Error Handling](#error-handling-1)
  * [Server Selection](#server-selection)
  * [Custom HTTP Client](#custom-http-client)
  * [Debugging](#debugging)

<!-- End Table of Contents [toc] -->

<!-- Start SDK Installation [installation] -->
## SDK Installation

The SDK can be installed with either [npm](https://www.npmjs.com/), [pnpm](https://pnpm.io/), [bun](https://bun.sh/) or [yarn](https://classic.yarnpkg.com/en/) package managers.

### NPM

```bash
npm add @santillana-ai/typescript-tutor-sdk
```

### PNPM

```bash
pnpm add @santillana-ai/typescript-tutor-sdk
```

### Bun

```bash
bun add @santillana-ai/typescript-tutor-sdk
```

### Yarn

```bash
yarn add @santillana-ai/typescript-tutor-sdk
```

> [!NOTE]
> This package is published with CommonJS and ES Modules (ESM) support.
<!-- End SDK Installation [installation] -->

<!-- Start Requirements [requirements] -->
## Requirements

For supported JavaScript runtimes, please consult [RUNTIMES.md](RUNTIMES.md).
<!-- End Requirements [requirements] -->

<!-- Start SDK Example Usage [usage] -->
## SDK Example Usage

### Example

```typescript
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();

```
<!-- End SDK Example Usage [usage] -->

<!-- Start Authentication [security] -->
## 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:
```typescript
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();

```
<!-- End Authentication [security] -->

<!-- Start Available Resources and Operations [operations] -->
## Available Resources and Operations

<details open>
<summary>Available methods</summary>

### [activities](docs/sdks/activities/README.md)

* [listActivities](docs/sdks/activities/README.md#listactivities) - List activities with pagination and filtering
* [createActivity](docs/sdks/activities/README.md#createactivity) - Create a new activity
* [getActivity](docs/sdks/activities/README.md#getactivity) - Get activity by ID with relations
* [updateActivity](docs/sdks/activities/README.md#updateactivity) - Update activity by ID
* [deleteActivity](docs/sdks/activities/README.md#deleteactivity) - Delete activity by ID
* [getActivityExercises](docs/sdks/activities/README.md#getactivityexercises) - Get all exercises for an activity
* [addExercise](docs/sdks/activities/README.md#addexercise) - Add a new exercise to an activity
* [getExercisesByStep](docs/sdks/activities/README.md#getexercisesbystep) - Get exercises for a specific step
* [updateExercise](docs/sdks/activities/README.md#updateexercise) - Update an existing exercise
* [removeExercise](docs/sdks/activities/README.md#removeexercise) - Remove an exercise from an activity

### [metrics](docs/sdks/metrics/README.md)

* [getMetricsSummary](docs/sdks/metrics/README.md#getmetricssummary) - Get metrics summary for the current API key
* [getMetricsTimeseries](docs/sdks/metrics/README.md#getmetricstimeseries) - Get time series metrics for the current API key
* [getMetricsByEndpoint](docs/sdks/metrics/README.md#getmetricsbyendpoint) - Get endpoint metrics for the current API key
* [getUserMetricsSummary](docs/sdks/metrics/README.md#getusermetricssummary) - Get comprehensive user metrics summary
* [getUserSubjectProgress](docs/sdks/metrics/README.md#getusersubjectprogress) - Get user progress by subject
* [getUserWeeklyProgress](docs/sdks/metrics/README.md#getuserweeklyprogress) - Get user weekly progress (last 7 days)
* [getUserSessionMetrics](docs/sdks/metrics/README.md#getusersessionmetrics) - Get user session metrics
* [getUserStreakMetrics](docs/sdks/metrics/README.md#getuserstreakmetrics) - Get user streak metrics
* [getUserActivityHeatmap](docs/sdks/metrics/README.md#getuseractivityheatmap) - Get user activity heatmap data
* [getUserBloomProgress](docs/sdks/metrics/README.md#getuserbloomprogress) - Get user Bloom taxonomy progress

### [sessions](docs/sdks/sessions/README.md)

* [createSession](docs/sdks/sessions/README.md#createsession) - Create a new learning session
* [listSessions](docs/sdks/sessions/README.md#listsessions) - List all sessions for the authenticated user
* [listUserSessions](docs/sdks/sessions/README.md#listusersessions) - List all sessions for a specific user
* [getSession](docs/sdks/sessions/README.md#getsession) - Get session details
* [getSessionMessages](docs/sdks/sessions/README.md#getsessionmessages) - Get all messages in a session
* [sendMessage](docs/sdks/sessions/README.md#sendmessage) - Send a message to the session and get AI response
* [getSessionProgress](docs/sdks/sessions/README.md#getsessionprogress) - Get session progress
* [resetSession](docs/sdks/sessions/README.md#resetsession) - Reset a session

### [tools](docs/sdks/tools/README.md)

* [adaptContent](docs/sdks/tools/README.md#adaptcontent) - Adapt content using Universal Design for Learning (DUA) principles
* [previewAdaptationPrompt](docs/sdks/tools/README.md#previewadaptationprompt) - Preview the prompts that will be used for content adaptation
* [getDefaultDUAFeatures](docs/sdks/tools/README.md#getdefaultduafeatures) - Get all available DUA features with their default descriptions
* [previewSessionPrompt](docs/sdks/tools/README.md#previewsessionprompt) - Preview the system prompt generated for a tutoring session

### [users](docs/sdks/users/README.md)

* [createUser](docs/sdks/users/README.md#createuser) - Create a new user
* [findUserByEmail](docs/sdks/users/README.md#finduserbyemail) - Find user by email
* [findUser](docs/sdks/users/README.md#finduser) - Get user details
* [getUserSessions](docs/sdks/users/README.md#getusersessions) - Get user with their sessions

</details>
<!-- End Available Resources and Operations [operations] -->

<!-- Start Standalone functions [standalone-funcs] -->
## 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](./FUNCTIONS.md).

<details>

<summary>Available standalone functions</summary>

- [`activitiesAddExercise`](docs/sdks/activities/README.md#addexercise) - Add a new exercise to an activity
- [`activitiesCreateActivity`](docs/sdks/activities/README.md#createactivity) - Create a new activity
- [`activitiesDeleteActivity`](docs/sdks/activities/README.md#deleteactivity) - Delete activity by ID
- [`activitiesGetActivity`](docs/sdks/activities/README.md#getactivity) - Get activity by ID with relations
- [`activitiesGetActivityExercises`](docs/sdks/activities/README.md#getactivityexercises) - Get all exercises for an activity
- [`activitiesGetExercisesByStep`](docs/sdks/activities/README.md#getexercisesbystep) - Get exercises for a specific step
- [`activitiesListActivities`](docs/sdks/activities/README.md#listactivities) - List activities with pagination and filtering
- [`activitiesRemoveExercise`](docs/sdks/activities/README.md#removeexercise) - Remove an exercise from an activity
- [`activitiesUpdateActivity`](docs/sdks/activities/README.md#updateactivity) - Update activity by ID
- [`activitiesUpdateExercise`](docs/sdks/activities/README.md#updateexercise) - Update an existing exercise
- [`metricsGetMetricsByEndpoint`](docs/sdks/metrics/README.md#getmetricsbyendpoint) - Get endpoint metrics for the current API key
- [`metricsGetMetricsSummary`](docs/sdks/metrics/README.md#getmetricssummary) - Get metrics summary for the current API key
- [`metricsGetMetricsTimeseries`](docs/sdks/metrics/README.md#getmetricstimeseries) - Get time series metrics for the current API key
- [`metricsGetUserActivityHeatmap`](docs/sdks/metrics/README.md#getuseractivityheatmap) - Get user activity heatmap data
- [`metricsGetUserBloomProgress`](docs/sdks/metrics/README.md#getuserbloomprogress) - Get user Bloom taxonomy progress
- [`metricsGetUserMetricsSummary`](docs/sdks/metrics/README.md#getusermetricssummary) - Get comprehensive user metrics summary
- [`metricsGetUserSessionMetrics`](docs/sdks/metrics/README.md#getusersessionmetrics) - Get user session metrics
- [`metricsGetUserStreakMetrics`](docs/sdks/metrics/README.md#getuserstreakmetrics) - Get user streak metrics
- [`metricsGetUserSubjectProgress`](docs/sdks/metrics/README.md#getusersubjectprogress) - Get user progress by subject
- [`metricsGetUserWeeklyProgress`](docs/sdks/metrics/README.md#getuserweeklyprogress) - Get user weekly progress (last 7 days)
- [`sessionsCreateSession`](docs/sdks/sessions/README.md#createsession) - Create a new learning session
- [`sessionsGetSession`](docs/sdks/sessions/README.md#getsession) - Get session details
- [`sessionsGetSessionMessages`](docs/sdks/sessions/README.md#getsessionmessages) - Get all messages in a session
- [`sessionsGetSessionProgress`](docs/sdks/sessions/README.md#getsessionprogress) - Get session progress
- [`sessionsListSessions`](docs/sdks/sessions/README.md#listsessions) - List all sessions for the authenticated user
- [`sessionsListUserSessions`](docs/sdks/sessions/README.md#listusersessions) - List all sessions for a specific user
- [`sessionsResetSession`](docs/sdks/sessions/README.md#resetsession) - Reset a session
- [`sessionsSendMessage`](docs/sdks/sessions/README.md#sendmessage) - Send a message to the session and get AI response
- [`toolsAdaptContent`](docs/sdks/tools/README.md#adaptcontent) - Adapt content using Universal Design for Learning (DUA) principles
- [`toolsGetDefaultDUAFeatures`](docs/sdks/tools/README.md#getdefaultduafeatures) - Get all available DUA features with their default descriptions
- [`toolsPreviewAdaptationPrompt`](docs/sdks/tools/README.md#previewadaptationprompt) - Preview the prompts that will be used for content adaptation
- [`toolsPreviewSessionPrompt`](docs/sdks/tools/README.md#previewsessionprompt) - Preview the system prompt generated for a tutoring session
- [`usersCreateUser`](docs/sdks/users/README.md#createuser) - Create a new user
- [`usersFindUser`](docs/sdks/users/README.md#finduser) - Get user details
- [`usersFindUserByEmail`](docs/sdks/users/README.md#finduserbyemail) - Find user by email
- [`usersGetUserSessions`](docs/sdks/users/README.md#getusersessions) - Get user with their sessions

</details>
<!-- End Standalone functions [standalone-funcs] -->

<!-- Start Retries [retries] -->
## 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:
```typescript
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:
```typescript
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();

```
<!-- End Retries [retries] -->

<!-- Start Error Handling [errors] -->
## Error Handling

[`SDKError`](./src/models/errors/sdkerror.ts) 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
```typescript
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`](./src/models/errors/sdkerror.ts): The base class for HTTP error responses.

<details><summary>Less common errors (6)</summary>

<br />

**Network errors:**
* [`ConnectionError`](./src/models/errors/httpclienterrors.ts): HTTP client was unable to make a request to a server.
* [`RequestTimeoutError`](./src/models/errors/httpclienterrors.ts): HTTP request timed out due to an AbortSignal signal.
* [`RequestAbortedError`](./src/models/errors/httpclienterrors.ts): HTTP request was aborted by the client.
* [`InvalidRequestError`](./src/models/errors/httpclienterrors.ts): Any input used to create a request is invalid.
* [`UnexpectedClientError`](./src/models/errors/httpclienterrors.ts): Unrecognised or unexpected error.


**Inherit from [`SDKError`](./src/models/errors/sdkerror.ts)**:
* [`ResponseValidationError`](./src/models/errors/responsevalidationerror.ts): Type mismatch between the data returned from the server and the structure expected by the SDK. See `error.rawValue` for the raw value and `error.pretty()` for a nicely formatted multi-line string.

</details>
<!-- End Error Handling [errors] -->

<!-- Start Server Selection [server] -->
## 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"`<br/>- `"production"` | `"staging"` | Deployment environment (staging or production) |

#### Example

```typescript
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:
```typescript
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();

```
<!-- End Server Selection [server] -->

<!-- Start Custom HTTP Client [http-client] -->
## Custom HTTP Client

The TypeScript SDK makes API calls using an `HTTPClient` that wraps the native
[Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/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:

```typescript
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 });
```
<!-- End Custom HTTP Client [http-client] -->

<!-- Start Debugging [debug] -->
## 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.

```typescript
import { SDK } from "@santillana-ai/typescript-tutor-sdk";

const sdk = new SDK({ debugLogger: console });
```
<!-- End Debugging [debug] -->

<!-- Placeholder for Future Speakeasy SDK Sections -->