### Novu Agent Toolkit - Quick Start (OpenAI) Source: https://github.com/novuhq/novu/blob/next/packages/agent-toolkit/README.md A quick start example demonstrating how to use the Novu Agent Toolkit with OpenAI to send a welcome email. ```APIDOC ## Quick Start (OpenAI) ```typescript import { createNovuAgentToolkit } from '@novu/agent-toolkit/openai'; import OpenAI from 'openai'; const openai = new OpenAI(); const toolkit = await createNovuAgentToolkit({ secretKey: process.env.NOVU_SECRET_KEY, subscriberId: 'user-123', }); const response = await openai.chat.completions.create({ model: 'gpt-4o', messages: [{ role: 'user', content: 'Send a welcome email to user-123' }], tools: toolkit.tools, }); // Handle tool calls for (const toolCall of response.choices[0].message.tool_calls ?? []) { const result = await toolkit.handleToolCall(toolCall); console.log(result); } ``` ``` -------------------------------- ### Start Novu Development Server Source: https://github.com/novuhq/novu/blob/next/packages/novu/README.MD Run this command to start the Novu development server. It guides you through the setup process. ```bash npx novu@latest dev ``` -------------------------------- ### Clone Novu and Start Docker Services Source: https://github.com/novuhq/novu/blob/next/docker/Readme.md Clone the Novu repository, navigate to the docker directory, copy the example environment file, and start Novu using docker-compose. ```sh # Get the code git clone https://github.com/novuhq/novu # Go to the docker folder cd novu/docker # Copy the example env file cp .env.example ./local/.env # Start Novu docker-compose -f ./local/docker-compose.yml up ``` -------------------------------- ### Setup Agent Environment Source: https://github.com/novuhq/novu/blob/next/AGENTS.md Run this command to set up the agent environment. It installs dependencies, links packages, builds the project, and configures environment files and Docker services. ```bash pnpm setup:agent ``` -------------------------------- ### Initialize Novu Project Source: https://github.com/novuhq/novu/blob/next/packages/novu/README.MD Use this command to initialize a new Novu project. It will guide you through the necessary setup steps. ```bash npx novu init ``` -------------------------------- ### Start Development Server Source: https://github.com/novuhq/novu/blob/next/packages/novu/src/commands/init/templates/app-agent/ts/README-template.md Run this command to start the local development server for the Novu Agent. ```bash npm run dev ``` -------------------------------- ### Install @novu/agent-toolkit Source: https://github.com/novuhq/novu/blob/next/packages/agent-toolkit/README.md Install the agent toolkit using npm. Ensure to also install the appropriate peer dependency for your framework. ```bash npm install @novu/agent-toolkit ``` -------------------------------- ### Install and Run add-inbox CLI Source: https://github.com/novuhq/novu/blob/next/packages/add-inbox/README.md Execute this command to start the interactive process for adding the Novu Inbox component to your project. ```bash npx add-inbox@latest ``` -------------------------------- ### Install and Use Node.js Version Source: https://github.com/novuhq/novu/blob/next/CONTRIBUTING.md Installs and uses a specific Node.js version using NVM. Ensure NVM is installed first. ```bash nvm install 22.22.1 nvm use 22.22.1 node -v # output: v22.22.1 ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/novuhq/novu/blob/next/apps/api/jarvis-api-intro.md Run this command from the root of the repository to install all necessary project dependencies. ```bash npm run setup:project ``` -------------------------------- ### Build and Run Example Script Source: https://github.com/novuhq/novu/blob/next/libs/internal-sdk/examples/README.md Build the project and then execute an example TypeScript file using tsx. ```bash npm run build && npx tsx example.ts ``` -------------------------------- ### Install @novu/maily-render Source: https://github.com/novuhq/novu/blob/next/libs/maily-render/readme.md Install the library using pnpm. ```sh pnpm add @novu/maily-render ``` -------------------------------- ### Start All Dependency Services Source: https://github.com/novuhq/novu/blob/next/docker/Readme.md Use this command to start all dependency services required for local development with Novu. ```sh # Start all dependency services (recommended) docker-compose -f docker/local/docker-compose.yml up -d ``` -------------------------------- ### Local Development Setup Source: https://github.com/novuhq/novu/blob/next/enterprise/workers/step-resolver/README.md Commands to install dependencies and run the worker locally using pnpm. For local development with wrangler, set the secret in a .dev.vars file. ```bash pnpm install ``` ```bash pnpm --filter @novu/step-resolver-worker dev ``` ```bash pnpm run dev ``` ```bash STEP_RESOLVER_HMAC_SECRET=local-dev-secret ``` -------------------------------- ### Run NestJS Application Source: https://github.com/novuhq/novu/blob/next/playground/nestjs/README.md Starts the NestJS application. This command assumes you are within the Novu monorepo and have installed dependencies. ```bash pnpm start ``` -------------------------------- ### Install Novu Providers Source: https://github.com/novuhq/novu/blob/next/packages/providers/README.md Use npm to install the @novu/providers package. ```bash npm install @novu/providers ``` -------------------------------- ### Novu Agent Toolkit - Installation Source: https://github.com/novuhq/novu/blob/next/packages/agent-toolkit/README.md Instructions for installing the Novu Agent Toolkit and its framework-specific peer dependencies. ```APIDOC ## Installation ```bash npm install @novu/agent-toolkit ``` Install the peer dependency for the framework you use: | Framework | Peer dependency | |---|---| | OpenAI | `openai >= 4.0.0` | | LangChain | `@langchain/core >= 0.2.0` | | Vercel AI SDK | `ai >= 6.0.0` | ``` -------------------------------- ### Install @novu/maily-core and Types Source: https://github.com/novuhq/novu/blob/next/libs/maily-core/readme.md Install the core package and its type definitions using pnpm. ```bash pnpm add @novu/maily-core # for types pnpm add -D @tiptap/core ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/novuhq/novu/blob/next/apps/worker/README.md Run this command in your project's root directory to install all necessary Node.js dependencies. ```bash $ npm install ``` -------------------------------- ### Install Novu JavaScript SDK Source: https://github.com/novuhq/novu/blob/next/packages/js/README.md Install the @novu/js npm package in your application using npm. ```bash npm install @novu/js ``` -------------------------------- ### Example translation file structure Source: https://github.com/novuhq/novu/blob/next/packages/novu/src/commands/translations/README.md Illustrates the expected directory structure and naming convention for translation files. ```bash translations/ ├── en_US.json ├── fr_FR.json ├── es_ES.json └── de_DE.json ``` -------------------------------- ### Copy Environment File Source: https://github.com/novuhq/novu/blob/next/playground/nestjs/README.md Copies the example environment file to a new file. Ensure you set the correct environment variables in the new file. ```bash cp .env.example .env ``` -------------------------------- ### Start Local ClickHouse Instance Source: https://github.com/novuhq/novu/blob/next/apps/api/migrations/clickhouse-migrations/README.md Use Docker Compose to start a local ClickHouse instance for development and testing. ```bash cd /path/to/novu docker-compose -f docker/local/docker-compose.yml up -d clickhouse ``` -------------------------------- ### Install Novu Framework Source: https://github.com/novuhq/novu/blob/next/packages/framework/README.md Install the Novu Framework package using npm. This command adds the necessary dependencies to your project. ```bash npm install @novu/framework ``` -------------------------------- ### Install Novu Stateless with npm Source: https://github.com/novuhq/novu/blob/next/packages/stateless/README.md Install the Novu Stateless SDK using npm. This is the primary package manager for Node.js. ```bash npm install @novu/stateless ``` -------------------------------- ### Quick Start with OpenAI Source: https://github.com/novuhq/novu/blob/next/packages/agent-toolkit/README.md Initialize the Novu agent toolkit for OpenAI and use it to create chat completions. Handle tool calls by iterating through `response.choices[0].message.tool_calls` and passing them to `toolkit.handleToolCall`. ```typescript import { createNovuAgentToolkit } from '@novu/agent-toolkit/openai'; import OpenAI from 'openai'; const openai = new OpenAI(); const toolkit = await createNovuAgentToolkit({ secretKey: process.env.NOVU_SECRET_KEY, subscriberId: 'user-123', }); const response = await openai.chat.completions.create({ model: 'gpt-4o', messages: [{ role: 'user', content: 'Send a welcome email to user-123' }], tools: toolkit.tools, }); // Handle tool calls for (const toolCall of response.choices[0].message.tool_calls ?? []) { const result = await toolkit.handleToolCall(toolCall); console.log(result); } ``` -------------------------------- ### Run Nest.js Application Source: https://github.com/novuhq/novu/blob/next/apps/worker/README.md Commands to start the Nest.js application in different modes. Use 'start:dev' for development with hot-reloading and 'start:prod' for production builds. ```bash # development $ npm run start # watch mode $ npm run start:dev # incremental rebuild (webpack) $ npm run webpack $ npm run start:hmr # production mode $ npm run start:prod ``` -------------------------------- ### Install Novu Stateless with Yarn Source: https://github.com/novuhq/novu/blob/next/packages/stateless/README.md Install the Novu Stateless SDK using Yarn. This is an alternative package manager for Node.js. ```bash yarn add @novu/stateless ``` -------------------------------- ### Install Novu API Package Source: https://github.com/novuhq/novu/blob/next/packages/novu/README.MD Install the Novu API client package for Node.js using npm. ```bash npm install @novu/api ``` -------------------------------- ### Install Novu React SDK Source: https://github.com/novuhq/novu/blob/next/packages/react/README.md Install the @novu/react npm package in your React application using npm. ```bash npm install @novu/react ``` -------------------------------- ### Run Nx Development Server Source: https://github.com/novuhq/novu/blob/next/libs/automation/README.md Command to start the development server for a specific project. This is useful for local development and testing. ```bash npx nx serve demo ``` -------------------------------- ### Install Novu React Native SDK Source: https://github.com/novuhq/novu/blob/next/packages/react-native/README.md Install the @novu/react-native npm package in your React application to begin using the SDK. ```bash npm install @novu/react-native ``` -------------------------------- ### Run Development Server Source: https://github.com/novuhq/novu/blob/next/packages/novu/src/commands/init/templates/app-react-email/ts/README-template.md Use these commands to start the development server for the Novu Bridge App. The server typically runs on http://localhost:4000. ```bash npm run dev ``` ```bash yarn dev ``` ```bash pnpm dev ``` ```bash bun dev ``` -------------------------------- ### Install Novu NextJS Package Source: https://github.com/novuhq/novu/blob/next/packages/nextjs/README.md Install the @novu/nextjs npm package in your NextJS application. ```bash npm install @novu/nextjs ``` -------------------------------- ### Example Migration: Add Performance Tracking Columns and Index Source: https://github.com/novuhq/novu/blob/next/apps/api/migrations/clickhouse-migrations/README.md This SQL migration adds 'execution_time_ms' and 'retry_count' columns to the 'step_runs' table and creates an index for performance queries. ```sql -- Add step execution metrics -- This migration adds performance tracking columns to step_runs table ALTER TABLE IF EXISTS step_runs ADD COLUMN IF NOT EXISTS execution_time_ms UInt32 DEFAULT 0, ADD COLUMN IF NOT EXISTS retry_count UInt8 DEFAULT 0; -- Add index for performance queries CREATE INDEX IF NOT EXISTS idx_step_runs_execution_time ON step_runs (execution_time_ms) TYPE minmax GRANULARITY 4; ``` -------------------------------- ### Example JSON content for a translation file Source: https://github.com/novuhq/novu/blob/next/packages/novu/src/commands/translations/README.md Provides an example of the valid JSON structure for a locale file, showing nested workflow translations. ```json { "workflows": { "welcome": { "subject": "Welcome to our platform!", "body": "Thank you for joining us." } } } ``` -------------------------------- ### Novu Stateless SDK Usage Example Source: https://github.com/novuhq/novu/blob/next/packages/stateless/README.md Demonstrates registering a Sendgrid email provider, registering a password reset template, and triggering an event using the Novu Stateless SDK in TypeScript. Ensure environment variables like SENDGRID_API_KEY are set. ```typescript import { NovuStateless, ChannelTypeEnum } from '@novu/stateless'; import { SendgridEmailProvider } from '@novu/providers'; const novu = new NovuStateless(); await novu.registerProvider( new SendgridEmailProvider({ apiKey: process.env.SENDGRID_API_KEY, from: 'sender@mail.com', }), ); const passwordResetTemplate = await novu.registerTemplate({ id: 'password-reset', messages: [ { subject: 'Your password reset request', channel: ChannelTypeEnum.EMAIL, template: ` Hi {{firstName}}! To reset your password click here. {{#if organization}} {{/if}} `, }, ], }); await novu.trigger('', { $user_id: '', $email: 'test@email.com', firstName: 'John', lastName: 'Doe', organization: { logo: 'https://evilcorp.com/logo.png', }, }); ``` -------------------------------- ### Novu CLI Development Flags Example Source: https://github.com/novuhq/novu/blob/next/packages/novu/README.MD This example demonstrates how to use Novu CLI flags to configure the bridge application's port and dashboard URL, useful when running on a custom port or in a specific region. ```bash npx novu@latest dev --port 3002 --dashboard-url https://eu.dashboard.novu.co ``` -------------------------------- ### Start Specific Service (ClickHouse) Source: https://github.com/novuhq/novu/blob/next/docker/Readme.md Start only the ClickHouse service if other services are already running or if you only need this specific service. ```sh # Run only ClickHouse docker-compose -f docker/local/docker-compose.yml up -d clickhouse ``` -------------------------------- ### Example Production Environment Variables for Migrations Source: https://github.com/novuhq/novu/blob/next/apps/api/migrations/clickhouse-migrations/README.md Set these environment variables in your deployment environment to configure the clickhouse-migrations package for production or staging. ```bash CH_MIGRATIONS_HOST=http://clickhouse.example.com:8123 CH_MIGRATIONS_USER=your_user CH_MIGRATIONS_PASSWORD=your_password CH_MIGRATIONS_DB=your_database CH_MIGRATIONS_HOME=./migrations/clickhouse-migrations ``` -------------------------------- ### Run API Service in Watch Mode Source: https://github.com/novuhq/novu/blob/next/apps/api/jarvis-api-intro.md Start the API service in watch mode for development. This command should be run from the root of the repository. ```bash npm run start:api ``` -------------------------------- ### Run ClickHouse Seeding Script (Custom Configuration) Source: https://github.com/novuhq/novu/blob/next/apps/api/scripts/clickhouse-seeder/README.md Execute the ClickHouse seeding script with custom parameters for organizations, days, scale, batch size, and start date. This allows for fine-grained control over data generation. ```bash pnpm seed:clickhouse -- \ --organizations=20 \ --days=7 \ --scale=5 \ --batch-size=5000 \ --start-date=2024-01-01 ``` -------------------------------- ### Trigger a Notification with Novu API Source: https://github.com/novuhq/novu/blob/next/packages/novu/README.MD This TypeScript example shows how to initialize the Novu client with your API key and trigger a notification. Ensure your NOVU_API_KEY is set in your environment variables. ```typescript import { Novu } from '@novu/api'; const novu = new Novu({ secretKey: process.env.NOVU_API_KEY }); await novu.trigger('', { to: { subscriberId: '', email: 'john@doemail.com', firstName: 'John', lastName: 'Doe', }, payload: { name: 'Hello World', organization: { logo: 'https://happycorp.com/logo.png', }, }, }); ``` -------------------------------- ### Define and Serve Notification Workflows with Novu Framework Source: https://github.com/novuhq/novu/blob/next/packages/framework/README.md This TypeScript example demonstrates how to define a notification workflow using Novu Framework's `workflow` function. It includes steps for in-app notifications, a weekly digest triggered by a cron expression, and an email notification. The workflow is served using `@novu/framework/next` and includes payload validation with Zod. Use this pattern to integrate custom notification logic into your application. ```typescript import { workflow, CronExpression } from '@novu/framework'; import { serve } from '@novu/framework/next'; import { z } from 'zod'; // Define your notification workflow const weeklyComments = workflow( 'comment-on-post', async ({ payload, step }) => { const inAppResponse = await step.inApp('new-comment', async () => ({ body: `You have a new comment on your post ${payload.comment}`, })); const weeklyDigest = await step.digest('weekly-digest', () => ({ cron: CronExpression.EVERY_WEEK, })); await step.email( 'weekly-comments', async (controls) => ({ subject: `${controls.prefix} - Weekly post comments (${weeklyDigest.events.length})`, body: `Weekly digest: ${weeklyDigest.events.map(({ payload }) => payload.comment).join(', ')}`, }), { // Skip the notification if the weekly digest is empty skip: () => weeklyDigest.events.length === 0, // Non-technical stakeholders can modify strongly-validated copy in Novu Cloud controlSchema: z.object({ prefix: z.string().describe('The prefix of the subject.').default('Hi!') }), } ); }, { payloadSchema: z.object({ comment: z.string().describe('The comment on the post.') }) } ); // Use your favorite framework to serve your workflows const { GET, POST, OPTIONS } = serve({ workflows: [weeklyComments] }); // Trigger your notification workflow weeklyComments.trigger({ to: 'user:123', comment: 'This is a comment on a post' }); ``` -------------------------------- ### Run Novu API in Watch Mode Source: https://github.com/novuhq/novu/blob/next/apps/api/README.md Use this command to run the Novu API in watch mode for development. Ensure you have followed the local setup guide. ```bash # Run the API in watch mode $ npm run start:api ``` -------------------------------- ### Build Project Source: https://github.com/novuhq/novu/blob/next/AGENTS.md Execute this command to build the project after making changes to packages or enterprise directories. Changes in apps/ do not require a rebuild. ```bash pnpm build ``` -------------------------------- ### Initialize Novu SDK and Fetch Notifications Source: https://github.com/novuhq/novu/blob/next/packages/js/README.md Initialize the Novu SDK with your application identifier and subscriber ID, then fetch a list of notifications. Ensure you replace placeholders with your actual credentials. ```typescript import { Novu } from '@novu/js'; const novu = new Novu({ applicationIdentifier: 'YOUR_NOVU_APPLICATION_IDENTIFIER', subscriber: 'YOUR_INTERNAL_SUBSCRIBER_ID', }); const { data: notifications, error } = await novu.notifications.list(); ``` -------------------------------- ### Add Nx Plugin and Generate App Source: https://github.com/novuhq/novu/blob/next/libs/automation/README.md Use these commands to add a new Nx plugin and then generate an application using that plugin's generators. Ensure you have npx available. ```bash npx nx add @nx/react ``` ```bash npx nx generate @nx/react:app demo ``` -------------------------------- ### Node.js HMAC Signing Example Source: https://github.com/novuhq/novu/blob/next/enterprise/workers/step-resolver/README.md Example of how to generate an HMAC signature for requests using Node.js crypto module. Ensure the secret and payload match the expected format for validation. ```typescript import { createHmac } from 'node:crypto'; const secret = process.env.STEP_RESOLVER_HMAC_SECRET!; const payload = { payload: { firstName: 'Ada' }, subscriber: { email: 'ada@example.com' }, context: {}, steps: {}, }; const timestamp = Date.now(); const bodyString = JSON.stringify(payload); const data = `${timestamp}.${bodyString}`; const hmac = createHmac('sha256', secret).update(data).digest('hex'); const signature = `t=${timestamp},v1=${hmac}`; // Send as headers: // X-Novu-Signature: t=1234567890,v1=abc123... // Body: (same string used in HMAC computation) ``` -------------------------------- ### Basic Nx Task Execution Source: https://github.com/novuhq/novu/blob/next/libs/automation/README.md The fundamental syntax for executing tasks with Nx. Replace `` and `` with your specific task and project names. ```bash npx nx <...options> ``` -------------------------------- ### Collect Environment Information Source: https://github.com/novuhq/novu/blob/next/libs/internal-sdk/CONTRIBUTING.md Use this command to gather environment details when reporting issues, provided you have Node.js installed. ```bash npx envinfo ``` -------------------------------- ### Show Project Details with Nx Source: https://github.com/novuhq/novu/blob/next/libs/automation/README.md Retrieve and display detailed information about a specific project within your Nx workspace. This command helps in understanding project configurations and dependencies. ```bash npx nx show project demo --web ``` -------------------------------- ### Copy .env.template to .env Source: https://github.com/novuhq/novu/blob/next/libs/internal-sdk/examples/README.md Copy the template environment file to create your own configuration. ```bash cp .env.template .env ``` -------------------------------- ### Initialize Novu Agent Toolkit for Vercel AI SDK Source: https://github.com/novuhq/novu/blob/next/packages/agent-toolkit/README.md Creates a toolkit instance for use with the Vercel AI SDK. The `toolkit.tools` property provides a `ToolSet` compatible with `generateText` and `streamText` functions. ```typescript import { createNovuAgentToolkit } from '@novu/agent-toolkit/ai-sdk'; const toolkit = await createNovuAgentToolkit({ secretKey: process.env.NOVU_SECRET_KEY, subscriberId: 'user-123', }); // toolkit.tools — ToolSet compatible with generateText / streamText ``` -------------------------------- ### Serving Novu Workflows with SvelteKit Source: https://context7.com/novuhq/novu/llms.txt Integrates Novu workflows into a SvelteKit application. Requires importing the 'serve' function from '@novu/framework/sveltekit' and your workflow definition. ```typescript // SVELTEKIT (src/routes/api/novu/+server.ts) import { serve } from '@novu/framework/sveltekit'; import { myWorkflow } from '$lib/novu/workflows'; export const { GET, POST, OPTIONS } = serve({ workflows: [myWorkflow] }); ``` -------------------------------- ### Integrate ESLint React Plugin Source: https://github.com/novuhq/novu/blob/next/apps/dashboard/README.md Configure ESLint to use the eslint-plugin-react, setting the React version and enabling its recommended rules. This setup is for eslint.config.js. ```javascript // eslint.config.js import react from 'eslint-plugin-react'; export default tseslint.config({ // Set the react version settings: { react: { version: '18.3' } }, plugins: { // Add the react plugin react, }, rules: { // other rules... // Enable its recommended rules ...react.configs.recommended.rules, ...react.configs['jsx-runtime'].rules, }, }); ``` -------------------------------- ### Initialize Novu Client and Manage Notifications Source: https://context7.com/novuhq/novu/llms.txt Initializes the Novu client with application identifier, subscriber ID, and optional HMAC hash. Demonstrates listing, counting, marking as read/unread, seen, archiving, snoozing, deleting, and bulk actions for notifications. Also shows how to subscribe to real-time events. ```typescript import { Novu } from '@novu/js'; // Initialize the Novu client const novu = new Novu({ applicationIdentifier: 'YOUR_APPLICATION_IDENTIFIER', subscriberId: 'user-123', // Optional: HMAC authentication for security subscriberHash: 'HMAC_HASH_FROM_BACKEND', }); // LIST NOTIFICATIONS const { data: notificationsList, error } = await novu.notifications.list({ limit: 10, status: 'unread', // 'unread' | 'read' | 'archived' tags: ['orders', 'updates'], }); if (notificationsList) { console.log(`Found ${notificationsList.notifications.length} notifications`); console.log('Has more:', notificationsList.hasMore); for (const notification of notificationsList.notifications) { console.log(notification.id, notification.body, notification.createdAt); } } // COUNT NOTIFICATIONS const { data: count } = await novu.notifications.count({ status: 'unread', }); console.log(`Unread count: ${count?.count}`); // MARK AS READ/UNREAD await novu.notifications.read({ notificationId: 'notification-123' }); await novu.notifications.unread({ notificationId: 'notification-123' }); // MARK AS SEEN await novu.notifications.seen({ notificationId: 'notification-123' }); // ARCHIVE/UNARCHIVE await novu.notifications.archive({ notificationId: 'notification-123' }); await novu.notifications.unarchive({ notificationId: 'notification-123' }); // SNOOZE/UNSNOOZE NOTIFICATIONS await novu.notifications.snooze({ notificationId: 'notification-123', until: new Date(Date.now() + 3600000), // Snooze for 1 hour }); await novu.notifications.unsnooze({ notificationId: 'notification-123' }); // DELETE NOTIFICATION await novu.notifications.delete({ notificationId: 'notification-123' }); // BULK ACTIONS await novu.notifications.readAll({ tags: ['orders'] }); await novu.notifications.archiveAll({ tags: ['promotions'] }); await novu.notifications.archiveAllRead(); await novu.notifications.deleteAll({ tags: ['old-notifications'] }); // COMPLETE ACTION BUTTONS await novu.notifications.completePrimary({ notificationId: 'notification-123' }); await novu.notifications.completeSecondary({ notificationId: 'notification-123' }); // REAL-TIME EVENTS const unsubscribe = novu.on('notifications.notification_received', (event) => { console.log('New notification:', event.result); }); novu.on('notifications.unread_count_changed', (event) => { console.log('Unread count changed:', event.result); }); // Clean up event listener unsubscribe(); ``` -------------------------------- ### Send SMS with Twilio using Novu Providers Source: https://github.com/novuhq/novu/blob/next/packages/providers/README.md Example of sending an SMS using the TwilioSmsProvider. Ensure your Twilio credentials and phone number are set as environment variables. ```javascript import { TwilioSmsProvider } from '@novu/providers'; const provider = new TwilioSmsProvider({ accountSid: process.env.TWILIO_ACCOUNT_SID, authToken: process.env.TWILIO_AUTH_TOKEN, from: process.env.TWILIO_FROM_NUMBER, // a valid twilio phone number }); await provider.sendMessage({ to: '0123456789', content: 'Message to send', }); ``` -------------------------------- ### Run Tests Source: https://github.com/novuhq/novu/blob/next/playground/nestjs/README.md Executes the test suite for the project. This command is used to verify the application's functionality. ```bash pnpm test ``` -------------------------------- ### Initialize Novu SDK with Context and Context Hash Source: https://github.com/novuhq/novu/blob/next/packages/js/README.md Initialize the Novu SDK with subscriber details, context, and the generated context hash. The contextHash is required when context is provided and HMAC encryption is enabled. ```typescript const novu = new Novu({ applicationIdentifier: 'YOUR_NOVU_APPLICATION_IDENTIFIER', subscriber: 'SUBSCRIBER_ID', subscriberHash: 'SUBSCRIBER_HASH_VALUE', context: { tenant: 'acme', app: 'dashboard' }, contextHash: 'CONTEXT_HASH_VALUE', }); ``` -------------------------------- ### Increase ClickHouse Batch Size Source: https://github.com/novuhq/novu/blob/next/apps/api/scripts/clickhouse-seeder/README.md For improved insertion performance on systems with sufficient memory, increase the batch size. This can lead to faster data seeding, as shown in this command example. ```bash pnpm seed:clickhouse -- --batch-size=20000 ``` -------------------------------- ### Curl Smoke Test for Step Resolver Source: https://github.com/novuhq/novu/blob/next/enterprise/workers/step-resolver/README.md Example curl command to test the Step Resolver dispatch worker. Ensure the DISPATCH_URL and STEP_RESOLVER_HMAC_SECRET environment variables are set correctly. ```bash DISPATCH_URL="https://step-resolver-dispatch-staging..workers.dev" ORGANIZATION_ID="696a21b632ef1f83460d584d" STEP_RESOLVER_HASH="abc12-def34" STEP_ID="welcome-email" SECRET="${STEP_RESOLVER_HMAC_SECRET:?set STEP_RESOLVER_HMAC_SECRET}" PATHNAME="/resolve/${ORGANIZATION_ID}/sr-${STEP_RESOLVER_HASH}/${STEP_ID}" BODY='{"payload":{"firstName":"Ada"},"subscriber":{"email":"ada@example.com"},"context":{},"steps":{}}' ``` -------------------------------- ### Run ClickHouse Seeding Script (Basic) Source: https://github.com/novuhq/novu/blob/next/apps/api/scripts/clickhouse-seeder/README.md Execute the basic ClickHouse seeding script from the 'apps/api' directory. This generates default data volumes for organizations, days, and records. ```bash pnpm seed:clickhouse ``` -------------------------------- ### Initialize Novu Agent Toolkit for OpenAI Source: https://github.com/novuhq/novu/blob/next/packages/agent-toolkit/README.md Creates a toolkit instance for use with the OpenAI framework. The `toolkit.tools` property provides OpenAI function tool definitions, and `toolkit.handleToolCall` executes tool calls. ```typescript import { createNovuAgentToolkit } from '@novu/agent-toolkit/openai'; const toolkit = await createNovuAgentToolkit({ secretKey: process.env.NOVU_SECRET_KEY, subscriberId: 'user-123', }); // toolkit.tools — OpenAI function tool definitions // toolkit.handleToolCall — execute a tool call and return a tool message ``` -------------------------------- ### Use Novu Inbox in Keyless Mode Source: https://github.com/novuhq/novu/blob/next/packages/react/README.md Import and render the Inbox component for local testing and experimentation without any configuration. This mode is ideal for quick setup and trying out Novu's features. ```jsx import React from 'react'; import { Inbox } from '@novu/react'; export function App() { return ; } ``` -------------------------------- ### Migration with ClickHouse Settings Source: https://github.com/novuhq/novu/blob/next/apps/api/migrations/clickhouse-migrations/README.md Include query-level settings, such as enabling experimental features, at the beginning of a migration file. ```sql SET allow_experimental_json_type = 1; CREATE TABLE IF NOT EXISTS events (data JSON) ENGINE = MergeTree ...; ``` -------------------------------- ### Next.js Server Component Layout with Inbox Integration Source: https://context7.com/novuhq/novu/llms.txt Example of a Next.js server component layout that fetches user data, generates an HMAC hash on the server for security, and includes the client-side Notifications component. ```tsx // app/layout.tsx (Server Component) import { createHmac } from 'crypto'; import { Notifications } from './components/Notifications'; import { getCurrentUser } from './auth'; export default async function RootLayout({ children }: { children: React.ReactNode }) { const user = await getCurrentUser(); // Generate HMAC on server for security const subscriberHash = createHmac('sha256', process.env.NOVU_API_KEY!) .update(user.id) .digest('hex'); return (
{children} ); } ``` -------------------------------- ### Novu ClickHouse Seeder File Structure Source: https://github.com/novuhq/novu/blob/next/apps/api/scripts/clickhouse-seeder/README.md This overview illustrates the directory structure for the ClickHouse seeder script, highlighting the main entry point and the modular components responsible for configuration, data generation, and insertion. ```bash apps/api/scripts/ ├── seed-clickhouse.ts # Main entry point └── clickhouse-seeder/ ├── config.ts # Configuration and CLI parsing ├── time-distribution.ts # Time pattern generation ├── generators.ts # Data generation logic ├── inserter.ts # Batched ClickHouse insertion └── README.md # This file ``` -------------------------------- ### Initialize Novu Agent Toolkit for LangChain Source: https://github.com/novuhq/novu/blob/next/packages/agent-toolkit/README.md Creates a toolkit instance for use with the LangChain framework. The `toolkit.tools` property provides `DynamicStructuredTool[]` instances ready for LangChain agents. ```typescript import { createNovuAgentToolkit } from '@novu/agent-toolkit/langchain'; const toolkit = await createNovuAgentToolkit({ secretKey: process.env.NOVU_SECRET_KEY, subscriberId: 'user-123', }); // toolkit.tools — DynamicStructuredTool[] ready for use with LangChain agents ``` -------------------------------- ### Add New Workflow Template in config.ts Source: https://github.com/novuhq/novu/blob/next/apps/api/scripts/clickhouse-seeder/README.md Customize the types of workflows generated by adding new templates to the `WORKFLOW_TEMPLATES` array in `config.ts`. This example adds a 'support' workflow type with email and SMS channels. ```typescript export const WORKFLOW_TEMPLATES: WorkflowTemplate[] = [ // ... existing templates { type: 'support', name: 'Support Ticket', channels: ['email', 'sms'], weight: 0.1 }, ]; ``` -------------------------------- ### Add New Organization Profile in config.ts Source: https://github.com/novuhq/novu/blob/next/apps/api/scripts/clickhouse-seeder/README.md Extend the data generation capabilities by defining new organization profiles in `config.ts`. This example shows how to add a 'startup' profile with specific ranges for daily runs, workflows, subscribers, and environments. ```typescript export const ORGANIZATION_PROFILES = { // ... existing profiles startup: { type: 'startup', runsPerDayMin: 10, runsPerDayMax: 100, workflowsMin: 1, workflowsMax: 3, subscribersMin: 10, subscribersMax: 100, environmentsMin: 1, environmentsMax: 1, }, }; ``` -------------------------------- ### Integrate Novu Workflows with Vercel AI SDK Source: https://context7.com/novuhq/novu/llms.txt Employ the `createNovuAgentToolkit` for the AI SDK to enable Novu workflow integration within the Vercel AI SDK. This setup involves using `generateText` with the specified model and Novu's tools. ```typescript // VERCEL AI SDK INTEGRATION import { createNovuAgentToolkit } from '@novu/agent-toolkit/ai-sdk'; import { generateText } from 'ai'; import { openai } from '@ai-sdk/openai'; const aiSdkToolkit = await createNovuAgentToolkit({ secretKey: process.env.NOVU_SECRET_KEY!, subscriberId: 'user-123', }); const { text, toolCalls } = await generateText({ model: openai('gpt-4o'), tools: aiSdkToolkit.tools, prompt: 'Notify user-456 about their shipping update', }); console.log('Response:', text); console.log('Tool calls:', toolCalls); ``` -------------------------------- ### Run Production/Staging ClickHouse Migrations Source: https://github.com/novuhq/novu/blob/next/apps/api/migrations/clickhouse-migrations/README.md Execute ClickHouse migrations in production or staging environments using a pnpm script that respects environment variables for connection details. ```bash pnpm run clickhouse:migrate:prod ``` -------------------------------- ### Sending Notifications with Novu Workflow SDK Source: https://context7.com/novuhq/novu/llms.txt Demonstrates various step types for sending notifications via email, SMS, push, chat, and in-app messages. Includes examples of delay and digest steps for workflow control. Requires payload schema definition. ```typescript import { workflow } from '@novu/framework'; import { z } from 'zod'; const multiChannelWorkflow = workflow( 'order-confirmation', async ({ payload, step }) => { // EMAIL STEP - Send transactional email await step.email('order-email', async () => ({ subject: `Order Confirmed #${payload.orderId}`, body: `

Thank you for your order!

Order ID: ${payload.orderId}

Total: $${payload.total}

`, })); // SMS STEP - Send text message await step.sms('order-sms', async () => ({ body: `Your order #${payload.orderId} is confirmed! Total: $${payload.total}`, })); // PUSH STEP - Send push notification await step.push('order-push', async () => ({ subject: 'Order Confirmed', body: `Order #${payload.orderId} has been confirmed`, data: { orderId: payload.orderId }, })); // CHAT STEP - Send to Slack/Discord/Teams await step.chat('order-chat', async () => ({ body: `New order received: #${payload.orderId} - $${payload.total}`, })); // IN-APP STEP - Send to Novu Inbox await step.inApp('order-inbox', async () => ({ body: `Your order #${payload.orderId} is confirmed`, avatar: 'https://example.com/order-icon.png', primaryAction: { label: 'View Order', redirect: { url: `/orders/${payload.orderId}` }, }, secondaryAction: { label: 'Track Shipment', redirect: { url: `/track/${payload.orderId}` }, }, data: { orderId: payload.orderId, total: payload.total }, })); // DELAY STEP - Wait before next step await step.delay('shipping-delay', async () => ({ amount: 2, unit: 'hours', })); // DIGEST STEP - Aggregate events over time const digest = await step.digest('daily-digest', async () => ({ amount: 24, unit: 'hours', lookBackWindow: { amount: 24, unit: 'hours' }, })); // Access digest events if (digest.events.length > 0) { await step.email('digest-summary', async () => ({ subject: `Daily Summary: ${digest.events.length} orders`, body: `You had ${digest.events.length} orders today.`, })); } }, { payloadSchema: z.object({ orderId: z.string(), total: z.number(), items: z.array(z.object({ name: z.string(), quantity: z.number(), })), }), } ); ``` -------------------------------- ### Novu Agent Toolkit - Vercel AI SDK Adapter Source: https://github.com/novuhq/novu/blob/next/packages/agent-toolkit/README.md Information on using the Novu Agent Toolkit with the Vercel AI SDK. ```APIDOC ## Vercel AI SDK Adapter ```typescript import { createNovuAgentToolkit } from '@novu/agent-toolkit/ai-sdk'; const toolkit = await createNovuAgentToolkit({ secretKey: process.env.NOVU_SECRET_KEY, subscriberId: 'user-123', }); // toolkit.tools — ToolSet compatible with generateText / streamText ``` The returned `toolkit` provides: - **`tools`** — A `ToolSet` object that can be passed to `generateText`, `streamText`, or other Vercel AI SDK functions. ``` -------------------------------- ### Novu Agent Toolkit - OpenAI Adapter Source: https://github.com/novuhq/novu/blob/next/packages/agent-toolkit/README.md Information on using the Novu Agent Toolkit with the OpenAI framework. ```APIDOC ## OpenAI Adapter ```typescript import { createNovuAgentToolkit } from '@novu/agent-toolkit/openai'; const toolkit = await createNovuAgentToolkit({ secretKey: process.env.NOVU_SECRET_KEY, subscriberId: 'user-123', }); // toolkit.tools — OpenAI function tool definitions // toolkit.handleToolCall — execute a tool call and return a tool message ``` The returned `toolkit` provides: - **`tools`** — Array of OpenAI-compatible function tool definitions. - **`handleToolCall(toolCall)`** — Executes a tool call and returns a `{ role: 'tool', tool_call_id, content }` message ready to append to the conversation. ``` -------------------------------- ### Basic Editor Usage with @novu/maily-core Source: https://github.com/novuhq/novu/blob/next/libs/maily-core/readme.md Set up the Maily editor component with initial content and event handlers for creation and updates. Ensure the core styles are imported. ```tsx import '@novu/maily-core/style.css'; import { useState } from 'react'; import { Editor } from '@novu/maily-core'; import type { Editor as TiptapEditor, JSONContent } from '@tiptap/core'; type AppProps = { contentJson: JSONContent; }; function App(props: AppProps) { const { contentJson: defaultContentJson } = props; const [editor, setEditor] = useState(); return ( ); } ``` -------------------------------- ### Migration File with Comments Source: https://github.com/novuhq/novu/blob/next/apps/api/migrations/clickhouse-migrations/README.md Document migration files with comments explaining the purpose and any relevant ticket numbers for context. ```sql -- Add user timezone preference -- Ticket: NV-1234 ALTER TABLE users ADD COLUMN IF NOT EXISTS timezone String DEFAULT 'UTC'; ``` -------------------------------- ### Serving Novu Workflows with Remix Source: https://context7.com/novuhq/novu/llms.txt Integrates Novu workflows into a Remix application. Requires importing the 'serve' function from '@novu/framework/remix' and your workflow definition. ```typescript // REMIX (app/routes/api.novu.ts) import { serve } from '@novu/framework/remix'; import { myWorkflow } from '~/novu/workflows'; const handler = serve({ workflows: [myWorkflow] }); export { handler as loader, handler as action }; ```