@destinedai/voice
v0.1.5
Published
Developer-friendly & type-safe Typescript SDK specifically catered to leverage *openapi* API.
Readme
openapi
Developer-friendly & type-safe Typescript SDK specifically catered to leverage openapi API.
[!IMPORTANT] This SDK is not yet ready for production use. To complete setup please follow the steps outlined in your workspace. Delete this section before > publishing to a package manager.
Summary
Destined Voice API:
Destined Voice API
High-quality Text-to-Speech (TTS) API with diverse speaker voices and Speech-to-Text (STT) evaluation capabilities.
Features
- 2,400+ Consented Speakers: Diverse demographics including gender, age, region, and accent
- Voice Cloning: Generate speech in any speaker's voice
- Batch Processing: Generate audio for multiple speakers asynchronously
- STT Testing: Evaluate 9 STT providers (Deepgram, AssemblyAI, OpenAI, Google, Azure, Amazon, Soniox, Play.ht)
- Accuracy Metrics: WER/CER calculation with demographic bias analysis
- Dataset Import: Upload CSV files for bulk TTS generation and dialog synthesis
Authentication
All endpoints except /health, /v1/speakers, and /v1/stt/calculate-accuracy require a Bearer token.
Use Clerk for authentication - include the JWT in the Authorization header.
Authorization: Bearer <clerk_jwt_token>Pricing Tiers
| Feature | Starter | Pro | Enterprise | |---------|---------|-----|------------| | Price | $100/month | $500/month | $5,000/month | | Evals/month | 1 | Unlimited | Unlimited | | Characters (synthesis) | 1,000 | 100,000 | 1,000,000 | | Real voices | 500 | 5,000 | 10,000+ | | Custom voices | Unlimited | Unlimited | Unlimited | | Dataset download | Add-on | Add-on | Included | | Realtime listening | Add-on | Included | Included | | SOC-2/HIPAA | Add-on | Add-on | Included |
SDKs
Support
- Documentation: https://docs.destined.ai
- Email: [email protected]
Table of Contents
SDK Installation
[!TIP] To finish publishing your SDK to npm and others you must run your first generation action.
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
NPM
npm add <UNSET>PNPM
pnpm add <UNSET>Bun
bun add <UNSET>Yarn
yarn add <UNSET>[!NOTE] This package is published with CommonJS and ES Modules (ESM) support.
Requirements
For supported JavaScript runtimes, please consult RUNTIMES.md.
SDK Example Usage
Example
import { SDK } from "@destinedai/voice";
const sdk = new SDK({
httpBearer: "<YOUR_BEARER_TOKEN_HERE>",
});
async function run() {
const result = await sdk.health.healthCheckHealthGet();
console.log(result);
}
run();
Authentication
Per-Client Security Schemes
This SDK supports the following security scheme globally:
| Name | Type | Scheme |
| ------------ | ---- | ----------- |
| httpBearer | http | HTTP Bearer |
To authenticate with the API the httpBearer parameter must be set when initializing the SDK client instance. For example:
import { SDK } from "@destinedai/voice";
const sdk = new SDK({
httpBearer: "<YOUR_BEARER_TOKEN_HERE>",
});
async function run() {
const result = await sdk.health.healthCheckHealthGet();
console.log(result);
}
run();
Available Resources and Operations
Billing
- createPortalSessionV1BillingCreatePortalSessionPost - Create Stripe customer portal session
- getAvailableTiersV1BillingTiersGet - Get available subscription tiers
- createCheckoutSessionV1BillingCreateCheckoutSessionPost - Create Stripe checkout session
CustomVoiceTTS
- getCustomVoiceEmotionsV1TtsCustomVoiceEmotionsGet - List supported emotion tags
- generateCustomVoiceTtsV1TtsCustomVoiceGeneratePost - Generate TTS with custom voice design
Datasets
- listDatasetsV1DatasetsGet - List user's datasets
- uploadDatasetV1DatasetsPost - Upload CSV dataset
- getUploadUrlV1DatasetsUploadUrlPost - Get presigned URL for large CSV upload
- validateDatasetV1DatasetsDatasetIdValidatePost - Validate and parse uploaded dataset
- getDatasetV1DatasetsDatasetIdGet - Get dataset details
- deleteDatasetV1DatasetsDatasetIdDelete - Delete dataset
- assignSpeakersV1DatasetsDatasetIdAssignSpeakersPost - Assign speakers to dataset roles
- previewScriptV1DatasetsDatasetIdScriptsScriptIdGet - Preview dialog script
- generateFromDatasetV1DatasetsDatasetIdGeneratePost - Generate TTS from dataset
- generateSingleDialogV1DatasetsDatasetIdGenerateDialogPost - Generate single dialog (quick test)
- getDatasetJobStatusV1DatasetsJobsJobIdGet - Get dataset job status
- getDatasetJobResultsV1DatasetsJobsJobIdResultsGet - Get dataset job results
Demo
- getDemoVoicesV1DemoVoicesGet - Get available demo voices
- getRealVoicesV1DemoRealVoicesGet - Get real speaker voices
- getRealVoiceSampleV1DemoRealVoiceSpeakerUidSampleGet - Get real voice sample audio URL
- streamRealVoiceSampleV1DemoRealVoiceSpeakerUidAudioGet - Redirect to real voice sample audio
- checkRateLimitStatusV1DemoRateLimitGet - Check demo rate limit status
- generateDemoTtsV1DemoTtsPost - Generate demo TTS audio (custom voice)
- streamDemoTtsV1DemoTtsStreamPost - Stream demo TTS audio (custom voice)
- submitDemoFeedbackV1DemoFeedbackPost - Submit feedback on demo TTS generation
Dialogs
- listDialogsV1DialogsGet - List dialog sessions
- createDialogV1DialogsPost - Create real-time dialog session
- createDialogFromDatasetV1DialogsFromDatasetPost - Create dialog from dataset script
- getDialogStatusV1DialogsDialogIdGet - Get dialog session status
- cancelDialogV1DialogsDialogIdDelete - Cancel dialog session
Environments
- listEnvironmentsV1EnvironmentsGet - List environments
- createEnvironmentV1EnvironmentsPost - Create environment
- resetEnvironmentV1EnvironmentsEnvironmentIdResetPost - Reset environment
- stepEnvironmentV1EnvironmentsEnvironmentIdStepPost - Take a step
- closeEnvironmentV1EnvironmentsEnvironmentIdClosePost - Close environment
- getEnvironmentV1EnvironmentsEnvironmentIdGet - Get environment
- getCurrentEpisodeV1EnvironmentsEnvironmentIdEpisodeGet - Get current episode
- getEpisodeV1EpisodesEpisodeIdGet - Get episode
- closeEnvironmentsBatchV1EnvironmentsBatchClosePost - Close multiple environments
- quickStartEnvironmentV1EnvironmentsQuickStartPost - Quick start environment
Evaluations
- listEvaluationsV1EvaluationsGet - List evaluations
- createEvaluationV1EvaluationsPost - Create evaluation run
- getEvaluationV1EvaluationsEvaluationIdGet - Get evaluation
- deleteEvaluationV1EvaluationsEvaluationIdDelete - Delete evaluation
- getEvaluationResultsV1EvaluationsEvaluationIdResultsGet - Get evaluation results
- getEvaluationRewardsV1EvaluationsEvaluationIdRewardsGet - Get episode rewards
- getEvaluationBiasV1EvaluationsEvaluationIdBiasGet - Get bias analysis
- cancelEvaluationV1EvaluationsEvaluationIdCancelPost - Cancel evaluation
- compareEvaluationsV1EvaluationsComparePost - Compare evaluations
- getEpisodeRewardV1EpisodesEpisodeIdRewardGet - Get episode reward
Health
- healthCheckHealthGet - Health Check
- rootGet - Root
InternalSpeakers
- getSpeakerManifestInternalSpeakersUidManifestGet - Get Speaker Manifest
- getReferenceClipsInternalSpeakersUidReferenceClipsGet - Get Reference Clips
Jobs
- getJobStatusV1JobsJobIdGet - Get job status
- listUserJobsV1JobsGet - List user jobs
- cancelJobV1JobsJobIdCancelPost - Cancel job
Scenarios
- listScenariosV1ScenariosGet - List scenarios
- createScenarioV1ScenariosPost - Create scenario
- createModerationScenarioV1ScenariosModerationPost - Create moderation scenario
- getScenarioV1ScenariosScenarioIdGet - Get scenario
- deleteScenarioV1ScenariosScenarioIdDelete - Delete scenario
- updateScenarioV1ScenariosScenarioIdPatch - Update scenario
- getScenarioVersionsV1ScenariosScenarioIdVersionsGet - Get scenario versions
- listSystemScenariosV1ScenariosSystemListGet - List system scenarios
- cloneScenarioV1ScenariosScenarioIdClonePost - Clone scenario
Speakers
- listSpeakersV1SpeakersGet - List Speakers
- getSpeakerV1SpeakersUidGet - Get Speaker
- getFilterOptionsV1SpeakersFiltersOptionsGet - Get Filter Options
STTTesting
- listSttProvidersV1SttProvidersGet - List available STT providers
- testSingleSttV1SttTestPost - Test single audio with STT provider
- createBatchSttTestV1SttTestBatchPost - Create batch STT test job
- listSttJobsV1SttJobsGet - List STT jobs
- getSttJobStatusV1SttJobsJobIdGet - Get STT job status
- getSttJobResultsV1SttJobsJobIdResultsGet - Get STT job results
- getSttBiasAnalysisV1SttJobsJobIdBiasGet - Get bias analysis for STT job
- compareSttProvidersV1SttJobsJobIdCompareGet - Compare STT providers
- calculateTextAccuracyV1SttCalculateAccuracyPost - Calculate WER/CER between two texts
TTSGeneration
- generateSingleTtsV1TtsGeneratePost - Generate TTS audio (single voice)
- generateBatchTtsV1TtsGenerateBatchPost - Generate TTS audio (batch)
- getCustomVoiceEmotionsV1TtsCustomVoiceEmotionsGet - List supported emotion tags
- generateCustomVoiceTtsV1TtsCustomVoiceGeneratePost - Generate TTS with custom voice design
Users
- getCurrentUserInfoV1UsersMeGet - Get current user
- getUserUsageStatsV1UsersMeUsageGet - Get user usage statistics
Webhooks
- clerkWebhookV1WebhooksClerkPost - Clerk webhook handler
- stripeWebhookV1WebhooksStripePost - Stripe webhook handler
Workers
- processBatchWebhookApiV1WorkersProcessBatchPost - QStash webhook for batch TTS processing
- triggerBatchManuallyApiV1WorkersTriggerBatchJobIdPost - Manually trigger batch processing (testing only)
- processSttBatchWebhookApiV1WorkersProcessSttBatchPost - QStash webhook for batch STT processing
- triggerSttBatchManuallyApiV1WorkersTriggerSttBatchJobIdPost - Manually trigger STT batch processing (testing only)
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.
billingCreateCheckoutSessionV1BillingCreateCheckoutSessionPost- Create Stripe checkout sessionbillingCreatePortalSessionV1BillingCreatePortalSessionPost- Create Stripe customer portal sessionbillingGetAvailableTiersV1BillingTiersGet- Get available subscription tiersdatasetsAssignSpeakersV1DatasetsDatasetIdAssignSpeakersPost- Assign speakers to dataset rolesdatasetsDeleteDatasetV1DatasetsDatasetIdDelete- Delete datasetdatasetsGenerateFromDatasetV1DatasetsDatasetIdGeneratePost- Generate TTS from datasetdatasetsGenerateSingleDialogV1DatasetsDatasetIdGenerateDialogPost- Generate single dialog (quick test)datasetsGetDatasetJobResultsV1DatasetsJobsJobIdResultsGet- Get dataset job resultsdatasetsGetDatasetJobStatusV1DatasetsJobsJobIdGet- Get dataset job statusdatasetsGetDatasetV1DatasetsDatasetIdGet- Get dataset detailsdatasetsGetUploadUrlV1DatasetsUploadUrlPost- Get presigned URL for large CSV uploaddatasetsListDatasetsV1DatasetsGet- List user's datasetsdatasetsPreviewScriptV1DatasetsDatasetIdScriptsScriptIdGet- Preview dialog scriptdatasetsUploadDatasetV1DatasetsPost- Upload CSV datasetdatasetsValidateDatasetV1DatasetsDatasetIdValidatePost- Validate and parse uploaded datasetdemoCheckRateLimitStatusV1DemoRateLimitGet- Check demo rate limit statusdemoGenerateDemoTtsV1DemoTtsPost- Generate demo TTS audio (custom voice)demoGetDemoVoicesV1DemoVoicesGet- Get available demo voicesdemoGetRealVoiceSampleV1DemoRealVoiceSpeakerUidSampleGet- Get real voice sample audio URLdemoGetRealVoicesV1DemoRealVoicesGet- Get real speaker voicesdemoStreamDemoTtsV1DemoTtsStreamPost- Stream demo TTS audio (custom voice)demoStreamRealVoiceSampleV1DemoRealVoiceSpeakerUidAudioGet- Redirect to real voice sample audiodemoSubmitDemoFeedbackV1DemoFeedbackPost- Submit feedback on demo TTS generationdialogsCancelDialogV1DialogsDialogIdDelete- Cancel dialog sessiondialogsCreateDialogFromDatasetV1DialogsFromDatasetPost- Create dialog from dataset scriptdialogsCreateDialogV1DialogsPost- Create real-time dialog sessiondialogsGetDialogStatusV1DialogsDialogIdGet- Get dialog session statusdialogsListDialogsV1DialogsGet- List dialog sessionsenvironmentsCloseEnvironmentsBatchV1EnvironmentsBatchClosePost- Close multiple environmentsenvironmentsCloseEnvironmentV1EnvironmentsEnvironmentIdClosePost- Close environmentenvironmentsCreateEnvironmentV1EnvironmentsPost- Create environmentenvironmentsGetCurrentEpisodeV1EnvironmentsEnvironmentIdEpisodeGet- Get current episodeenvironmentsGetEnvironmentV1EnvironmentsEnvironmentIdGet- Get environmentenvironmentsGetEpisodeV1EpisodesEpisodeIdGet- Get episodeenvironmentsListEnvironmentsV1EnvironmentsGet- List environmentsenvironmentsQuickStartEnvironmentV1EnvironmentsQuickStartPost- Quick start environmentenvironmentsResetEnvironmentV1EnvironmentsEnvironmentIdResetPost- Reset environmentenvironmentsStepEnvironmentV1EnvironmentsEnvironmentIdStepPost- Take a stepevaluationsCancelEvaluationV1EvaluationsEvaluationIdCancelPost- Cancel evaluationevaluationsCompareEvaluationsV1EvaluationsComparePost- Compare evaluationsevaluationsCreateEvaluationV1EvaluationsPost- Create evaluation runevaluationsDeleteEvaluationV1EvaluationsEvaluationIdDelete- Delete evaluationevaluationsGetEpisodeRewardV1EpisodesEpisodeIdRewardGet- Get episode rewardevaluationsGetEvaluationBiasV1EvaluationsEvaluationIdBiasGet- Get bias analysisevaluationsGetEvaluationResultsV1EvaluationsEvaluationIdResultsGet- Get evaluation resultsevaluationsGetEvaluationRewardsV1EvaluationsEvaluationIdRewardsGet- Get episode rewardsevaluationsGetEvaluationV1EvaluationsEvaluationIdGet- Get evaluationevaluationsListEvaluationsV1EvaluationsGet- List evaluationshealthHealthCheckHealthGet- Health CheckhealthRootGet- RootinternalSpeakersGetReferenceClipsInternalSpeakersUidReferenceClipsGet- Get Reference ClipsinternalSpeakersGetSpeakerManifestInternalSpeakersUidManifestGet- Get Speaker ManifestjobsCancelJobV1JobsJobIdCancelPost- Cancel jobjobsGetJobStatusV1JobsJobIdGet- Get job statusjobsListUserJobsV1JobsGet- List user jobsscenariosCloneScenarioV1ScenariosScenarioIdClonePost- Clone scenarioscenariosCreateModerationScenarioV1ScenariosModerationPost- Create moderation scenarioscenariosCreateScenarioV1ScenariosPost- Create scenarioscenariosDeleteScenarioV1ScenariosScenarioIdDelete- Delete scenarioscenariosGetScenarioV1ScenariosScenarioIdGet- Get scenarioscenariosGetScenarioVersionsV1ScenariosScenarioIdVersionsGet- Get scenario versionsscenariosListScenariosV1ScenariosGet- List scenariosscenariosListSystemScenariosV1ScenariosSystemListGet- List system scenariosscenariosUpdateScenarioV1ScenariosScenarioIdPatch- Update scenariospeakersGetFilterOptionsV1SpeakersFiltersOptionsGet- Get Filter OptionsspeakersGetSpeakerV1SpeakersUidGet- Get SpeakerspeakersListSpeakersV1SpeakersGet- List SpeakerssttTestingCalculateTextAccuracyV1STTCalculateAccuracyPost- Calculate WER/CER between two textssttTestingCompareSTTProvidersV1STTJobsJobIdCompareGet- Compare STT providerssttTestingCreateBatchSTTTestV1STTTestBatchPost- Create batch STT test jobsttTestingGetSTTBiasAnalysisV1STTJobsJobIdBiasGet- Get bias analysis for STT jobsttTestingGetSTTJobResultsV1STTJobsJobIdResultsGet- Get STT job resultssttTestingGetSTTJobStatusV1STTJobsJobIdGet- Get STT job statussttTestingListSTTJobsV1STTJobsGet- List STT jobssttTestingListSTTProvidersV1STTProvidersGet- List available STT providerssttTestingTestSingleSTTV1STTTestPost- Test single audio with STT providerttsGenerationGenerateBatchTTSV1TTSGenerateBatchPost- Generate TTS audio (batch)ttsGenerationGenerateCustomVoiceTTSV1TTSCustomVoiceGeneratePost- Generate TTS with custom voice designttsGenerationGenerateCustomVoiceTTSV1TTSCustomVoiceGeneratePost- Generate TTS with custom voice designttsGenerationGenerateSingleTTSV1TTSGeneratePost- Generate TTS audio (single voice)ttsGenerationGetCustomVoiceEmotionsV1TTSCustomVoiceEmotionsGet- List supported emotion tagsttsGenerationGetCustomVoiceEmotionsV1TTSCustomVoiceEmotionsGet- List supported emotion tagsusersGetCurrentUserInfoV1UsersMeGet- Get current userusersGetUserUsageStatsV1UsersMeUsageGet- Get user usage statisticswebhooksClerkWebhookV1WebhooksClerkPost- Clerk webhook handlerwebhooksStripeWebhookV1WebhooksStripePost- Stripe webhook handlerworkersProcessBatchWebhookApiV1WorkersProcessBatchPost- QStash webhook for batch TTS processingworkersProcessSttBatchWebhookApiV1WorkersProcessSttBatchPost- QStash webhook for batch STT processingworkersTriggerBatchManuallyApiV1WorkersTriggerBatchJobIdPost- Manually trigger batch processing (testing only)workersTriggerSttBatchManuallyApiV1WorkersTriggerSttBatchJobIdPost- Manually trigger STT batch processing (testing only)
File uploads
Certain SDK methods accept files as part of a multi-part request. It is possible and typically recommended to upload files as a stream rather than reading the entire contents into memory. This avoids excessive memory consumption and potentially crashing with out-of-memory errors when working with very large files. The following example demonstrates how to attach a file stream to a request.
[!TIP]
Depending on your JavaScript runtime, there are convenient utilities that return a handle to a file without reading the entire contents into memory:
- Node.js v20+: Since v20, Node.js comes with a native
openAsBlobfunction innode:fs.- Bun: The native
Bun.filefunction produces a file handle that can be used for streaming file uploads.- Browsers: All supported browsers return an instance to a
Filewhen reading the value from an<input type="file">element.- Node.js v18: A file stream can be created using the
fileFromhelper fromfetch-blob/from.js.
import { SDK } from "@destinedai/voice";
import { openAsBlob } from "node:fs";
const sdk = new SDK({
httpBearer: "<YOUR_BEARER_TOKEN_HERE>",
});
async function run() {
const result = await sdk.datasets.uploadDatasetV1DatasetsPost({
file: await openAsBlob("example.file"),
name: "<value>",
});
console.log(result);
}
run();
Retries
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
import { SDK } from "@destinedai/voice";
const sdk = new SDK({
httpBearer: "<YOUR_BEARER_TOKEN_HERE>",
});
async function run() {
const result = await sdk.health.healthCheckHealthGet({
retries: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
console.log(result);
}
run();
If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
import { SDK } from "@destinedai/voice";
const sdk = new SDK({
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
httpBearer: "<YOUR_BEARER_TOKEN_HERE>",
});
async function run() {
const result = await sdk.health.healthCheckHealthGet();
console.log(result);
}
run();
Error Handling
SDKError is the base class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
| ------------------- | ---------- | --------------------------------------------------------------------------------------- |
| error.message | string | Error message |
| error.statusCode | number | HTTP response status code eg 404 |
| error.headers | Headers | HTTP response headers |
| error.body | string | HTTP body. Can be empty string if no body is returned. |
| error.rawResponse | Response | Raw HTTP response |
| error.data$ | | Optional. Some errors may contain structured data. See Error Classes. |
Example
import { SDK } from "@destinedai/voice";
import * as errors from "@destinedai/voice/models/errors";
const sdk = new SDK({
httpBearer: "<YOUR_BEARER_TOKEN_HERE>",
});
async function run() {
try {
const result = await sdk.speakers.listSpeakersV1SpeakersGet({});
console.log(result);
} catch (error) {
// The base class for HTTP error responses
if (error instanceof errors.SDKError) {
console.log(error.message);
console.log(error.statusCode);
console.log(error.body);
console.log(error.headers);
// Depending on the method different errors may be thrown
if (error instanceof errors.HTTPValidationError) {
console.log(error.data$.detail); // ValidationError[]
}
}
}
}
run();
Error Classes
Primary errors:
SDKError: The base class for HTTP error responses.HTTPValidationError: Validation Error. Status code422. *
Network errors:
ConnectionError: HTTP client was unable to make a request to a server.RequestTimeoutError: HTTP request timed out due to an AbortSignal signal.RequestAbortedError: HTTP request was aborted by the client.InvalidRequestError: Any input used to create a request is invalid.UnexpectedClientError: Unrecognised or unexpected error.
Inherit from SDKError:
ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. Seeerror.rawValuefor the raw value anderror.pretty()for a nicely formatted multi-line string.
* Check the method documentation to see if the error is applicable.
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 | Description |
| --- | ------------------------- | ----------------- |
| 0 | https://api.destined.ai | Production |
| 1 | http://localhost:8000 | Local Development |
Example
import { SDK } from "@destinedai/voice";
const sdk = new SDK({
serverIdx: 0,
httpBearer: "<YOUR_BEARER_TOKEN_HERE>",
});
async function run() {
const result = await sdk.health.healthCheckHealthGet();
console.log(result);
}
run();
Override Server URL Per-Client
The default server can also be overridden globally by passing a URL to the serverURL: string optional parameter when initializing the SDK client instance. For example:
import { SDK } from "@destinedai/voice";
const sdk = new SDK({
serverURL: "http://localhost:8000",
httpBearer: "<YOUR_BEARER_TOKEN_HERE>",
});
async function run() {
const result = await sdk.health.healthCheckHealthGet();
console.log(result);
}
run();
Custom HTTP Client
The TypeScript SDK makes API calls using an HTTPClient that wraps the native
Fetch API. This
client is a thin wrapper around fetch and provides the ability to attach hooks
around the request lifecycle that can be used to modify the request or handle
errors and response.
The HTTPClient constructor takes an optional fetcher argument that can be
used to integrate a third-party HTTP client or when writing tests to mock out
the HTTP client and feed in fixtures.
The following example shows how to use the "beforeRequest" hook to to add a
custom header and a timeout to requests and how to use the "requestError" hook
to log errors:
import { SDK } from "@destinedai/voice";
import { HTTPClient } from "@destinedai/voice/lib/http";
const httpClient = new HTTPClient({
// fetcher takes a function that has the same signature as native `fetch`.
fetcher: (request) => {
return fetch(request);
}
});
httpClient.addHook("beforeRequest", (request) => {
const nextRequest = new Request(request, {
signal: request.signal || AbortSignal.timeout(5000)
});
nextRequest.headers.set("x-custom-header", "custom value");
return nextRequest;
});
httpClient.addHook("requestError", (error, request) => {
console.group("Request Error");
console.log("Reason:", `${error}`);
console.log("Endpoint:", `${request.method} ${request.url}`);
console.groupEnd();
});
const sdk = new SDK({ httpClient: httpClient });Debugging
You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass a logger that matches console's interface as an SDK option.
[!WARNING] Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.
import { SDK } from "@destinedai/voice";
const sdk = new SDK({ debugLogger: console });Development
Maturity
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
Contributions
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.
