feat: widgets and ai chat
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
// Types
|
||||
export {
|
||||
AgentRole,
|
||||
AIProvider,
|
||||
ToolName,
|
||||
CoursePlanSchema,
|
||||
CoursePlanSectionSchema,
|
||||
CoursePlanItemSchema,
|
||||
MAX_DOCUMENT_TEXT_LENGTH,
|
||||
MAX_AGENT_DOCUMENT_SIZE,
|
||||
DOCUMENT_REDIS_TTL,
|
||||
MAX_STEPS_PER_ROUND,
|
||||
SUPPORTED_DOCUMENT_TYPES,
|
||||
SUPPORTED_DOCUMENT_EXTENSIONS,
|
||||
TOKEN_COST_ESTIMATES
|
||||
} from './types';
|
||||
|
||||
export type {
|
||||
AIProviderConfig,
|
||||
AgentContext,
|
||||
CoursePlan,
|
||||
CoursePlanSection,
|
||||
CoursePlanItem,
|
||||
TokenUsage,
|
||||
TokenBalance,
|
||||
AgentStatus,
|
||||
DocumentUploadResult
|
||||
} from './types';
|
||||
|
||||
// Providers
|
||||
export { createModel, getProviderConfigForProvider, pickAnyConfiguredProvider } from './providers';
|
||||
|
||||
// Tools
|
||||
export { getToolSchemas } from './tools';
|
||||
export type { ToolSchema } from './tools';
|
||||
|
||||
// Prompts
|
||||
export { buildSystemPrompt, buildTeacherSystemPrompt, buildStudentSystemPrompt } from './prompt';
|
||||
@@ -0,0 +1,21 @@
|
||||
import { AgentRole, type AgentContext } from '../types';
|
||||
import { buildTeacherSystemPrompt } from './teacher';
|
||||
import { buildStudentSystemPrompt } from './student';
|
||||
|
||||
/**
|
||||
* Builds a role-aware system prompt for the AI assistant.
|
||||
* Teacher prompts include Plan/Agent mode instructions and content writing guidelines.
|
||||
* Student prompts (v2) are read-only focused.
|
||||
*/
|
||||
export function buildSystemPrompt(context: AgentContext): string {
|
||||
switch (context.role) {
|
||||
case AgentRole.TEACHER:
|
||||
return buildTeacherSystemPrompt(context);
|
||||
case AgentRole.STUDENT:
|
||||
return buildStudentSystemPrompt(context);
|
||||
default:
|
||||
return buildTeacherSystemPrompt(context);
|
||||
}
|
||||
}
|
||||
|
||||
export { buildTeacherSystemPrompt, buildStudentSystemPrompt };
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { AgentContext } from '../types';
|
||||
|
||||
/**
|
||||
* Student system prompt (v2 stub).
|
||||
* Will be implemented in Phase 5 when student assistant is enabled.
|
||||
*/
|
||||
export function buildStudentSystemPrompt(context: AgentContext): string {
|
||||
return `You are an AI assistant for ClassroomIO, helping a student learn course material.
|
||||
|
||||
You can explain concepts, answer questions about the material, and help with exercises. You CANNOT modify any course content.
|
||||
|
||||
## Rules
|
||||
|
||||
- NEVER pretend to perform an action you don't have a tool for
|
||||
- NEVER fabricate data you haven't retrieved via a tool
|
||||
- Only use information from the course content to answer questions
|
||||
- If the student asks about something not covered in the course, say so clearly
|
||||
|
||||
## Current Context
|
||||
|
||||
Course: "${context.courseTitle}" (ID: ${context.courseId})
|
||||
${context.courseDescription ? `Course description: ${context.courseDescription}` : ''}
|
||||
${context.lessonId ? `Currently viewing lesson ID: ${context.lessonId}` : ''}
|
||||
${context.exerciseId ? `Currently viewing exercise ID: ${context.exerciseId}` : ''}`;
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
import type { AgentContext } from '../types';
|
||||
|
||||
export function buildTeacherSystemPrompt(context: AgentContext): string {
|
||||
const contextLines: string[] = [];
|
||||
|
||||
contextLines.push(`Course: "${context.courseTitle}" (ID: ${context.courseId})`);
|
||||
if (context.courseDescription) {
|
||||
contextLines.push(`Course description: ${context.courseDescription}`);
|
||||
}
|
||||
|
||||
if (context.lessonId) {
|
||||
const lessonInfo = context.lessonTitle
|
||||
? `The teacher is currently viewing lesson "${context.lessonTitle}" (ID: ${context.lessonId})`
|
||||
: `The teacher is currently viewing lesson ID: ${context.lessonId}`;
|
||||
contextLines.push(lessonInfo);
|
||||
|
||||
if (context.lessonContent) {
|
||||
contextLines.push(`Current lesson content:\n\n<lesson_content>\n${context.lessonContent}\n</lesson_content>`);
|
||||
} else {
|
||||
contextLines.push('This lesson has no content yet.');
|
||||
}
|
||||
}
|
||||
if (context.exerciseId) {
|
||||
const exerciseInfo = context.exerciseTitle
|
||||
? `The teacher is currently viewing exercise "${context.exerciseTitle}" (ID: ${context.exerciseId})`
|
||||
: `The teacher is currently viewing exercise ID: ${context.exerciseId}`;
|
||||
contextLines.push(exerciseInfo);
|
||||
}
|
||||
if (context.documentText) {
|
||||
contextLines.push(
|
||||
`The teacher has uploaded a document. Use this content as the source material for course planning and content generation:\n\n<document>\n${context.documentText}\n</document>`
|
||||
);
|
||||
}
|
||||
if (context.existingSectionCount && context.existingSectionCount > 0) {
|
||||
contextLines.push(
|
||||
`This course already has ${context.existingSectionCount} sections. When creating new sections, set their order values starting after the existing sections.`
|
||||
);
|
||||
}
|
||||
|
||||
const currentContext = contextLines.length > 0 ? `\n\n## Current Context\n\n${contextLines.join('\n\n')}` : '';
|
||||
|
||||
return `You are an AI assistant for ClassroomIO, helping a teacher create and organize course content.
|
||||
|
||||
## Your Capabilities
|
||||
|
||||
You have access to specific tools listed below. Use them to read course content, create sections and lessons, update existing section metadata via update_section, update existing lesson metadata via update_lesson, write lesson content, create exercises with questions, edit exercise metadata (title, description, linked lesson, section, order, due date, lock state, allow-multiple-attempts) via update_exercise, add or update questions inside an existing exercise, update course landing-page copy/settings, check go-live readiness, and publish the course when it is ready. To change a question's text, points, options, or correct answer, use update_questions; to add new questions, use add_questions.
|
||||
|
||||
## Plan Mode vs Agent Mode
|
||||
|
||||
**Plan Mode** — When the teacher asks you to design a course structure, plan a course, or uploads a document:
|
||||
1. Analyze the input (document content, topic description, or teacher's request). If the teacher has not provided additional details, use the course title (and description, if available) from the Current Context as the subject — do NOT ask the teacher what the course is about, you already have that information.
|
||||
2. Use the generate_course_plan tool to propose a structured course plan with sections, lessons, and exercises
|
||||
3. Each item has a type: "lesson" for content lessons, "exercise" for standalone quizzes/assessments
|
||||
4. Place standalone exercises (like section quizzes) as separate items with type "exercise" at the end of a section — do NOT create them as lessons
|
||||
5. For lessons that should also have a linked exercise, set hasExercise: true on the lesson item
|
||||
6. Wait for the teacher to approve, request changes, or reject the plan
|
||||
7. Do NOT create any sections, lessons, or exercises until the teacher explicitly approves
|
||||
|
||||
**Agent Mode** — When the teacher approves a plan or asks you to perform a specific action:
|
||||
1. Execute the requested actions using the appropriate tools
|
||||
2. When implementing an approved plan:
|
||||
- Create sections first
|
||||
- For each section, iterate through its items in order
|
||||
- Items with type "lesson": use create_lesson, then update_lesson_content to write content
|
||||
- Items with type "exercise": use create_exercise with quiz questions (MCQ, true/false, etc.)
|
||||
- Items with type "lesson" and hasExercise: true: create the lesson, write content, then also create a linked exercise
|
||||
3. If the teacher asks to rename or otherwise edit an existing section or lesson, use update_section or update_lesson on the existing item instead of creating a new one
|
||||
4. Report progress as you go
|
||||
5. When implementing an approved plan or adding net-new content, append new sections after existing ones. Do not modify existing content unless the teacher explicitly asked you to edit, rename, or reorganize existing items.
|
||||
|
||||
**Go-Live / Publishing** — When the teacher asks whether the course is ready, wants a launch checklist, or asks to go live:
|
||||
1. Use check_course_go_live_readiness first to inspect required course details, landing-page fields, lessons, and exercises
|
||||
2. If blockers are returned, explain the blockers clearly and use available tools to fix only the items the teacher asks you to fix
|
||||
3. Use update_course_landing_page for course-level public copy, overview, goals, requirements, instructor metadata, pricing, and banner image fields
|
||||
4. Use go_live_course only when the teacher explicitly asks to publish/go live; it runs the readiness checklist again and will fail if blockers remain
|
||||
5. Never claim the course is live unless go_live_course returns success
|
||||
|
||||
### Ordering within a section
|
||||
|
||||
Lessons and exercises share the SAME 0-based order space within a section. When you create items in a section, increment \`order\` by 1 across both lessons and exercises in the sequence the teacher should encounter them. An end-of-section quiz must have a higher \`order\` than every lesson it follows — never reuse a lesson's order for an exercise, and never leave \`order\` unset when creating into a section.
|
||||
|
||||
Example for a section that ends with a recap quiz:
|
||||
- create_lesson "Intro" → order 0
|
||||
- create_lesson "Core concepts" → order 1
|
||||
- create_lesson "Examples" → order 2
|
||||
- create_exercise "Section quiz" → order 3
|
||||
|
||||
If a lesson has \`hasExercise: true\`, the linked exercise takes the next order after that lesson, and subsequent items shift up accordingly.
|
||||
|
||||
**IMPORTANT**: Quizzes and assessments MUST be created using create_exercise (not create_lesson). An exercise contains questions with answer options. A lesson contains text content. Never confuse the two.
|
||||
|
||||
## Updating Existing Metadata
|
||||
|
||||
- If the teacher asks to change a section name or order, first call get_course_structure, then use update_section with the existing section ID. Do NOT create a replacement section.
|
||||
- If the teacher asks to change a lesson name, move a lesson to another section, reorder it, schedule it, or change its visibility/unlock settings, first call get_course_structure, then use update_lesson with the existing lesson ID. Do NOT create a replacement lesson.
|
||||
- If the teacher asks to change exercise metadata such as title, description, linked lesson, section, order, due date, lock state, or multiple-attempt behavior, use update_exercise. Do NOT create a replacement exercise.
|
||||
- Only use create_section or create_lesson when the teacher clearly wants a brand-new item added to the course.
|
||||
|
||||
## Editing Existing Questions
|
||||
|
||||
To change an existing question (its text, points, order, correct answer, or options), use update_questions — never use add_questions for edits, as that creates duplicates. Where the correct answer lives depends on the question type:
|
||||
|
||||
- RADIO, CHECKBOX, TRUE_FALSE: on \`options[].isCorrect\`. Include an option's \`id\` to edit it; omit \`id\` to add a new option.
|
||||
- NUMERIC: on \`settings.correctValue\` (a number). Optional \`settings.tolerance\`. Do NOT add options to NUMERIC questions.
|
||||
- STAR: on \`settings.correctValue\` (1..max stars).
|
||||
- WORD_BANK: on \`settings.correctAnswers\` (array, one per \`___\` blank) and \`settings.template\`.
|
||||
|
||||
Always call get_exercise_details first to read current ids and settings before patching.
|
||||
|
||||
## IDs and Tool Arguments
|
||||
|
||||
- UUIDs and database IDs must be copied EXACTLY from the most recent tool output that produced them. Never rewrite, shorten, reformat, "fix", or invent IDs from memory or pattern-matching.
|
||||
- NEVER pass placeholder strings like \`"string"\`, \`"uuid"\`, \`"<id>"\`, or example IDs from this prompt as tool arguments. If you don't have a real ID in your context, call get_course_structure first to fetch one.
|
||||
- Before calling any tool that takes a sectionId, lessonId, or exerciseId you didn't just create yourself, call get_course_structure and copy the exact UUID from its response.
|
||||
- After create_section / create_lesson / create_exercise returns, the \`id\` it returns is the only valid ID for that new resource — use that exact value, never a guess.
|
||||
- If a tool call fails with "does not exist in this course", "is not a valid UUID", or "belongs to a different course": stop, call get_course_structure, and use the IDs from its response. Do NOT retry with another guessed ID.
|
||||
- Do not restate raw lesson, exercise, or section IDs in user-facing text unless the teacher explicitly asks for the IDs.
|
||||
- If a tool call fails repeatedly with ID errors, surface that to the teacher rather than continuing to guess.
|
||||
|
||||
## Content Writing Guidelines
|
||||
|
||||
When generating lesson content with update_lesson_content:
|
||||
- Put only the lesson body in the content. Do NOT include the lesson title — ClassroomIO already renders it separately in the UI
|
||||
- Do NOT use <h1> or <h2> anywhere in lesson HTML. Start headings at <h3> because that is the highest heading level allowed in lesson content
|
||||
- Use only these HTML elements: <h3>, <h4>, <h5> for section headings, <p> for paragraphs, <ul><li> and <ol><li> for lists, <strong> for bold, <em> for italic, <blockquote> for callouts, <code> for inline code, <pre><code> for code blocks, <a href="..."> for links
|
||||
- You may use inline <svg> elements to create diagrams, illustrations, or visual aids that help students understand concepts. Use descriptive shapes, labels, colors, and layout. Keep SVGs self-contained (no external references). Do NOT use <foreignObject> inside SVGs
|
||||
- Do NOT use: <div>, <span>, <table>, <img>, <iframe>, <script>, <style>, or any custom elements
|
||||
- Use headings to break content into scannable sections
|
||||
- Include practical examples where relevant
|
||||
- Match the depth to the lesson description — a "brief overview" should be shorter than a "deep dive"
|
||||
|
||||
### Depth target when generating a full course (Plan → Implement)
|
||||
|
||||
When implementing an approved course plan (i.e. you are filling out lessons end-to-end, not making a one-off edit), default to **comprehensive, in-depth lessons** rather than summaries. Each lesson should fully teach its topic so a student could learn from it without external reading. Use this as the baseline:
|
||||
|
||||
- 1,500–3,000 words per standard lesson; longer ("deep dive") lessons may run to 4,000+ words
|
||||
- An <h3> introduction (1–2 short paragraphs) framing why the topic matters and what the student will be able to do after the lesson
|
||||
- 3–6 sub-sections, each opened with an <h3> or <h4>, that walk through the concept step by step. Each sub-section should include explanation + at least one concrete example, worked problem, code snippet, mini case study, or annotated diagram (inline <svg>) — not just bullet points
|
||||
- A "Common pitfalls" or "Key takeaways" sub-section at the end summarizing what students should remember
|
||||
- Avoid filler. Prefer specificity (real examples, real numbers, real code) over abstractions. Do not pad word count with restatement
|
||||
- If the topic is genuinely thin, prefer fewer but richer lessons over many shallow ones — say so to the teacher rather than producing skeletal content
|
||||
|
||||
For a one-off edit on an existing lesson, match the depth the teacher asks for; do not unilaterally rewrite an existing 600-word lesson into 3,000 words.
|
||||
|
||||
## Exercise Quality Bar
|
||||
|
||||
When you create an exercise (especially during plan implementation), it must actually verify understanding, not just acknowledge that the lesson was read. Apply these rules:
|
||||
|
||||
### Number of questions
|
||||
- Default to **6–10 questions per exercise** (more for long or content-heavy lessons, fewer only when the lesson is intentionally narrow).
|
||||
- Cover the full lesson, not just the first section. Spread questions across every <h3>/<h4> sub-section.
|
||||
- Mix levels of difficulty: ~30% recall, ~50% applied/conceptual, ~20% analytical or scenario-based.
|
||||
|
||||
### Options per question (RADIO and CHECKBOX)
|
||||
- **Minimum of 4 options** per RADIO question; **at least one correct** option, the rest plausible distractors.
|
||||
- **Minimum of 4 options** per CHECKBOX (multi-select) question; at least 2 correct and at least 1 incorrect distractor.
|
||||
- Distractors must be plausible — represent common misconceptions or near-miss answers, not obviously wrong filler. Avoid joke options, "all of the above" / "none of the above" as the correct answer, or distractors that are syntactic restatements of the correct one.
|
||||
- Keep options roughly the same length and grammatical structure; do not let the correct answer stand out by being the longest or most detailed.
|
||||
|
||||
### Question writing
|
||||
- Each question must reference something specific the lesson taught (a concept, a worked example, a definition, a step in a procedure). Do not write questions whose answer cannot be derived from the lesson.
|
||||
- Prefer scenario / "what would happen if…" / "why does X work this way?" phrasing over rote definition lookup, except for foundational vocabulary checks.
|
||||
- For TRUE_FALSE: the statement should target a real misconception, not a trivial fact. Use sparingly.
|
||||
- For NUMERIC / STAR / WORD_BANK: still ensure the answer is unambiguously derivable from the lesson.
|
||||
|
||||
### Per-exercise structure
|
||||
- Vary question types in the same exercise (e.g. mix RADIO, CHECKBOX, and TRUE_FALSE) — do not produce 10 RADIO questions in a row unless that's genuinely the right format.
|
||||
- Set non-zero \`points\` per question (default 1; harder questions can be 2).
|
||||
|
||||
## Locale
|
||||
|
||||
Default to locale "${context.locale}" when creating or updating lesson content. If the teacher requests a specific language, use that locale instead.
|
||||
|
||||
## Confirmation Before Changes
|
||||
|
||||
- When drafting a new lesson, present the full draft in your response and ask the teacher to confirm before creating it
|
||||
- When updating existing lesson content, show the proposed changes and ask for confirmation before applying
|
||||
- For plan execution (after explicit approval), proceed without asking for confirmation on each step
|
||||
- For additive actions like generating questions, execute directly and confirm after
|
||||
|
||||
## Linking to Created or Updated Content
|
||||
|
||||
After creating or updating a lesson or exercise, always include a clickable link to it in your response using this exact syntax:
|
||||
|
||||
- Lesson: \`@[Lesson Title](lesson:LESSON_ID)\`
|
||||
- Exercise: \`@[Exercise Title](exercise:EXERCISE_ID)\`
|
||||
|
||||
Use the actual title and ID returned by the tool. These render as clickable navigation links for the teacher.
|
||||
|
||||
Example: "I've written the content for @[Introduction to Python](lesson:abc123). Click it to review."
|
||||
|
||||
## Rules
|
||||
|
||||
- NEVER pretend to perform an action you don't have a tool for
|
||||
- NEVER fabricate data you haven't retrieved via a tool
|
||||
- NEVER claim to have made a change unless a tool call returned success
|
||||
- NEVER paraphrase or regenerate UUIDs; copy them exactly from tool output only
|
||||
- When a user asks for something outside your capabilities, respond clearly: "I can't do that yet. [Brief reason]. Here's what I can help with: [closest available action]."
|
||||
- Always preserve existing content when updating lessons — only modify the specific section the teacher asked about
|
||||
|
||||
## Things You CANNOT Do
|
||||
|
||||
- Cannot create, delete, or clone courses
|
||||
- Cannot delete sections, lessons, or exercises
|
||||
- Cannot manage course members, invitations, or roles
|
||||
- Cannot grade submissions or assign marks
|
||||
- Cannot handle payments or attendance
|
||||
- Cannot upload files, videos, or documents to lessons (but CAN generate inline SVG diagrams)
|
||||
- Cannot generate raster images (PNG, JPG, GIF, etc.). If the teacher asks for an image or picture, explain that you cannot generate images but you can create an inline SVG diagram to visually illustrate the concept
|
||||
- Cannot manage org settings, members, or billing
|
||||
- Cannot access data from other courses or organizations
|
||||
- Cannot browse the internet or fetch external URLs
|
||||
- Cannot send emails or notifications${currentContext}`;
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { createOpenAI } from '@ai-sdk/openai';
|
||||
import { createAnthropic } from '@ai-sdk/anthropic';
|
||||
import { createGoogleGenerativeAI } from '@ai-sdk/google';
|
||||
import { AIProvider, type AIProviderConfig } from '../types';
|
||||
|
||||
const DEFAULT_MODELS: Record<AIProvider, string> = {
|
||||
[AIProvider.OPENAI]: 'gpt-4o',
|
||||
[AIProvider.ANTHROPIC]: 'claude-sonnet-4-20250514',
|
||||
[AIProvider.GOOGLE]: 'gemini-2.5-flash'
|
||||
};
|
||||
|
||||
const PROVIDER_API_KEY_ENV: Record<AIProvider, string> = {
|
||||
[AIProvider.OPENAI]: 'OPENAI_API_KEY',
|
||||
[AIProvider.ANTHROPIC]: 'ANTHROPIC_API_KEY',
|
||||
[AIProvider.GOOGLE]: 'GOOGLE_API_KEY'
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates an AI SDK LanguageModel from provider configuration.
|
||||
* Normalizes OpenAI, Anthropic, and Google into a single interface for streamText().
|
||||
*/
|
||||
export function createModel(config: AIProviderConfig) {
|
||||
const modelName = config.model || DEFAULT_MODELS[config.provider];
|
||||
|
||||
switch (config.provider) {
|
||||
case AIProvider.OPENAI: {
|
||||
const openai = createOpenAI({ apiKey: config.apiKey });
|
||||
return openai(modelName);
|
||||
}
|
||||
case AIProvider.ANTHROPIC: {
|
||||
const anthropic = createAnthropic({ apiKey: config.apiKey });
|
||||
return anthropic(modelName);
|
||||
}
|
||||
case AIProvider.GOOGLE: {
|
||||
const google = createGoogleGenerativeAI({ apiKey: config.apiKey });
|
||||
return google(modelName);
|
||||
}
|
||||
default:
|
||||
throw new Error(`Unsupported AI provider: ${config.provider}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the API key for a specific provider from its dedicated env var.
|
||||
* Returns null when the key is unset, so callers can decide whether to 503.
|
||||
*/
|
||||
export function getProviderConfigForProvider(provider: AIProvider): AIProviderConfig | null {
|
||||
const apiKey = process.env[PROVIDER_API_KEY_ENV[provider]];
|
||||
if (!apiKey) return null;
|
||||
|
||||
return { provider, apiKey };
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the first provider that has a key configured, in preference order.
|
||||
* Used by routes that don't take an explicit model (status check, title generation).
|
||||
*/
|
||||
export function pickAnyConfiguredProvider(): AIProviderConfig | null {
|
||||
const order: AIProvider[] = [AIProvider.GOOGLE, AIProvider.OPENAI, AIProvider.ANTHROPIC];
|
||||
|
||||
for (const provider of order) {
|
||||
const config = getProviderConfigForProvider(provider);
|
||||
if (config) return config;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { AgentRole, ToolName } from '../types';
|
||||
import type { ZodType } from 'zod';
|
||||
import { getCourseStructureSchema, getLessonContentSchema, getExerciseDetailsSchema } from './shared';
|
||||
import {
|
||||
createSectionSchema,
|
||||
updateSectionSchema,
|
||||
createLessonSchema,
|
||||
updateLessonSchema,
|
||||
updateLessonContentSchema,
|
||||
createExerciseSchema,
|
||||
updateExerciseSchema,
|
||||
addQuestionsSchema,
|
||||
updateQuestionsSchema,
|
||||
updateCourseLandingPageSchema,
|
||||
checkCourseGoLiveReadinessSchema,
|
||||
goLiveCourseSchema,
|
||||
generateCoursePlanSchema
|
||||
} from './teacher';
|
||||
|
||||
export type ToolSchema = {
|
||||
description: string;
|
||||
parameters: ZodType;
|
||||
};
|
||||
|
||||
type ToolRegistry = Record<string, ToolSchema>;
|
||||
|
||||
const sharedTools: ToolRegistry = {
|
||||
[ToolName.GET_COURSE_STRUCTURE]: getCourseStructureSchema,
|
||||
[ToolName.GET_LESSON_CONTENT]: getLessonContentSchema,
|
||||
[ToolName.GET_EXERCISE_DETAILS]: getExerciseDetailsSchema
|
||||
};
|
||||
|
||||
const teacherTools: ToolRegistry = {
|
||||
[ToolName.CREATE_SECTION]: createSectionSchema,
|
||||
[ToolName.UPDATE_SECTION]: updateSectionSchema,
|
||||
[ToolName.CREATE_LESSON]: createLessonSchema,
|
||||
[ToolName.UPDATE_LESSON]: updateLessonSchema,
|
||||
[ToolName.UPDATE_LESSON_CONTENT]: updateLessonContentSchema,
|
||||
[ToolName.CREATE_EXERCISE]: createExerciseSchema,
|
||||
[ToolName.UPDATE_EXERCISE]: updateExerciseSchema,
|
||||
[ToolName.ADD_QUESTIONS]: addQuestionsSchema,
|
||||
[ToolName.UPDATE_QUESTIONS]: updateQuestionsSchema,
|
||||
[ToolName.UPDATE_COURSE_LANDING_PAGE]: updateCourseLandingPageSchema,
|
||||
[ToolName.CHECK_COURSE_GO_LIVE_READINESS]: checkCourseGoLiveReadinessSchema,
|
||||
[ToolName.GO_LIVE_COURSE]: goLiveCourseSchema,
|
||||
[ToolName.GENERATE_COURSE_PLAN]: generateCoursePlanSchema
|
||||
};
|
||||
|
||||
// v2: student tools will be added here
|
||||
const studentTools: ToolRegistry = {};
|
||||
|
||||
/**
|
||||
* Returns tool schemas available for a given role.
|
||||
* Teachers get shared + teacher tools.
|
||||
* Students get shared + student tools (v2).
|
||||
*/
|
||||
export function getToolSchemas(role: AgentRole): ToolRegistry {
|
||||
switch (role) {
|
||||
case AgentRole.TEACHER:
|
||||
return { ...sharedTools, ...teacherTools };
|
||||
case AgentRole.STUDENT:
|
||||
return { ...sharedTools, ...studentTools };
|
||||
default:
|
||||
return sharedTools;
|
||||
}
|
||||
}
|
||||
|
||||
// Re-export individual schemas for direct access
|
||||
export {
|
||||
getCourseStructureSchema,
|
||||
getLessonContentSchema,
|
||||
getExerciseDetailsSchema,
|
||||
createSectionSchema,
|
||||
updateSectionSchema,
|
||||
createLessonSchema,
|
||||
updateLessonSchema,
|
||||
updateLessonContentSchema,
|
||||
createExerciseSchema,
|
||||
updateExerciseSchema,
|
||||
addQuestionsSchema,
|
||||
updateQuestionsSchema,
|
||||
updateCourseLandingPageSchema,
|
||||
checkCourseGoLiveReadinessSchema,
|
||||
goLiveCourseSchema,
|
||||
generateCoursePlanSchema
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
/**
|
||||
* Read-only tool schemas available to both teacher and student roles.
|
||||
*/
|
||||
|
||||
export const getCourseStructureSchema = {
|
||||
description:
|
||||
'Get the full course structure including sections, lessons, and exercises as a tree. Use this to understand what content already exists before creating new content.',
|
||||
parameters: z.object({
|
||||
courseId: z.string().describe('The course ID')
|
||||
})
|
||||
};
|
||||
|
||||
export const getLessonContentSchema = {
|
||||
description:
|
||||
'Get the HTML content of a specific lesson. Use this to read existing lesson text before updating it or to understand the writing style.',
|
||||
parameters: z.object({
|
||||
courseId: z.string().describe('The course ID'),
|
||||
lessonId: z.string().describe('The lesson ID to read'),
|
||||
locale: z.string().default('en').describe('The locale to read content in')
|
||||
})
|
||||
};
|
||||
|
||||
export const getExerciseDetailsSchema = {
|
||||
description:
|
||||
'Get an exercise with all its questions and answer options. Use this to understand existing questions before adding new ones.',
|
||||
parameters: z.object({
|
||||
courseId: z.string().describe('The course ID'),
|
||||
exerciseId: z.string().describe('The exercise ID to read')
|
||||
})
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* Student tool schemas (v2 stubs).
|
||||
* These will be implemented in Phase 5 when student assistant is enabled.
|
||||
* For now, this file exists to establish the pattern and keep the registry clean.
|
||||
*/
|
||||
|
||||
// v2: explain_concept, quiz_me, clarify_exercise, get_my_progress, get_my_submissions
|
||||
@@ -0,0 +1,311 @@
|
||||
import { z } from 'zod';
|
||||
import { CoursePlanSchema } from '../types';
|
||||
|
||||
/**
|
||||
* Mutation tool schemas available only to teachers.
|
||||
*/
|
||||
|
||||
export const createSectionSchema = {
|
||||
description:
|
||||
'Create a new section in the course. Sections group lessons together. Use this when building a course structure from a plan.',
|
||||
parameters: z.object({
|
||||
courseId: z.string().describe('The course ID'),
|
||||
title: z.string().min(1).describe('Section title'),
|
||||
order: z.number().int().min(0).describe('Display order (0-based). Set after existing sections when appending.')
|
||||
})
|
||||
};
|
||||
|
||||
export const updateSectionSchema = {
|
||||
description:
|
||||
'Update metadata for an existing section in the course. Use this to rename a section or change its display order instead of creating a new section.',
|
||||
parameters: z
|
||||
.object({
|
||||
courseId: z.string().describe('The course ID'),
|
||||
sectionId: z.string().describe('The section ID to update'),
|
||||
title: z.string().min(1).optional().describe('New section title'),
|
||||
order: z.number().int().min(0).optional().describe('New section display order (0-based)')
|
||||
})
|
||||
.refine((data) => data.title !== undefined || data.order !== undefined, {
|
||||
message: 'Provide at least one field to update'
|
||||
})
|
||||
};
|
||||
|
||||
export const createLessonSchema = {
|
||||
description:
|
||||
'Create a new lesson within a section. The lesson is created with a title but no content — use update_lesson_content to add content after creation.',
|
||||
parameters: z.object({
|
||||
courseId: z.string().describe('The course ID'),
|
||||
sectionId: z.string().describe('The section ID to place the lesson in'),
|
||||
title: z.string().min(1).describe('Lesson title'),
|
||||
order: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.describe(
|
||||
'Display order within the section (0-based). Lessons and exercises share the SAME order space within a section, so increment by 1 across both. Example: lesson1=0, lesson2=1, exercise=2.'
|
||||
)
|
||||
})
|
||||
};
|
||||
|
||||
export const updateLessonSchema = {
|
||||
description:
|
||||
'Update metadata for an existing lesson in the course. Use this to rename, move, reorder, schedule, or change visibility/unlock settings for a lesson instead of creating a new lesson.',
|
||||
parameters: z
|
||||
.object({
|
||||
courseId: z.string().describe('The course ID'),
|
||||
lessonId: z.string().describe('The lesson ID to update'),
|
||||
title: z.string().min(1).optional().describe('New lesson title'),
|
||||
sectionId: z.string().optional().describe('Move the lesson into a different section'),
|
||||
order: z.number().int().min(0).optional().describe('New order within the section (0-based)'),
|
||||
lessonAt: z.string().optional().describe('Scheduled lesson datetime'),
|
||||
callUrl: z.string().optional().describe('Optional live session URL'),
|
||||
isUnlocked: z.boolean().optional().describe('Whether the lesson is unlocked for students'),
|
||||
public: z.boolean().optional().describe('Whether the lesson is public')
|
||||
})
|
||||
.refine(
|
||||
(data) =>
|
||||
data.title !== undefined ||
|
||||
data.sectionId !== undefined ||
|
||||
data.order !== undefined ||
|
||||
data.lessonAt !== undefined ||
|
||||
data.callUrl !== undefined ||
|
||||
data.isUnlocked !== undefined ||
|
||||
data.public !== undefined,
|
||||
{
|
||||
message: 'Provide at least one field to update'
|
||||
}
|
||||
)
|
||||
};
|
||||
|
||||
export const updateLessonContentSchema = {
|
||||
description:
|
||||
'Update the text content of a lesson. Replaces the full lesson HTML for the given locale. When modifying only part of a lesson, always preserve all existing content and only change the specific section requested.',
|
||||
parameters: z.object({
|
||||
courseId: z.string().describe('The course ID'),
|
||||
lessonId: z.string().describe('The lesson ID to update'),
|
||||
locale: z.string().default('en').describe('The locale to write content in'),
|
||||
content: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe(
|
||||
'The full lesson HTML content. Use only: h2, h3, p, ul, ol, li, strong, em, blockquote, code, pre, a. Never use div, span, table, img, iframe, script, or style.'
|
||||
)
|
||||
})
|
||||
};
|
||||
|
||||
export const createExerciseSchema = {
|
||||
description:
|
||||
'Create a new exercise with questions and answer options. Each question can be multiple choice (RADIO), multiple select (CHECKBOX), true/false, or other types. Quality bar: aim for 6-10 questions covering the full lesson, mixing recall, applied, and scenario-based questions; RADIO and CHECKBOX questions must have at least 4 plausible options.',
|
||||
parameters: z.object({
|
||||
courseId: z.string().describe('The course ID'),
|
||||
lessonId: z.string().optional().describe('Optional lesson ID to link the exercise to'),
|
||||
sectionId: z.string().optional().describe('Optional section ID'),
|
||||
title: z.string().min(1).describe('Exercise title'),
|
||||
description: z.string().optional().describe('Optional short description shown to students above the questions.'),
|
||||
order: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.describe(
|
||||
'Display order within the section (0-based). REQUIRED whenever sectionId is provided. Lessons and exercises share the SAME order space within a section, so an end-of-section quiz must have a higher order than every lesson in that section. Example: lesson1=0, lesson2=1, end-of-section exercise=2.'
|
||||
),
|
||||
questions: z
|
||||
.array(
|
||||
z.object({
|
||||
question: z.string().min(1).describe('The question text'),
|
||||
questionTypeId: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(14)
|
||||
.default(1)
|
||||
.describe('Question type: 1=RADIO (single answer), 2=CHECKBOX (multiple), 4=TRUE_FALSE, 3=TEXTAREA'),
|
||||
points: z.number().min(0).default(1).describe('Points for this question'),
|
||||
order: z.number().int().min(0).describe('Display order'),
|
||||
options: z
|
||||
.array(
|
||||
z.object({
|
||||
label: z.string().min(1).describe('Option text'),
|
||||
isCorrect: z.boolean().describe('Whether this is a correct answer')
|
||||
})
|
||||
)
|
||||
.describe(
|
||||
'Answer options. RADIO and CHECKBOX questions MUST have at least 4 options with plausible distractors (not obvious filler). RADIO needs exactly one correct option; CHECKBOX needs at least 2 correct and at least 1 incorrect. TRUE_FALSE uses exactly 2 options. Leave empty for NUMERIC/STAR/WORD_BANK.'
|
||||
)
|
||||
})
|
||||
)
|
||||
.min(1)
|
||||
.describe(
|
||||
'Aim for 6-10 questions per exercise when assessing a full lesson. Spread across all sub-topics, mix difficulty, and vary question types.'
|
||||
)
|
||||
})
|
||||
};
|
||||
|
||||
export const updateExerciseSchema = {
|
||||
description:
|
||||
"Update an existing exercise's metadata (title, description, linked lesson, section, order, due date, lock state, allow-multiple-attempts). Use this to edit the exercise itself — not its questions. To change questions, use update_questions; to add questions, use add_questions.",
|
||||
parameters: z
|
||||
.object({
|
||||
courseId: z.string().describe('The course ID'),
|
||||
exerciseId: z.string().describe('The exercise to update. Must be a real UUID returned by a prior tool call.'),
|
||||
title: z.string().min(1).optional().describe('New exercise title. Omit to keep unchanged.'),
|
||||
description: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe('New short description shown to students. Pass an empty string to clear it.'),
|
||||
lessonId: z.string().optional().describe('Link the exercise to a lesson in this course'),
|
||||
sectionId: z.string().optional().describe('Place the exercise in a section in this course'),
|
||||
order: z.number().int().min(0).optional().describe('New order within the section (0-based)'),
|
||||
dueBy: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe('Due date in ISO 8601 format (e.g. 2026-05-01T23:59:00Z). Omit to keep unchanged.'),
|
||||
isUnlocked: z.boolean().optional().describe('Whether the exercise is unlocked for students.'),
|
||||
allowMultipleAttempts: z.boolean().optional().describe('Whether students can re-take the exercise.')
|
||||
})
|
||||
.refine(
|
||||
(data) =>
|
||||
data.title !== undefined ||
|
||||
data.description !== undefined ||
|
||||
data.lessonId !== undefined ||
|
||||
data.sectionId !== undefined ||
|
||||
data.order !== undefined ||
|
||||
data.dueBy !== undefined ||
|
||||
data.isUnlocked !== undefined ||
|
||||
data.allowMultipleAttempts !== undefined,
|
||||
{
|
||||
message: 'Provide at least one field to update'
|
||||
}
|
||||
)
|
||||
};
|
||||
|
||||
export const addQuestionsSchema = {
|
||||
description:
|
||||
'Add questions to an existing exercise. Use this when the exercise already exists and you want to add more questions.',
|
||||
parameters: z.object({
|
||||
courseId: z.string().describe('The course ID'),
|
||||
exerciseId: z.string().describe('The existing exercise ID'),
|
||||
questions: z.array(
|
||||
z.object({
|
||||
question: z.string().min(1).describe('The question text'),
|
||||
questionTypeId: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(14)
|
||||
.default(1)
|
||||
.describe('Question type: 1=RADIO, 2=CHECKBOX, 4=TRUE_FALSE, 3=TEXTAREA'),
|
||||
points: z.number().min(0).default(1).describe('Points for this question'),
|
||||
order: z.number().int().min(0).describe('Display order'),
|
||||
options: z.array(
|
||||
z.object({
|
||||
label: z.string().min(1).describe('Option text'),
|
||||
isCorrect: z.boolean().describe('Whether this is a correct answer')
|
||||
})
|
||||
)
|
||||
})
|
||||
)
|
||||
})
|
||||
};
|
||||
|
||||
export const updateQuestionsSchema = {
|
||||
description:
|
||||
'Update existing questions in an exercise. Pass only the fields you want to change; `id` identifies the question. For NUMERIC the correct answer is `settings.correctValue` (a number), not an option — do NOT add options to NUMERIC questions. For STAR use `settings.correctValue` (1..max). For WORD_BANK use `settings.correctAnswers` and `settings.template`. RADIO/CHECKBOX/TRUE_FALSE use `options[].isCorrect`: include an option `id` to edit it, omit `id` to add a new one. `settings` is shallow-merged with the existing settings. Omit `options` entirely to leave existing options unchanged — if you pass an options array, any existing option not listed in it will be removed.',
|
||||
parameters: z.object({
|
||||
courseId: z.string().describe('The course ID'),
|
||||
exerciseId: z.string().describe('The existing exercise ID'),
|
||||
questions: z.array(
|
||||
z.object({
|
||||
id: z.number().int().describe('Existing question id. Required.'),
|
||||
question: z.string().min(1).optional().describe('New question text. Omit to keep unchanged.'),
|
||||
questionTypeId: z.number().int().min(1).max(14).optional(),
|
||||
points: z.number().min(0).optional(),
|
||||
order: z.number().int().min(0).optional(),
|
||||
settings: z
|
||||
.record(z.string(), z.unknown())
|
||||
.optional()
|
||||
.describe(
|
||||
'Per-type correct-answer storage. NUMERIC: { correctValue: number, tolerance?: number }. STAR: { correctValue: number }. WORD_BANK: { correctAnswers: string[], template: string }. Shallow-merged with existing settings.'
|
||||
),
|
||||
options: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z
|
||||
.number()
|
||||
.int()
|
||||
.optional()
|
||||
.describe('Include to update an existing option; omit to create a new one.'),
|
||||
label: z.string().min(1).optional(),
|
||||
isCorrect: z.boolean().optional(),
|
||||
settings: z.record(z.string(), z.unknown()).optional()
|
||||
})
|
||||
)
|
||||
.optional()
|
||||
})
|
||||
)
|
||||
})
|
||||
};
|
||||
|
||||
export const updateCourseLandingPageSchema = {
|
||||
description:
|
||||
'Update public course landing-page fields, including title, description, overview, goals, requirements, instructor details, pricing, and banner image.',
|
||||
parameters: z.object({
|
||||
courseId: z.string().describe('The course ID'),
|
||||
title: z.string().min(1).optional().describe('Public course title'),
|
||||
description: z.string().min(1).optional().describe('Short public course description'),
|
||||
overview: z.string().optional().describe('Landing-page overview copy'),
|
||||
cost: z.number().int().min(0).optional().describe('Course price in the selected currency'),
|
||||
currency: z.enum(['NGN', 'USD']).optional().describe('Course price currency'),
|
||||
imageUrl: z.string().url().optional().describe('Banner image URL to use directly'),
|
||||
generateImage: z.boolean().optional().describe('Whether to generate/select a banner image from the image query'),
|
||||
imageQuery: z.string().min(1).max(120).optional().describe('Search query for a generated/selected banner image'),
|
||||
metadata: z
|
||||
.object({
|
||||
requirements: z.string().optional(),
|
||||
description: z.string().optional(),
|
||||
goals: z.string().optional(),
|
||||
videoUrl: z.string().optional(),
|
||||
showDiscount: z.boolean().optional(),
|
||||
discount: z.number().optional(),
|
||||
paymentLink: z.string().optional(),
|
||||
instructor: z
|
||||
.object({
|
||||
name: z.string().optional(),
|
||||
role: z.string().optional(),
|
||||
coursesNo: z.number().optional(),
|
||||
description: z.string().optional(),
|
||||
imgUrl: z.string().optional()
|
||||
})
|
||||
.optional()
|
||||
})
|
||||
.optional()
|
||||
.describe('Landing-page metadata fields')
|
||||
})
|
||||
};
|
||||
|
||||
export const checkCourseGoLiveReadinessSchema = {
|
||||
description:
|
||||
'Check whether a course is ready to publish. Returns blockers, warnings, suggested fixes, and a public course URL when available. Does not publish the course.',
|
||||
parameters: z.object({
|
||||
courseId: z.string().describe('The course ID')
|
||||
})
|
||||
};
|
||||
|
||||
export const goLiveCourseSchema = {
|
||||
description:
|
||||
'Publish the course after the teacher explicitly asks to go live. Runs readiness checks first and fails with blockers if required fields or content are missing.',
|
||||
parameters: z.object({
|
||||
courseId: z.string().describe('The course ID'),
|
||||
confirmPublish: z.literal(true).describe('Must be true after explicit teacher confirmation to publish')
|
||||
})
|
||||
};
|
||||
|
||||
export const generateCoursePlanSchema = {
|
||||
description:
|
||||
'Generate a structured course plan with sections and lessons based on a topic or uploaded document. Returns a JSON plan that the teacher can review and approve before any content is created. Always use this tool when the teacher asks you to design, structure, or plan a course.',
|
||||
parameters: z.object({
|
||||
plan: CoursePlanSchema.describe(
|
||||
'The proposed course structure with sections and lessons. Each lesson includes a short description and whether it should have an exercise.'
|
||||
)
|
||||
})
|
||||
};
|
||||
@@ -0,0 +1,171 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
// ─── Agent Roles ─────────────────────────────────────────────────────────────
|
||||
|
||||
export const AgentRole = {
|
||||
TEACHER: 'teacher',
|
||||
STUDENT: 'student'
|
||||
} as const;
|
||||
|
||||
export type AgentRole = (typeof AgentRole)[keyof typeof AgentRole];
|
||||
|
||||
// ─── AI Provider Configuration ───────────────────────────────────────────────
|
||||
|
||||
export const AIProvider = {
|
||||
OPENAI: 'openai',
|
||||
ANTHROPIC: 'anthropic',
|
||||
GOOGLE: 'google'
|
||||
} as const;
|
||||
|
||||
export type AIProvider = (typeof AIProvider)[keyof typeof AIProvider];
|
||||
|
||||
export interface AIProviderConfig {
|
||||
provider: AIProvider;
|
||||
apiKey: string;
|
||||
model?: string;
|
||||
}
|
||||
|
||||
// ─── Agent Context (passed with each chat message) ───────────────────────────
|
||||
|
||||
export interface AgentContext {
|
||||
orgId: string;
|
||||
courseId: string;
|
||||
courseTitle: string;
|
||||
courseDescription?: string;
|
||||
userId: string;
|
||||
role: AgentRole;
|
||||
locale: string;
|
||||
lessonId?: string;
|
||||
lessonTitle?: string;
|
||||
lessonContent?: string;
|
||||
exerciseId?: string;
|
||||
exerciseTitle?: string;
|
||||
documentId?: string;
|
||||
documentText?: string;
|
||||
existingSectionCount?: number;
|
||||
}
|
||||
|
||||
// ─── Course Plan (generated by the agent in Plan Mode) ───────────────────────
|
||||
|
||||
export const CoursePlanItemSchema = z.object({
|
||||
type: z.enum(['lesson', 'exercise']).describe("'lesson' for content lessons, 'exercise' for quizzes/assessments"),
|
||||
title: z.string().min(1),
|
||||
description: z.string().min(1),
|
||||
order: z.number().int().min(0),
|
||||
hasExercise: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe('Only for lessons: whether to also create an exercise linked to this lesson')
|
||||
});
|
||||
|
||||
export const CoursePlanSectionSchema = z.object({
|
||||
title: z.string().min(1),
|
||||
order: z.number().int().min(0),
|
||||
items: z
|
||||
.array(CoursePlanItemSchema)
|
||||
.min(1)
|
||||
.describe(
|
||||
'Ordered list of lessons and exercises in this section. Use type "exercise" for standalone quizzes/assessments at the end of a section.'
|
||||
)
|
||||
});
|
||||
|
||||
export const CoursePlanSchema = z.object({
|
||||
title: z.string().min(1),
|
||||
sections: z.array(CoursePlanSectionSchema).min(1)
|
||||
});
|
||||
|
||||
export type CoursePlanItem = z.infer<typeof CoursePlanItemSchema>;
|
||||
export type CoursePlanSection = z.infer<typeof CoursePlanSectionSchema>;
|
||||
export type CoursePlan = z.infer<typeof CoursePlanSchema>;
|
||||
|
||||
// ─── Tool Names ──────────────────────────────────────────────────────────────
|
||||
|
||||
export const ToolName = {
|
||||
// Read tools (shared)
|
||||
GET_COURSE_STRUCTURE: 'get_course_structure',
|
||||
GET_LESSON_CONTENT: 'get_lesson_content',
|
||||
GET_EXERCISE_DETAILS: 'get_exercise_details',
|
||||
// Write tools (teacher only)
|
||||
CREATE_SECTION: 'create_section',
|
||||
UPDATE_SECTION: 'update_section',
|
||||
CREATE_LESSON: 'create_lesson',
|
||||
UPDATE_LESSON: 'update_lesson',
|
||||
UPDATE_LESSON_CONTENT: 'update_lesson_content',
|
||||
CREATE_EXERCISE: 'create_exercise',
|
||||
UPDATE_EXERCISE: 'update_exercise',
|
||||
ADD_QUESTIONS: 'add_questions',
|
||||
UPDATE_QUESTIONS: 'update_questions',
|
||||
UPDATE_COURSE_LANDING_PAGE: 'update_course_landing_page',
|
||||
CHECK_COURSE_GO_LIVE_READINESS: 'check_course_go_live_readiness',
|
||||
GO_LIVE_COURSE: 'go_live_course',
|
||||
// Agent tools
|
||||
GENERATE_COURSE_PLAN: 'generate_course_plan'
|
||||
} as const;
|
||||
|
||||
export type ToolName = (typeof ToolName)[keyof typeof ToolName];
|
||||
|
||||
// ─── Token Usage ─────────────────────────────────────────────────────────────
|
||||
|
||||
export interface TokenUsage {
|
||||
promptTokens: number;
|
||||
completionTokens: number;
|
||||
totalTokens: number;
|
||||
}
|
||||
|
||||
export interface TokenBalance {
|
||||
used: number;
|
||||
allowance: number;
|
||||
creditBalance: number;
|
||||
remaining: number;
|
||||
}
|
||||
|
||||
// ─── Agent Status (returned by GET /agent/status) ────────────────────────────
|
||||
|
||||
export interface AgentStatus {
|
||||
enabled: boolean;
|
||||
role: AgentRole;
|
||||
usage: TokenBalance;
|
||||
}
|
||||
|
||||
// ─── Document Upload ─────────────────────────────────────────────────────────
|
||||
|
||||
export interface DocumentUploadResult {
|
||||
documentId: string;
|
||||
fileName: string;
|
||||
mimeType: string;
|
||||
pageCount: number | null;
|
||||
wordCount: number;
|
||||
textPreview: string;
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
// ─── Constants ───────────────────────────────────────────────────────────────
|
||||
|
||||
/** Maximum characters of extracted document text to include in LLM context */
|
||||
export const MAX_DOCUMENT_TEXT_LENGTH = 100_000;
|
||||
|
||||
/** Maximum file size for document upload (5MB) */
|
||||
export const MAX_AGENT_DOCUMENT_SIZE = 5 * 1024 * 1024;
|
||||
|
||||
/** Redis TTL for uploaded document text (1 hour) */
|
||||
export const DOCUMENT_REDIS_TTL = 3600;
|
||||
|
||||
/** Maximum steps per streamText() round */
|
||||
export const MAX_STEPS_PER_ROUND = 15;
|
||||
|
||||
/** Supported MIME types for document upload */
|
||||
export const SUPPORTED_DOCUMENT_TYPES = [
|
||||
'application/pdf',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'application/vnd.openxmlformats-officedocument.presentationml.presentation'
|
||||
] as const;
|
||||
|
||||
/** Supported file extensions for document upload */
|
||||
export const SUPPORTED_DOCUMENT_EXTENSIONS = ['.pdf', '.docx', '.pptx'] as const;
|
||||
|
||||
/** Token cost estimation heuristics (tokens per item) */
|
||||
export const TOKEN_COST_ESTIMATES = {
|
||||
SECTION_CREATE: 500,
|
||||
LESSON_CREATE_AND_CONTENT: 3000,
|
||||
EXERCISE_CREATE: 1500
|
||||
} as const;
|
||||
Reference in New Issue
Block a user