AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(deepgram): transcribe, analyze text and generate speech from flows and AI agents (#16384)
Odai Ahmadd334cf1b9ce6
diff --git a/bun.lock b/bun.lockindex 3f7415b8d8b..7eaeab1283e 100644--- a/bun.lock+++ b/bun.lock@@ -2509,17 +2509,19 @@},"packages/pieces/community/deepgram": {"name": "@activepieces/piece-deepgram",- "version": "0.2.0",+ "version": "0.3.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*","@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*","mime-types": "2.1.35",+ "undici": "7.29.1",},"devDependencies": {"@types/mime-types": "2.1.1","tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/deepl": {diff --git a/packages/pieces/community/deepgram/package.json b/packages/pieces/community/deepgram/package.jsonindex 91042cb7831..2016a3d486b 100644--- a/packages/pieces/community/deepgram/package.json+++ b/packages/pieces/community/deepgram/package.json@@ -1,22 +1,25 @@{"name": "@activepieces/piece-deepgram",- "version": "0.2.0",+ "version": "0.3.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"},"dependencies": {"@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*","mime-types": "2.1.35","@activepieces/core-piece-types": "workspace:*",- "@activepieces/core-utils": "workspace:*"+ "@activepieces/core-utils": "workspace:*",+ "undici": "7.29.1"},"devDependencies": {"@types/mime-types": "2.1.1",- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/deepgram/src/actions/ai/generate-speech.ts b/packages/pieces/community/deepgram/src/actions/ai/generate-speech.tsnew file mode 100644index 00000000000..1e770c71d15--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/ai/generate-speech.ts@@ -0,0 +1,75 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../../common/auth';+import { DEFAULT_AI_VOICE, TTS_ENCODING_OPTIONS } from '../../common/constants';+import { deepgramSpeech } from '../../common/speech';+import { generateSpeechOutputSchema } from '../../output-schemas';++const VOICE_PATTERN = /^aura(-2)?-[a-z]+-[a-z]{2}$/;++export const generateSpeechAction = createAction({+ auth: deepgramAuth,+ name: 'deepgram_generate_speech',+ classification: 'READ',+ displayName: 'Generate Speech',+ description: 'Converts text to an audio file with a Deepgram Aura voice ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Converts up to 2,000 characters of text to speech with a Deepgram Aura voice ID (default aura-2-thalia-en; Aura-2 voices exist for en, es, de, fr, nl, it and ja) and returns an audio file. Get voice IDs from deepgram_list_models with type tts. Each call is billed per character, so retries are billed again.',+ idempotent: false,+ },+ outputSchema: generateSpeechOutputSchema,+ props: {+ text: Property.LongText({+ displayName: 'Text',+ description: 'The text to speak, up to 2,000 characters.',+ required: true,+ }),+ voice: Property.ShortText({+ displayName: 'Voice ID',+ description: `A Deepgram voice ID such as ${DEFAULT_AI_VOICE} or aura-2-celeste-es. Leave empty for ${DEFAULT_AI_VOICE}.`,+ required: false,+ }),+ encoding: Property.StaticDropdown({+ displayName: 'Audio Format',+ required: false,+ defaultValue: 'mp3',+ options: { disabled: false, options: TTS_ENCODING_OPTIONS },+ }),+ speed: Property.Number({+ displayName: 'Speed',+ description:+ 'Speaking rate from 0.5 to 1.5 (1 is normal). Not supported by every voice.',+ required: false,+ }),+ },+ async run(context) {+ const voice =+ (context.propsValue.voice ?? '').trim().toLowerCase() || DEFAULT_AI_VOICE;+ if (!VOICE_PATTERN.test(voice)) {+ throw new Error(+ `"${voice}" is not a Deepgram voice ID. Use an ID like ${DEFAULT_AI_VOICE}; deepgram_list_models (type tts) lists them all.`+ );+ }+ const encoding = context.propsValue.encoding ?? undefined;+ if (+ encoding &&+ !TTS_ENCODING_OPTIONS.some((option) => option.value === encoding)+ ) {+ throw new Error(+ `Unknown audio format "${encoding}". Use one of ${TTS_ENCODING_OPTIONS.map(+ (option) => option.value+ ).join(', ')}.`+ );+ }+ return deepgramSpeech.synthesize({+ apiKey: context.auth.secret_text,+ text: context.propsValue.text,+ model: voice,+ encoding,+ speed: context.propsValue.speed,+ writeFile: ({ fileName, data }) =>+ context.files.write({ fileName, data }),+ });+ },+});diff --git a/packages/pieces/community/deepgram/src/actions/ai/get-balance.ts b/packages/pieces/community/deepgram/src/actions/ai/get-balance.tsnew file mode 100644index 00000000000..ad7fa71ffde--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/ai/get-balance.ts@@ -0,0 +1,56 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../../common/auth';+import { balanceOutputSchema } from '../../output-schemas';+import { DEEPGRAM_TIMEOUTS, deepgramClient } from '../../common/client';+import { deepgramProjects } from '../../common/projects';+import { deepgramProps } from '../../common/props';+import { BalanceRow, flattenBalance } from '../get-balances';++export const getBalanceAction = createAction({+ auth: deepgramAuth,+ name: 'deepgram_get_balance',+ classification: 'READ',+ displayName: 'Get Credit Balance by ID',+ description: 'Gets one prepaid credit balance of a Deepgram project by ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns one prepaid credit balance of a Deepgram project by its balance ID, with amount and units. Get the ID from deepgram_list_balances, which already returns every balance. Needs an admin or owner key. Read-only.',+ idempotent: true,+ },+ outputSchema: balanceOutputSchema,+ props: {+ project_id: deepgramProps.projectId(),+ balance_id: Property.ShortText({+ displayName: 'Balance ID',+ description: 'The balance ID from deepgram_list_balances.',+ required: true,+ }),+ },+ async run(context) {+ const apiKey = context.auth.secret_text;+ const balanceId = (context.propsValue.balance_id ?? '').trim();+ if (balanceId.length === 0) {+ throw new Error('Enter a balance ID.');+ }+ const projectId = await deepgramProjects.resolveProjectId({+ apiKey,+ project: context.propsValue.project_id,+ });+ const response = await deepgramClient.request<BalanceRow>({+ apiKey,+ method: HttpMethod.GET,+ path: deepgramProjects.projectPath({+ projectId,+ rest: ['balances', balanceId],+ }),+ timeoutMs: DEEPGRAM_TIMEOUTS.manage,+ operation: 'get the credit balance',+ });+ return flattenBalance({+ ...(response.body ?? {}),+ balance_id: response.body?.balance_id ?? balanceId,+ });+ },+});diff --git a/packages/pieces/community/deepgram/src/actions/ai/get-billing-breakdown.ts b/packages/pieces/community/deepgram/src/actions/ai/get-billing-breakdown.tsnew file mode 100644index 00000000000..ee393627bc6--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/ai/get-billing-breakdown.ts@@ -0,0 +1,37 @@+import { createAction } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../../common/auth';+import { deepgramProps } from '../../common/props';+import { billingOutputSchema } from '../../output-schemas';+import {+ getBillingBreakdown,+ getBillingBreakdownAction,+} from '../get-billing-breakdown';++const { project: _project, ...originalProps } = getBillingBreakdownAction.props;++export const getBillingBreakdownAiAction = createAction({+ auth: deepgramAuth,+ name: 'deepgram_get_billing_breakdown',+ classification: 'READ',+ displayName: 'Get Cost Breakdown (Agent)',+ description:+ 'Gets what a Deepgram project spent in dollars for a date range, optionally grouped.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the dollar cost of a Deepgram project for a date range, split per day or grouped by line item (for example streaming::nova-3), API key, deployment or tag, plus the total. Valid line items, keys and tags come from deepgram_list_billing_fields; use deepgram_get_usage_breakdown for hours and requests. Needs an admin or owner key. Read-only.',+ idempotent: true,+ },+ outputSchema: billingOutputSchema,+ props: {+ project_id: deepgramProps.projectId(),+ ...originalProps,+ },+ async run(context) {+ const { project_id, ...input } = context.propsValue;+ return getBillingBreakdown({+ apiKey: context.auth.secret_text,+ input: { ...input, project: project_id ?? undefined },+ });+ },+});diff --git a/packages/pieces/community/deepgram/src/actions/ai/get-model.ts b/packages/pieces/community/deepgram/src/actions/ai/get-model.tsnew file mode 100644index 00000000000..ece37ffad34--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/ai/get-model.ts@@ -0,0 +1,44 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../../common/auth';+import { modelOutputSchema } from '../../output-schemas';+import { deepgramModels } from '../../common/models';++export const getModelAction = createAction({+ auth: deepgramAuth,+ name: 'deepgram_get_model',+ classification: 'READ',+ displayName: 'Get Model',+ description: 'Gets one Deepgram model build by its UUID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns one Deepgram speech-to-text model or text-to-speech voice build by its UUID: canonical name, architecture, languages, version, batch/streaming support and voice traits. Get the UUID from deepgram_list_models with One Row per Build on; a canonical name such as nova-3-general is not accepted. Empty project ID reads the public catalog. Read-only.',+ idempotent: true,+ },+ outputSchema: modelOutputSchema,+ props: {+ model_id: Property.ShortText({+ displayName: 'Model UUID',+ description:+ 'The build UUID from deepgram_list_models with One Row per Build on.',+ required: true,+ }),+ project_id: Property.ShortText({+ displayName: 'Project ID',+ description:+ 'A project ID from List Projects (list_projects) to read a custom model of that project. Leave empty for the public catalog.',+ required: false,+ }),+ },+ async run(context) {+ const modelId = (context.propsValue.model_id ?? '').trim();+ if (modelId.length === 0) {+ throw new Error('Enter a model UUID.');+ }+ return deepgramModels.getModel({+ apiKey: context.auth.secret_text,+ projectId: context.propsValue.project_id?.trim() || undefined,+ modelId,+ });+ },+});diff --git a/packages/pieces/community/deepgram/src/actions/ai/get-request.ts b/packages/pieces/community/deepgram/src/actions/ai/get-request.tsnew file mode 100644index 00000000000..9623bd93fc3--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/ai/get-request.ts@@ -0,0 +1,34 @@+import { createAction } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../../common/auth';+import { deepgramProps } from '../../common/props';+import { requestOutputSchema } from '../../output-schemas';+import { getRequest, getRequestAction } from '../get-request';++const { project: _project, ...originalProps } = getRequestAction.props;++export const getRequestAiAction = createAction({+ auth: deepgramAuth,+ name: 'deepgram_get_request',+ classification: 'READ',+ displayName: 'Get Request (Agent)',+ description:+ 'Gets one past Deepgram request by ID with its status, duration and cost.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns one past Deepgram API request by its request ID with status code, completion time, audio duration, cost in USD and callback delivery status. Get the ID from deepgram_list_requests or from the request_id that deepgram_transcribe_audio returns. Read-only.',+ idempotent: true,+ },+ outputSchema: requestOutputSchema,+ props: {+ project_id: deepgramProps.projectId(),+ ...originalProps,+ },+ async run(context) {+ const { project_id, ...input } = context.propsValue;+ return getRequest({+ apiKey: context.auth.secret_text,+ input: { ...input, project: project_id ?? undefined },+ });+ },+});diff --git a/packages/pieces/community/deepgram/src/actions/ai/get-usage-breakdown.ts b/packages/pieces/community/deepgram/src/actions/ai/get-usage-breakdown.tsnew file mode 100644index 00000000000..3861b76f26c--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/ai/get-usage-breakdown.ts@@ -0,0 +1,34 @@+import { createAction } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../../common/auth';+import { deepgramProps } from '../../common/props';+import { usageOutputSchema } from '../../output-schemas';+import { getUsageBreakdown, getUsageAction } from '../get-usage';++const { project: _project, ...originalProps } = getUsageAction.props;++export const getUsageBreakdownAiAction = createAction({+ auth: deepgramAuth,+ name: 'deepgram_get_usage_breakdown',+ classification: 'READ',+ displayName: 'Get Usage Breakdown (Agent)',+ description:+ 'Gets audio hours, requests, characters and tokens used by a Deepgram project, optionally grouped.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns usage totals of a Deepgram project for a date range (audio hours, requests, text-to-speech characters, tokens), split per day or grouped by endpoint, model, method, tag, key, feature set or deployment. Valid tag values come from deepgram_list_usage_fields. Use deepgram_get_billing_breakdown for dollars. Read-only.',+ idempotent: true,+ },+ outputSchema: usageOutputSchema,+ props: {+ project_id: deepgramProps.projectId(),+ ...originalProps,+ },+ async run(context) {+ const { project_id, ...input } = context.propsValue;+ return getUsageBreakdown({+ apiKey: context.auth.secret_text,+ input: { ...input, project: project_id ?? undefined },+ });+ },+});diff --git a/packages/pieces/community/deepgram/src/actions/ai/get-usage-summary.ts b/packages/pieces/community/deepgram/src/actions/ai/get-usage-summary.tsnew file mode 100644index 00000000000..332b11c47a2--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/ai/get-usage-summary.ts@@ -0,0 +1,121 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../../common/auth';+import { usageSummaryOutputSchema } from '../../output-schemas';+import { DEEPGRAM_TIMEOUTS, deepgramClient } from '../../common/client';+import { deepgramProjects } from '../../common/projects';+import { deepgramProps } from '../../common/props';+import { deepgramReports, UsageSummaryResponse } from '../../common/reports';++export const getUsageSummaryAction = createAction({+ auth: deepgramAuth,+ name: 'deepgram_get_usage_summary',+ classification: 'READ',+ displayName: 'Get Usage Summary',+ description:+ 'Gets the usage summary of a Deepgram project for a date range, with optional filters.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the usage summary of a Deepgram project for a date range (YYYY-MM-DD), filterable by API key, tag, model build UUID, endpoint, method and deployment. Valid tag and model values come from deepgram_list_usage_fields; a model name such as nova-3 does not match. Returns per-day totals of audio hours, requests, text-to-speech characters and tokens plus overall totals; use deepgram_get_usage_breakdown to group by endpoint, model, tag or key. Read-only.',+ idempotent: true,+ },+ outputSchema: usageSummaryOutputSchema,+ props: {+ project_id: deepgramProps.projectId(),+ start: Property.DateTime({+ displayName: 'Start Date',+ description: 'First day to include. Deepgram defaults to 30 days ago.',+ required: false,+ }),+ end: Property.DateTime({+ displayName: 'End Date',+ description: 'Last day to include. Deepgram defaults to today.',+ required: false,+ }),+ accessor: Property.ShortText({+ displayName: 'API Key ID',+ description: 'Only count requests made with this API key ID.',+ required: false,+ }),+ tag: Property.ShortText({+ displayName: 'Tag',+ description:+ 'Only count requests with this tag, from deepgram_list_usage_fields.',+ required: false,+ }),+ model: Property.ShortText({+ displayName: 'Model UUID',+ description:+ 'Only count requests to this model build, using a model_id from deepgram_list_usage_fields.',+ required: false,+ }),+ endpoint: Property.StaticDropdown({+ displayName: 'Endpoint',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Speech to text (listen)', value: 'listen' },+ { label: 'Text intelligence (read)', value: 'read' },+ { label: 'Text to speech (speak)', value: 'speak' },+ { label: 'Voice agent (agent)', value: 'agent' },+ ],+ },+ }),+ method: Property.StaticDropdown({+ displayName: 'Method',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Synchronous', value: 'sync' },+ { label: 'Callback (async)', value: 'async' },+ { label: 'Streaming', value: 'streaming' },+ ],+ },+ }),+ deployment: Property.StaticDropdown({+ displayName: 'Deployment',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Hosted', value: 'hosted' },+ { label: 'Beta', value: 'beta' },+ { label: 'Self-hosted', value: 'self-hosted' },+ ],+ },+ }),+ },+ async run(context) {+ const apiKey = context.auth.secret_text;+ const props = context.propsValue;+ const start = deepgramReports.toDay(props.start);+ const end = deepgramReports.toDay(props.end);+ deepgramReports.checkRange({ start, end });+ const projectId = await deepgramProjects.resolveProjectId({+ apiKey,+ project: props.project_id,+ });+ const tag = props.tag?.trim();+ const response = await deepgramClient.request<UsageSummaryResponse>({+ apiKey,+ method: HttpMethod.GET,+ path: deepgramProjects.projectPath({ projectId, rest: ['usage'] }),+ query: {+ start,+ end,+ accessor: props.accessor?.trim() || undefined,+ tag: tag ? deepgramReports.stripTagPrefix(tag) : undefined,+ model: props.model?.trim() || undefined,+ endpoint: props.endpoint ?? undefined,+ method: props.method ?? undefined,+ deployment: props.deployment ?? undefined,+ },+ timeoutMs: DEEPGRAM_TIMEOUTS.manage,+ operation: 'get the usage summary',+ });+ return deepgramReports.flattenUsageSummary(response.body ?? {});+ },+});diff --git a/packages/pieces/community/deepgram/src/actions/ai/list-balances.ts b/packages/pieces/community/deepgram/src/actions/ai/list-balances.tsnew file mode 100644index 00000000000..c717ac1ac14--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/ai/list-balances.ts@@ -0,0 +1,33 @@+import { createAction } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../../common/auth';+import { deepgramProps } from '../../common/props';+import { balancesOutputSchema } from '../../output-schemas';+import { listBalances, getBalancesAction } from '../get-balances';++const { project: _project, ...originalProps } = getBalancesAction.props;++export const listBalancesAiAction = createAction({+ auth: deepgramAuth,+ name: 'deepgram_list_balances',+ classification: 'SEARCH',+ displayName: 'List Credit Balances',+ description: 'Lists the prepaid credit balances of a Deepgram project.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists every prepaid credit balance of a Deepgram project with its ID, amount and units; amounts in different units are never added up. Use before large batches to avoid out-of-credit errors, or to get a balance ID for deepgram_get_balance. Needs an admin or owner key. Read-only.',+ idempotent: true,+ },+ outputSchema: balancesOutputSchema,+ props: {+ project_id: deepgramProps.projectId(),+ ...originalProps,+ },+ async run(context) {+ const { project_id, ...input } = context.propsValue;+ return listBalances({+ apiKey: context.auth.secret_text,+ input: { ...input, project: project_id ?? undefined },+ });+ },+});diff --git a/packages/pieces/community/deepgram/src/actions/ai/list-billing-fields.ts b/packages/pieces/community/deepgram/src/actions/ai/list-billing-fields.tsnew file mode 100644index 00000000000..80554d5e0b0--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/ai/list-billing-fields.ts@@ -0,0 +1,59 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../../common/auth';+import { billingFieldsOutputSchema } from '../../output-schemas';+import { DEEPGRAM_TIMEOUTS, deepgramClient } from '../../common/client';+import { deepgramProjects } from '../../common/projects';+import { deepgramProps } from '../../common/props';+import { BillingFieldsResponse, deepgramReports } from '../../common/reports';++export const listBillingFieldsAction = createAction({+ auth: deepgramAuth,+ name: 'deepgram_list_billing_fields',+ classification: 'SEARCH',+ displayName: 'List Billing Filter Values',+ description:+ 'Lists the API keys, deployments, tags and line items billed to a Deepgram project in a date range.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists the API key IDs, deployments, tags and line items (with descriptions) billed to a Deepgram project in a date range (YYYY-MM-DD). Use to find valid line items and tags for deepgram_get_billing_breakdown. Needs an admin or owner key. Read-only.',+ idempotent: true,+ },+ outputSchema: billingFieldsOutputSchema,+ props: {+ project_id: deepgramProps.projectId(),+ start: Property.DateTime({+ displayName: 'Start Date',+ description: 'First day to include.',+ required: false,+ }),+ end: Property.DateTime({+ displayName: 'End Date',+ description: 'Last day to include.',+ required: false,+ }),+ },+ async run(context) {+ const apiKey = context.auth.secret_text;+ const start = deepgramReports.toDay(context.propsValue.start);+ const end = deepgramReports.toDay(context.propsValue.end);+ deepgramReports.checkRange({ start, end });+ const projectId = await deepgramProjects.resolveProjectId({+ apiKey,+ project: context.propsValue.project_id,+ });+ const response = await deepgramClient.request<BillingFieldsResponse>({+ apiKey,+ method: HttpMethod.GET,+ path: deepgramProjects.projectPath({+ projectId,+ rest: ['billing', 'fields'],+ }),+ query: { start, end },+ timeoutMs: DEEPGRAM_TIMEOUTS.manage,+ operation: 'list the billing filter values',+ });+ return deepgramReports.flattenBillingFields(response.body ?? {});+ },+});diff --git a/packages/pieces/community/deepgram/src/actions/ai/list-models.ts b/packages/pieces/community/deepgram/src/actions/ai/list-models.tsnew file mode 100644index 00000000000..d5cd51d28b7--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/ai/list-models.ts@@ -0,0 +1,45 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../../common/auth';+import { listModelBuildsOutputSchema } from '../../output-schemas';+import { listModels, listModelsAction } from '../list-models';++const { project: _project, ...originalProps } = listModelsAction.props;++export const listModelsAiAction = createAction({+ auth: deepgramAuth,+ name: 'deepgram_list_models',+ classification: 'SEARCH',+ displayName: 'List Models and Voices (Agent)',+ description:+ 'Lists Deepgram speech-to-text models and text-to-speech voices, one row per model or one row per build.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists Deepgram speech-to-text models and text-to-speech voices with canonical IDs, languages and voice traits. Use to pick a model for deepgram_transcribe_audio or a voice (type tts) for deepgram_generate_speech. Turn on One Row per Build to get build UUIDs for deepgram_get_model; then narrow with language, because one model can have over 100 builds. Empty project ID lists the public catalog. Read-only.',+ idempotent: true,+ },+ outputSchema: listModelBuildsOutputSchema,+ props: {+ ...originalProps,+ project_id: Property.ShortText({+ displayName: 'Project ID',+ description:+ 'A project ID from List Projects (list_projects) to also list custom models trained for it. Leave empty for the public catalog.',+ required: false,+ }),+ perBuild: Property.Checkbox({+ displayName: 'One Row per Build',+ description:+ 'Return one row per language/version build with its UUID instead of one merged row per model.',+ required: false,+ defaultValue: false,+ }),+ },+ async run(context) {+ const { project_id, ...input } = context.propsValue;+ return listModels({+ apiKey: context.auth.secret_text,+ input: { ...input, project: project_id ?? undefined },+ });+ },+});diff --git a/packages/pieces/community/deepgram/src/actions/ai/list-project-members.ts b/packages/pieces/community/deepgram/src/actions/ai/list-project-members.tsnew file mode 100644index 00000000000..0ef7edaa865--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/ai/list-project-members.ts@@ -0,0 +1,36 @@+import { createAction } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../../common/auth';+import { deepgramProps } from '../../common/props';+import { listMembersOutputSchema } from '../../output-schemas';+import {+ listProjectMembers,+ listProjectMembersAction,+} from '../list-project-members';++const { project: _project, ...originalProps } = listProjectMembersAction.props;++export const listProjectMembersAiAction = createAction({+ auth: deepgramAuth,+ name: 'deepgram_list_project_members',+ classification: 'SEARCH',+ displayName: 'List Project Members (Agent)',+ description: 'Lists the members of a Deepgram project with their scopes.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists every member of a Deepgram project with email, name and scopes (roles), so it also answers which scopes each member holds. Use to audit who has access. Needs an admin or owner key; a member key gets a permission error. Read-only.',+ idempotent: true,+ },+ outputSchema: listMembersOutputSchema,+ props: {+ project_id: deepgramProps.projectId(),+ ...originalProps,+ },+ async run(context) {+ const { project_id, ...input } = context.propsValue;+ return listProjectMembers({+ apiKey: context.auth.secret_text,+ input: { ...input, project: project_id ?? undefined },+ });+ },+});diff --git a/packages/pieces/community/deepgram/src/actions/ai/list-purchases.ts b/packages/pieces/community/deepgram/src/actions/ai/list-purchases.tsnew file mode 100644index 00000000000..aa95ee4ac38--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/ai/list-purchases.ts@@ -0,0 +1,64 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../../common/auth';+import { purchasesOutputSchema } from '../../output-schemas';+import { DEEPGRAM_TIMEOUTS, deepgramClient } from '../../common/client';+import { deepgramProjects } from '../../common/projects';+import { deepgramProps } from '../../common/props';+import { deepgramReports, PurchaseRow } from '../../common/reports';++export const listPurchasesAction = createAction({+ auth: deepgramAuth,+ name: 'deepgram_list_purchases',+ classification: 'SEARCH',+ displayName: 'List Purchases',+ description: 'Lists the most recent credit purchases of a Deepgram project.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists the most recent credit purchases (orders) of a Deepgram project with amount, units, order type, creation and expiry date. Returns at most Limit orders and cannot page further. Use deepgram_list_balances for the credit that is left. Needs an admin or owner key. Read-only.',+ idempotent: true,+ },+ outputSchema: purchasesOutputSchema,+ props: {+ project_id: deepgramProps.projectId(),+ limit: Property.Number({+ displayName: 'Limit',+ description:+ 'How many recent purchases to return, from 1 to 1000. Defaults to 10.',+ required: false,+ defaultValue: 10,+ }),+ },+ async run(context) {+ const apiKey = context.auth.secret_text;+ const raw = context.propsValue.limit;+ const limit =+ raw === undefined || raw === null || String(raw) === ''+ ? 10+ : Number(raw);+ if (!Number.isInteger(limit) || limit < 1 || limit > 1000) {+ throw new Error('Limit must be a whole number from 1 to 1000.');+ }+ const projectId = await deepgramProjects.resolveProjectId({+ apiKey,+ project: context.propsValue.project_id,+ });+ const response = await deepgramClient.request<PurchasesResponse>({+ apiKey,+ method: HttpMethod.GET,+ path: deepgramProjects.projectPath({ projectId, rest: ['purchases'] }),+ query: { limit },+ timeoutMs: DEEPGRAM_TIMEOUTS.manage,+ operation: 'list purchases',+ });+ const orders = (response.body?.orders ?? []).map((order) =>+ deepgramReports.flattenPurchase(order)+ );+ return { orders, count: orders.length };+ },+});++type PurchasesResponse = {+ orders?: PurchaseRow[];+};diff --git a/packages/pieces/community/deepgram/src/actions/ai/list-requests.ts b/packages/pieces/community/deepgram/src/actions/ai/list-requests.tsnew file mode 100644index 00000000000..2e3ed701ef3--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/ai/list-requests.ts@@ -0,0 +1,34 @@+import { createAction } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../../common/auth';+import { deepgramProps } from '../../common/props';+import { listRequestsOutputSchema } from '../../output-schemas';+import { listRequests, listRequestsAction } from '../list-requests';++const { project: _project, ...originalProps } = listRequestsAction.props;++export const listRequestsAiAction = createAction({+ auth: deepgramAuth,+ name: 'deepgram_list_requests',+ classification: 'SEARCH',+ displayName: 'List Requests (Agent)',+ description:+ 'Lists past API requests of a Deepgram project with status, duration and cost.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists past API requests of a Deepgram project, newest first, with status code, audio duration and cost in USD, filterable by date range (YYYY-MM-DD or ISO date-time), endpoint, method and success. Use to audit usage or to find a request ID for deepgram_get_request. Returns one page; has_more is true when the page is full, so ask for the next page number. Read-only.',+ idempotent: true,+ },+ outputSchema: listRequestsOutputSchema,+ props: {+ project_id: deepgramProps.projectId(),+ ...originalProps,+ },+ async run(context) {+ const { project_id, ...input } = context.propsValue;+ return listRequests({+ apiKey: context.auth.secret_text,+ input: { ...input, project: project_id ?? undefined },+ });+ },+});diff --git a/packages/pieces/community/deepgram/src/actions/ai/list-think-models.ts b/packages/pieces/community/deepgram/src/actions/ai/list-think-models.tsnew file mode 100644index 00000000000..47357ac2868--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/ai/list-think-models.ts@@ -0,0 +1,43 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../../common/auth';+import { thinkModelsOutputSchema } from '../../output-schemas';+import { DEEPGRAM_TIMEOUTS, deepgramClient } from '../../common/client';+import { AGENT_BASE_URL } from '../../common/constants';++export const listThinkModelsAction = createAction({+ auth: deepgramAuth,+ name: 'deepgram_list_think_models',+ classification: 'SEARCH',+ displayName: 'List Voice Agent LLMs',+ description:+ 'Lists the language models a Deepgram Voice Agent can use to think.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists the LLMs (OpenAI, Anthropic, Google, Groq, Amazon Bedrock and others) that a Deepgram Voice Agent can use for its think step, each with its model ID, name and provider. Use when configuring a Deepgram Voice Agent. Read-only.',+ idempotent: true,+ },+ outputSchema: thinkModelsOutputSchema,+ props: {},+ async run(context) {+ const response = await deepgramClient.request<ThinkModelsResponse>({+ apiKey: context.auth.secret_text,+ method: HttpMethod.GET,+ path: '/agent/settings/think/models',+ baseUrl: AGENT_BASE_URL,+ timeoutMs: DEEPGRAM_TIMEOUTS.manage,+ operation: 'list voice agent models',+ });+ const models = (response.body?.models ?? []).map((model) => ({+ id: typeof model.id === 'string' ? model.id : String(model.id ?? ''),+ name: typeof model.name === 'string' ? model.name : null,+ provider: typeof model.provider === 'string' ? model.provider : null,+ }));+ return { models, count: models.length };+ },+});++type ThinkModelsResponse = {+ models?: { id?: unknown; name?: unknown; provider?: unknown }[];+};diff --git a/packages/pieces/community/deepgram/src/actions/ai/list-usage-fields.ts b/packages/pieces/community/deepgram/src/actions/ai/list-usage-fields.tsnew file mode 100644index 00000000000..7849e63f6bf--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/ai/list-usage-fields.ts@@ -0,0 +1,59 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../../common/auth';+import { usageFieldsOutputSchema } from '../../output-schemas';+import { DEEPGRAM_TIMEOUTS, deepgramClient } from '../../common/client';+import { deepgramProjects } from '../../common/projects';+import { deepgramProps } from '../../common/props';+import { UsageFieldsResponse, deepgramReports } from '../../common/reports';++export const listUsageFieldsAction = createAction({+ auth: deepgramAuth,+ name: 'deepgram_list_usage_fields',+ classification: 'SEARCH',+ displayName: 'List Usage Filter Values',+ description:+ 'Lists the tags, model builds, methods and features used by a Deepgram project in a date range.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists the tags, model builds (with model_id UUIDs), processing methods and features a Deepgram project actually used in a date range (YYYY-MM-DD). Use to find valid tag and model values for deepgram_get_usage_summary and deepgram_get_usage_breakdown; tags are returned without the tag= prefix. Read-only.',+ idempotent: true,+ },+ outputSchema: usageFieldsOutputSchema,+ props: {+ project_id: deepgramProps.projectId(),+ start: Property.DateTime({+ displayName: 'Start Date',+ description: 'First day to include.',+ required: false,+ }),+ end: Property.DateTime({+ displayName: 'End Date',+ description: 'Last day to include.',+ required: false,+ }),+ },+ async run(context) {+ const apiKey = context.auth.secret_text;+ const start = deepgramReports.toDay(context.propsValue.start);+ const end = deepgramReports.toDay(context.propsValue.end);+ deepgramReports.checkRange({ start, end });+ const projectId = await deepgramProjects.resolveProjectId({+ apiKey,+ project: context.propsValue.project_id,+ });+ const response = await deepgramClient.request<UsageFieldsResponse>({+ apiKey,+ method: HttpMethod.GET,+ path: deepgramProjects.projectPath({+ projectId,+ rest: ['usage', 'fields'],+ }),+ query: { start, end },+ timeoutMs: DEEPGRAM_TIMEOUTS.manage,+ operation: 'list the usage filter values',+ });+ return deepgramReports.flattenUsageFields(response.body ?? {});+ },+});diff --git a/packages/pieces/community/deepgram/src/actions/ai/transcribe-audio.ts b/packages/pieces/community/deepgram/src/actions/ai/transcribe-audio.tsnew file mode 100644index 00000000000..058bb28b714--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/ai/transcribe-audio.ts@@ -0,0 +1,45 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../../common/auth';+import { DEFAULT_STT_MODEL } from '../../common/constants';+import { transcribeAudioOutputSchema } from '../../output-schemas';+import { transcribeAudio, transcribeAudioAction } from '../transcribe-audio';++const {+ model: _model,+ audioUrl,+ audioFile,+ ...originalProps+} = transcribeAudioAction.props;++export const transcribeAudioAiAction = createAction({+ auth: deepgramAuth,+ name: 'deepgram_transcribe_audio',+ classification: 'READ',+ displayName: 'Transcribe Audio (Agent)',+ description:+ 'Transcribes an audio or video file or URL and returns the transcript, with optional speakers, paragraphs, summary, topics and more.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Transcribes speech from a public audio/video URL or a file from an earlier step with Deepgram and returns the full transcript and its request_id, optionally with speaker labels, paragraphs, detected language, entities and an English-only summary, topics, intents and sentiment. Suits recordings that finish processing within about 8 minutes. Each call is billed per audio minute, so retries are billed again.',+ idempotent: false,+ },+ outputSchema: transcribeAudioOutputSchema,+ props: {+ audioUrl,+ audioFile,+ model: Property.ShortText({+ displayName: 'Model',+ description: `A Deepgram speech-to-text model: a short alias such as nova-3 or nova-2, or a canonical name from deepgram_list_models such as nova-3-general. Leave empty for ${DEFAULT_STT_MODEL}.`,+ required: false,+ defaultValue: DEFAULT_STT_MODEL,+ }),+ ...originalProps,+ },+ async run(context) {+ return transcribeAudio({+ apiKey: context.auth.secret_text,+ input: context.propsValue,+ });+ },+});diff --git a/packages/pieces/community/deepgram/src/actions/analyze-text.ts b/packages/pieces/community/deepgram/src/actions/analyze-text.tsnew file mode 100644index 00000000000..3f162916748--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/analyze-text.ts@@ -0,0 +1,165 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../common/auth';+import { deepgramRead } from '../common/read';+import { deepgramTranscript } from '../common/transcript';+import { analyzeTextOutputSchema } from '../output-schemas';++export const analyzeTextAction = createAction({+ auth: deepgramAuth,+ name: 'analyze_text',+ classification: 'READ',+ displayName: 'Analyze Text',+ description:+ 'Summarizes English text and detects its topics, intents and sentiment.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Runs Deepgram text intelligence on English text (or a public text URL) and returns a summary, topics, intents and/or sentiment; choose at least one. Use for text you already have; for audio use deepgram_transcribe_audio with the same options. Billed per token, so repeat calls are billed again.',+ idempotent: false,+ },+ outputSchema: analyzeTextOutputSchema,+ props: {+ text: Property.LongText({+ displayName: 'Text',+ description: 'The English text to analyze. Use this or Text URL.',+ required: false,+ }),+ textUrl: Property.ShortText({+ displayName: 'Text URL',+ description:+ 'A public link to a plain-text file. Deepgram downloads it directly. Use this or Text.',+ required: false,+ }),+ summarize: Property.Checkbox({+ displayName: 'Summarize',+ required: false,+ defaultValue: true,+ }),+ topics: Property.Checkbox({+ displayName: 'Detect Topics',+ required: false,+ defaultValue: false,+ }),+ intents: Property.Checkbox({+ displayName: 'Detect Intents',+ required: false,+ defaultValue: false,+ }),+ sentiment: Property.Checkbox({+ displayName: 'Analyze Sentiment',+ required: false,+ defaultValue: false,+ }),+ customTopics: Property.Array({+ displayName: 'Custom Topics',+ description:+ 'Topics to look for in addition to (or instead of) the detected ones. Up to 100.',+ required: false,+ }),+ customTopicMode: Property.StaticDropdown({+ displayName: 'Custom Topic Mode',+ description:+ 'Extended adds your topics to the detected ones; Strict only returns your topics.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Extended', value: 'extended' },+ { label: 'Strict', value: 'strict' },+ ],+ },+ }),+ customIntents: Property.Array({+ displayName: 'Custom Intents',+ description:+ 'Intents to look for in addition to (or instead of) the detected ones. Up to 100.',+ required: false,+ }),+ customIntentMode: Property.StaticDropdown({+ displayName: 'Custom Intent Mode',+ description:+ 'Extended adds your intents to the detected ones; Strict only returns your intents.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Extended', value: 'extended' },+ { label: 'Strict', value: 'strict' },+ ],+ },+ }),+ },+ async run(context) {+ const props = context.propsValue;+ const text = typeof props.text === 'string' ? props.text : '';+ const textUrl = props.textUrl?.trim() ?? '';+ if (text.trim().length > 0 && textUrl.length > 0) {+ throw new Error('Provide either Text or Text URL, not both.');+ }+ if (text.trim().length === 0 && textUrl.length === 0) {+ throw new Error('Provide the text to analyze or a Text URL.');+ }+ if (textUrl.length > 0 && !/^https?:\/\//i.test(textUrl)) {+ throw new Error('Text URL must start with https:// or http://.');+ }+ const customTopics = textList({+ value: props.customTopics,+ label: 'Custom Topics',+ });+ const customIntents = textList({+ value: props.customIntents,+ label: 'Custom Intents',+ });+ const topics = props.topics === true || customTopics.length > 0;+ const intents = props.intents === true || customIntents.length > 0;+ const summarize = props.summarize === true;+ const sentiment = props.sentiment === true;+ if (!summarize && !topics && !intents && !sentiment) {+ throw new Error(+ 'Turn on at least one of Summarize, Detect Topics, Detect Intents or Analyze Sentiment.'+ );+ }+ const body = await deepgramRead.readText({+ apiKey: context.auth.secret_text,+ query: {+ language: 'en',+ summarize: summarize ? 'true' : undefined,+ topics: topics ? 'true' : undefined,+ intents: intents ? 'true' : undefined,+ sentiment: sentiment ? 'true' : undefined,+ custom_topic: customTopics,+ custom_topic_mode:+ customTopics.length > 0+ ? props.customTopicMode ?? undefined+ : undefined,+ custom_intent: customIntents,+ custom_intent_mode:+ customIntents.length > 0+ ? props.customIntentMode ?? undefined+ : undefined,+ },+ source: textUrl.length > 0 ? { url: textUrl } : { text },+ });+ return deepgramTranscript.flattenRead(body);+ },+});++function textList({+ value,+ label,+}: {+ value: unknown;+ label: string;+}): string[] {+ if (value === undefined || value === null || value === '') {+ return [];+ }+ const items = Array.isArray(value) ? value : [value];+ const texts = items+ .map((item) => (typeof item === 'string' ? item.trim() : ''))+ .filter((item) => item.length > 0);+ if (texts.length > 100) {+ throw new Error(`${label} accepts at most 100 values.`);+ }+ return texts;+}diff --git a/packages/pieces/community/deepgram/src/actions/create-summary.ts b/packages/pieces/community/deepgram/src/actions/create-summary.tsindex f4140adeffd..94acd70647b 100644--- a/packages/pieces/community/deepgram/src/actions/create-summary.ts+++ b/packages/pieces/community/deepgram/src/actions/create-summary.ts@@ -1,59 +1,37 @@import { Property, createAction } from '@activepieces/pieces-framework';+import { deepgramAudio } from '../common/audio';import { deepgramAuth } from '../common/auth';-import { BASE_URL, LANG_OPTIONS } from '../common/constants';-import { deepgramModels } from '../common/models';-import mime from 'mime-types';-import { httpClient, HttpMethod } from '@activepieces/pieces-common';+import { LANG_OPTIONS } from '../common/constants';+import { deepgramProps } from '../common/props';+import { deepgramTranscript } from '../common/transcript';export const createSummaryAction = createAction({auth: deepgramAuth,name: 'create_summary',classification: 'READ',displayName: 'Create Summary',- description: 'Produces a summary of the content from an audio file.',- audience: 'both',+ description: 'Produces a summary of the content from an English audio file.',+ audience: 'human',aiMetadata: {description:- 'Uploads an audio file to Deepgram and returns an AI-generated summary of its spoken content (summarize v2), synchronously. Pick this over Create Transcription when you need a condensed overview rather than the full text; by default it falls back to the full transcript if no summary is available. Re-running re-processes the audio and incurs another billed request, though it creates no persistent resource.',+ 'Uploads an audio file to Deepgram and returns an AI-generated summary of its spoken content (summarize v2), synchronously. Pick this over Create Transcription when you need a condensed overview rather than the full text; by default it falls back to the full transcript if no summary is available. Re-running re-processes the audio and incurs another billed request, though it creates no persistent resource. Agents should use deepgram_transcribe_audio with Summarize on.',idempotent: false,},props: {audioFile: Property.File({displayName: 'Audio File',+ description: 'The English audio or video file to summarize.',required: true,}),- model: Property.Dropdown({- auth: deepgramAuth,- displayName: 'Model',- required: false,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Enter your API key first',- options: [],- };- }- try {- const options = await deepgramModels.fetchSttModelOptions({- apiKey: auth.secret_text,- });- return { disabled: false, options };- } catch (error) {- return {- disabled: true,- options: [],- placeholder:- "Couldn't load models, check your API key or try again.",- };- }- },+ model: deepgramProps.sttModel({+ description:+ 'Leave empty for nova (Nova-1). For better accuracy choose nova-3-general.',}),language: Property.StaticDropdown({displayName: 'Language',required: false,- description: 'en',+ description:+ 'Summaries are only available for English (en, en-US, en-GB, en-AU, en-IN, en-NZ). Leave empty for en.',options: {disabled: false,options: LANG_OPTIONS,@@ -67,41 +45,38 @@ export const createSummaryAction = createAction({}),},async run(context) {- const {+ const { audioFile, fallbackToTranscript } = context.propsValue;+ const model = context.propsValue.model || 'nova';+ const language = context.propsValue.language || 'en';+ if (!deepgramAudio.isEnglish(language)) {+ throw new Error(+ `Deepgram summaries are only available for English, and the language is set to "${language}". Choose an English language or use Transcribe Audio.`+ );+ }+ const source = deepgramAudio.resolveSource({+ audioUrl: undefined,audioFile,- model = 'nova',- fallbackToTranscript,- language,- } = context.propsValue;- const mimeType = mime.lookup(audioFile.extension || '') || 'audio/wav';-- const response = await httpClient.sendRequest({- url: BASE_URL + '/listen',- method: HttpMethod.POST,- headers: {- Authorization: `Token ${context.auth.secret_text}`,- 'Content-Type': mimeType,- },- body: audioFile.data,- responseType: 'json',- queryParams: {- model,- summarize: 'v2',- language: language || 'en',- },+ fallbackContentType: 'audio/wav',});-- if (response.body.results.summary) {- return response.body.results.summary;+ const body = await deepgramAudio.listen({+ apiKey: context.auth.secret_text,+ source,+ query: { model, summarize: 'v2', language },+ operation: 'summarize the audio',+ });+ const summary = deepgramTranscript.summaryOutcome(body);+ if (summary && summary.result === 'success' && summary.short) {+ return summary;}-- if (- fallbackToTranscript &&- response.body.results.channels?.[0]?.alternatives?.[0]?.transcript- ) {- return response.body.results.channels[0].alternatives[0].transcript;+ const transcript = deepgramTranscript.firstTranscript(body);+ if (fallbackToTranscript && transcript) {+ return transcript;}-- throw new Error('No summary or transcript available');+ const reason = summary?.short ? ` (${summary.short})` : '';+ throw new Error(+ transcript+ ? `Deepgram could not summarize this audio${reason}. Turn on Fallback to Full Transcript to get the transcript instead.`+ : `Deepgram returned no summary or transcript for this audio${reason}.`+ );},});diff --git a/packages/pieces/community/deepgram/src/actions/create-transcription.ts b/packages/pieces/community/deepgram/src/actions/create-transcription.tsindex 71c2dcd9f40..e2e608df02f 100644--- a/packages/pieces/community/deepgram/src/actions/create-transcription.ts+++ b/packages/pieces/community/deepgram/src/actions/create-transcription.ts@@ -1,59 +1,47 @@import { Property, createAction } from '@activepieces/pieces-framework';+import { deepgramAudio } from '../common/audio';import { deepgramAuth } from '../common/auth';-import { BASE_URL, LANG_OPTIONS } from '../common/constants';-import { deepgramModels } from '../common/models';-import mime from 'mime-types';-import { httpClient, HttpMethod } from '@activepieces/pieces-common';+import { deepgramClient } from '../common/client';+import { LANG_OPTIONS } from '../common/constants';+import { deepgramProps } from '../common/props';+import { createTranscriptionCallbackOutputSchema } from '../output-schemas';export const createTranscriptionCallbackAction = createAction({auth: deepgramAuth,name: 'create_transcription_callback',- classification: 'READ',+ classification: 'WRITE',displayName: 'Create Transcription (Callback)',- description: 'Creates a transcription using a callback URL.',- audience: 'both',+ description:+ 'Starts a transcription and has Deepgram send the result to a callback URL. To receive it in another flow, use the Catch Webhook URL of the Webhook piece.',+ audience: 'human',aiMetadata: {description:- 'Submits an audio file to Deepgram for asynchronous speech-to-text: the action returns only a request ID immediately, and the finished transcript is delivered later to the callback URL you provide. Pick this for long audio or when a webhook endpoint will consume the result; it does not return the transcript itself. Each run submits a new billed transcription job, so it is not idempotent.',+ 'Submits an audio file to Deepgram for asynchronous speech-to-text: the action returns only a request ID immediately, and the finished transcript is delivered later to the callback URL you provide. Pick this for long audio or when a webhook endpoint will consume the result; it does not return the transcript itself. Each run submits a new billed transcription job, so it is not idempotent. Agents should use deepgram_transcribe_audio.',idempotent: false,},+ outputSchema: createTranscriptionCallbackOutputSchema,props: {audioFile: Property.File({displayName: 'Audio File',- required: true,+ description:+ 'The audio or video file to transcribe. Use this or Audio URL.',+ required: false,}),- model: Property.Dropdown({- auth: deepgramAuth,- displayName: 'Model',+ audioUrl: Property.ShortText({+ displayName: 'Audio URL',+ description:+ 'A public link to the audio or video file. Deepgram downloads it directly. Use this or Audio File.',required: false,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Enter your API key first',- options: [],- };- }- try {- const options = await deepgramModels.fetchSttModelOptions({- apiKey: auth.secret_text,- });- return { disabled: false, options };- } catch (error) {- return {- disabled: true,- options: [],- placeholder:- "Couldn't load models, check your API key or try again.",- };- }- },+ }),+ model: deepgramProps.sttModel({+ description:+ 'Leave empty for nova (Nova-1, English, Spanish and Hindi only). For other languages choose nova-3-general or nova-2-general.',}),language: Property.StaticDropdown({displayName: 'Language',required: false,- description: 'en',+ description:+ 'Spoken language. Leave empty for en. The default model nova only supports en, es and hi-Latn; pick a nova-3 or nova-2 model for other languages.',options: {disabled: false,options: LANG_OPTIONS,@@ -61,38 +49,82 @@ export const createTranscriptionCallbackAction = createAction({}),callbackUrl: Property.ShortText({displayName: 'Callback URL',- description: 'URL to receive the transcription when ready.',+ description:+ 'URL to receive the transcription when ready. Must use port 80, 443, 8080 or 8443. Basic-auth credentials (https://user:password@host) are allowed and hidden in the output.',required: true,}),+ callbackMethod: Property.StaticDropdown({+ displayName: 'Callback Method',+ description: 'How Deepgram sends the result. Defaults to POST.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'POST', value: 'POST' },+ { label: 'PUT', value: 'PUT' },+ ],+ },+ }),+ smartFormat: Property.Checkbox({+ displayName: 'Smart Format',+ description:+ 'Add punctuation, capitals and readable numbers, dates and currency.',+ required: false,+ defaultValue: false,+ }),+ diarize: Property.Checkbox({+ displayName: 'Identify Speakers',+ description: 'Label who speaks when.',+ required: false,+ defaultValue: false,+ }),+ paragraphs: Property.Checkbox({+ displayName: 'Paragraphs',+ required: false,+ defaultValue: false,+ }),+ utterances: Property.Checkbox({+ displayName: 'Utterances',+ required: false,+ defaultValue: false,+ }),},async run(context) {- const {- audioFile,- model = 'nova',- callbackUrl,- language,- } = context.propsValue;- const mimeType = mime.lookup(audioFile.extension || '') || 'audio/wav';-- const response = await httpClient.sendRequest({- url: BASE_URL + '/listen',- method: HttpMethod.POST,- headers: {- Authorization: `Token ${context.auth.secret_text}`,- 'Content-Type': mimeType,- },- body: audioFile.data,- responseType: 'json',- queryParams: {+ const props = context.propsValue;+ const model = props.model || 'nova';+ const language = props.language || 'en';+ const callbackUrl = deepgramAudio.checkCallbackUrl(props.callbackUrl);+ const callbackMethod = props.callbackMethod ?? undefined;+ if (+ callbackMethod &&+ callbackMethod !== 'POST' &&+ callbackMethod !== 'PUT'+ ) {+ throw new Error('Callback Method must be POST or PUT.');+ }+ const source = deepgramAudio.resolveSource({+ audioUrl: props.audioUrl,+ audioFile: props.audioFile,+ fallbackContentType: 'audio/wav',+ });+ const body = await deepgramAudio.listen({+ apiKey: context.auth.secret_text,+ source,+ query: {model,callback: callbackUrl,- language: language || 'en',+ callback_method: callbackMethod?.toLowerCase(),+ language,+ smart_format: props.smartFormat === true ? 'true' : undefined,+ diarize_model: props.diarize === true ? 'latest' : undefined,+ paragraphs: props.paragraphs === true ? 'true' : undefined,+ utterances: props.utterances === true ? 'true' : undefined,},+ operation: 'start the transcription',});-return {- requestId: response.body.request_id,- callbackUrl,+ requestId: body.request_id ?? body.metadata?.request_id ?? null,+ callbackUrl: deepgramClient.maskUrlCredentials(callbackUrl),status: 'submitted',};},diff --git a/packages/pieces/community/deepgram/src/actions/get-balances.ts b/packages/pieces/community/deepgram/src/actions/get-balances.tsnew file mode 100644index 00000000000..eb0dfa253c5--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/get-balances.ts@@ -0,0 +1,81 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../common/auth';+import { DEEPGRAM_TIMEOUTS, deepgramClient } from '../common/client';+import { deepgramProjects } from '../common/projects';+import { deepgramProps } from '../common/props';+import { balancesOutputSchema } from '../output-schemas';++export const getBalancesAction = createAction({+ auth: deepgramAuth,+ name: 'get_balances',+ classification: 'READ',+ displayName: 'Get Credit Balance',+ description:+ 'Gets the remaining prepaid credit of a Deepgram project. Needs an admin or owner API key.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Returns the remaining prepaid credit balances of a Deepgram project, each with its amount and units. Use before large batches to avoid out-of-credit (402) errors. Requires an admin or owner key. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: balancesOutputSchema,+ props: {+ project: deepgramProps.project(),+ },+ async run(context) {+ return listBalances({+ apiKey: context.auth.secret_text,+ input: context.propsValue,+ });+ },+});++export async function listBalances({+ apiKey,+ input,+}: {+ apiKey: string;+ input: ListBalancesInput;+}) {+ const projectId = await deepgramProjects.resolveProjectId({+ apiKey,+ project: input.project,+ });+ const response = await deepgramClient.request<BalancesResponse>({+ apiKey,+ method: HttpMethod.GET,+ path: deepgramProjects.projectPath({ projectId, rest: ['balances'] }),+ timeoutMs: DEEPGRAM_TIMEOUTS.manage,+ operation: 'get the credit balance',+ });+ return {+ balances: (response.body?.balances ?? []).map((balance) =>+ flattenBalance(balance)+ ),+ };+}++export function flattenBalance(balance: BalanceRow) {+ return {+ balance_id: balance.balance_id ?? '',+ amount: typeof balance.amount === 'number' ? balance.amount : null,+ units: balance.units ?? null,+ purchase_order_id: balance.purchase_order_id ?? null,+ };+}++export type BalanceRow = {+ balance_id?: string;+ amount?: number;+ units?: string;+ purchase_order_id?: string;+};++type BalancesResponse = {+ balances?: BalanceRow[];+};++export type ListBalancesInput = {+ project?: string;+};diff --git a/packages/pieces/community/deepgram/src/actions/get-billing-breakdown.ts b/packages/pieces/community/deepgram/src/actions/get-billing-breakdown.tsnew file mode 100644index 00000000000..e77782d3007--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/get-billing-breakdown.ts@@ -0,0 +1,103 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../common/auth';+import { DEEPGRAM_TIMEOUTS, deepgramClient } from '../common/client';+import { deepgramProjects } from '../common/projects';+import { deepgramProps } from '../common/props';+import { BillingBreakdownResponse, deepgramReports } from '../common/reports';+import { billingOutputSchema } from '../output-schemas';++export const getBillingBreakdownAction = createAction({+ auth: deepgramAuth,+ name: 'get_billing_breakdown',+ classification: 'READ',+ displayName: 'Get Cost Breakdown',+ description:+ 'Gets what a Deepgram project spent in dollars for a date range, optionally grouped. Needs an admin or owner API key.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Returns the dollar cost of a Deepgram project for a date range, split per day or grouped by line item (for example streaming::nova-3), API key, deployment or tag, plus the total. Requires an admin or owner key. Use deepgram_get_usage_breakdown for hours and requests. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: billingOutputSchema,+ props: {+ project: deepgramProps.project(),+ start: Property.DateTime({+ displayName: 'Start Date',+ description: 'First day to include.',+ required: false,+ }),+ end: Property.DateTime({+ displayName: 'End Date',+ description: 'Last day to include.',+ required: false,+ }),+ groupBy: Property.StaticMultiSelectDropdown({+ displayName: 'Group By',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Line item', value: 'line_item' },+ { label: 'API key (accessor)', value: 'accessor' },+ { label: 'Deployment', value: 'deployment' },+ { label: 'Tag', value: 'tags' },+ ],+ },+ }),+ lineItem: Property.ShortText({+ displayName: 'Line Item',+ description:+ 'Only include this line item, for example streaming::nova-3.',+ required: false,+ }),+ },+ async run(context) {+ return getBillingBreakdown({+ apiKey: context.auth.secret_text,+ input: context.propsValue,+ });+ },+});++export async function getBillingBreakdown({+ apiKey,+ input,+}: {+ apiKey: string;+ input: BillingBreakdownInput;+}) {+ const start = deepgramReports.toDay(input.start);+ const end = deepgramReports.toDay(input.end);+ deepgramReports.checkRange({ start, end });+ const projectId = await deepgramProjects.resolveProjectId({+ apiKey,+ project: input.project,+ });+ const response = await deepgramClient.request<BillingBreakdownResponse>({+ apiKey,+ method: HttpMethod.GET,+ path: deepgramProjects.projectPath({+ projectId,+ rest: ['billing', 'breakdown'],+ }),+ query: {+ start,+ end,+ grouping: input.groupBy ?? [],+ line_item: input.lineItem?.trim() || undefined,+ },+ timeoutMs: DEEPGRAM_TIMEOUTS.manage,+ operation: 'get the cost breakdown',+ });+ return deepgramReports.flattenBilling(response.body ?? {});+}++export type BillingBreakdownInput = {+ project?: string;+ start?: string;+ end?: string;+ groupBy?: string[];+ lineItem?: string;+};diff --git a/packages/pieces/community/deepgram/src/actions/get-project.ts b/packages/pieces/community/deepgram/src/actions/get-project.tsnew file mode 100644index 00000000000..59d1cd40c12--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/get-project.ts@@ -0,0 +1,31 @@+import { createAction } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../common/auth';+import { deepgramProjects } from '../common/projects';+import { deepgramProps } from '../common/props';+import { projectOutputSchema } from '../output-schemas';++export const getProjectAction = createAction({+ auth: deepgramAuth,+ name: 'get_project',+ classification: 'READ',+ displayName: 'Get Project',+ description: 'Gets the name and settings of a Deepgram project.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Returns one Deepgram project by ID with its name and model-improvement opt-out setting. Leave the project empty when the key has a single project. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: projectOutputSchema,+ props: {+ project: deepgramProps.project(),+ },+ async run(context) {+ const apiKey = context.auth.secret_text;+ const projectId = await deepgramProjects.resolveProjectId({+ apiKey,+ project: context.propsValue.project,+ });+ return deepgramProjects.getProject({ apiKey, projectId });+ },+});diff --git a/packages/pieces/community/deepgram/src/actions/get-request.ts b/packages/pieces/community/deepgram/src/actions/get-request.tsnew file mode 100644index 00000000000..9d3fc47fb4f--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/get-request.ts@@ -0,0 +1,80 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../common/auth';+import { DEEPGRAM_TIMEOUTS, deepgramClient } from '../common/client';+import { deepgramProjects } from '../common/projects';+import { deepgramProps } from '../common/props';+import { deepgramReports, RequestRow } from '../common/reports';+import { requestOutputSchema } from '../output-schemas';++export const getRequestAction = createAction({+ auth: deepgramAuth,+ name: 'get_request',+ classification: 'READ',+ displayName: 'Get Request',+ description:+ 'Gets one past Deepgram request by ID with its status, duration and cost.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Returns one past Deepgram API request by its request ID with status code, completion time, audio duration and cost in USD. Use to check whether a callback transcription finished or what a call cost. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: requestOutputSchema,+ props: {+ project: deepgramProps.project(),+ requestId: Property.ShortText({+ displayName: 'Request ID',+ description:+ 'The request ID returned by a Deepgram action, for example Create Transcription (Callback).',+ required: true,+ }),+ },+ async run(context) {+ return getRequest({+ apiKey: context.auth.secret_text,+ input: context.propsValue,+ });+ },+});++export async function getRequest({+ apiKey,+ input,+}: {+ apiKey: string;+ input: GetRequestInput;+}) {+ const requestId = (input.requestId ?? '').trim();+ if (requestId.length === 0) {+ throw new Error('Enter a request ID.');+ }+ const projectId = await deepgramProjects.resolveProjectId({+ apiKey,+ project: input.project,+ });+ const response = await deepgramClient.request<+ RequestRow & { request?: RequestRow }+ >({+ apiKey,+ method: HttpMethod.GET,+ path: deepgramProjects.projectPath({+ projectId,+ rest: ['requests', requestId],+ }),+ timeoutMs: DEEPGRAM_TIMEOUTS.manage,+ operation: 'get the request',+ });+ const row = response.body?.request ?? response.body;+ if (!row || !row.request_id) {+ throw new Error(+ `Deepgram has no request with ID ${requestId} in this project. Check the request ID and project; a request made in the last few minutes may not be listed yet.`+ );+ }+ return deepgramReports.flattenRequest(row);+}++export type GetRequestInput = {+ project?: string;+ requestId?: string;+};diff --git a/packages/pieces/community/deepgram/src/actions/get-usage.ts b/packages/pieces/community/deepgram/src/actions/get-usage.tsnew file mode 100644index 00000000000..7f5fc537daf--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/get-usage.ts@@ -0,0 +1,122 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../common/auth';+import { DEEPGRAM_TIMEOUTS, deepgramClient } from '../common/client';+import { deepgramProjects } from '../common/projects';+import { deepgramProps } from '../common/props';+import { deepgramReports, UsageBreakdownResponse } from '../common/reports';+import { usageOutputSchema } from '../output-schemas';++export const getUsageAction = createAction({+ auth: deepgramAuth,+ name: 'get_usage',+ classification: 'READ',+ displayName: 'Get Usage Breakdown',+ description:+ 'Gets audio hours, requests, characters and tokens used by a Deepgram project, optionally grouped.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Returns usage totals of a Deepgram project for a date range (audio hours, requests, text-to-speech characters, tokens), split per day or grouped by endpoint, model, method, tag, key, feature set or deployment. Use for usage reports; use deepgram_get_billing_breakdown for dollars. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: usageOutputSchema,+ props: {+ project: deepgramProps.project(),+ start: Property.DateTime({+ displayName: 'Start Date',+ description: 'First day to include. Deepgram defaults to 30 days ago.',+ required: false,+ }),+ end: Property.DateTime({+ displayName: 'End Date',+ description: 'Last day to include. Deepgram defaults to today.',+ required: false,+ }),+ groupBy: Property.StaticDropdown({+ displayName: 'Group By',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Endpoint', value: 'endpoint' },+ { label: 'Model', value: 'models' },+ { label: 'Method', value: 'method' },+ { label: 'Tag', value: 'tags' },+ { label: 'API key (accessor)', value: 'accessor' },+ { label: 'Feature set', value: 'feature_set' },+ { label: 'Deployment', value: 'deployment' },+ ],+ },+ }),+ endpoint: Property.StaticDropdown({+ displayName: 'Endpoint',+ description: 'Only count requests to this endpoint.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Speech to text (listen)', value: 'listen' },+ { label: 'Text intelligence (read)', value: 'read' },+ { label: 'Text to speech (speak)', value: 'speak' },+ { label: 'Voice agent (agent)', value: 'agent' },+ ],+ },+ }),+ tag: Property.ShortText({+ displayName: 'Tag',+ description: 'Only count requests sent with this tag.',+ required: false,+ }),+ },+ async run(context) {+ return getUsageBreakdown({+ apiKey: context.auth.secret_text,+ input: context.propsValue,+ });+ },+});++export async function getUsageBreakdown({+ apiKey,+ input,+}: {+ apiKey: string;+ input: UsageBreakdownInput;+}) {+ const { groupBy, endpoint, tag } = input;+ const start = deepgramReports.toDay(input.start);+ const end = deepgramReports.toDay(input.end);+ deepgramReports.checkRange({ start, end });+ const projectId = await deepgramProjects.resolveProjectId({+ apiKey,+ project: input.project,+ });+ const response = await deepgramClient.request<UsageBreakdownResponse>({+ apiKey,+ method: HttpMethod.GET,+ path: deepgramProjects.projectPath({+ projectId,+ rest: ['usage', 'breakdown'],+ }),+ query: {+ start,+ end,+ grouping: groupBy ?? undefined,+ endpoint: endpoint ?? undefined,+ tag: tag?.trim() || undefined,+ },+ timeoutMs: DEEPGRAM_TIMEOUTS.manage,+ operation: 'get usage',+ });+ return deepgramReports.flattenUsage(response.body ?? {});+}++export type UsageBreakdownInput = {+ project?: string;+ start?: string;+ end?: string;+ groupBy?: string;+ endpoint?: string;+ tag?: string;+};diff --git a/packages/pieces/community/deepgram/src/actions/list-models.ts b/packages/pieces/community/deepgram/src/actions/list-models.tsnew file mode 100644index 00000000000..db21f87d8e0--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/list-models.ts@@ -0,0 +1,93 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../common/auth';+import { deepgramModels } from '../common/models';+import { deepgramProps } from '../common/props';+import { listModelsOutputSchema } from '../output-schemas';++export const listModelsAction = createAction({+ auth: deepgramAuth,+ name: 'list_models',+ classification: 'SEARCH',+ displayName: 'List Models and Voices',+ description:+ 'Lists Deepgram speech-to-text models and text-to-speech voices, one row per model.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Lists Deepgram speech-to-text models and text-to-speech voices with their canonical IDs, languages and voice traits, one row per model (versions merged). Use to pick a model ID for deepgram_transcribe_audio or a voice ID for deepgram_generate_speech; filter by type and language. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: listModelsOutputSchema,+ props: {+ type: Property.StaticDropdown({+ displayName: 'Type',+ required: true,+ defaultValue: 'all',+ options: {+ disabled: false,+ options: [+ { label: 'Speech to text and voices', value: 'all' },+ { label: 'Speech to text models', value: 'stt' },+ { label: 'Text to speech voices', value: 'tts' },+ ],+ },+ }),+ language: Property.ShortText({+ displayName: 'Language',+ description:+ 'Only list models for this language code, for example en, es or de. "en" also matches en-US and en-GB.',+ required: false,+ }),+ project: {+ ...deepgramProps.project(),+ description:+ 'Pick a project to also list custom models trained for it. Leave empty for the public catalog.',+ },+ includeOutdated: Property.Checkbox({+ displayName: 'Include Older Versions',+ description:+ 'Also consider models that are no longer the latest version.',+ required: false,+ defaultValue: false,+ }),+ },+ async run(context) {+ return listModels({+ apiKey: context.auth.secret_text,+ input: context.propsValue,+ });+ },+});++export async function listModels({+ apiKey,+ input,+}: {+ apiKey: string;+ input: ListModelsInput;+}) {+ const type = input.type;+ if (type !== 'all' && type !== 'stt' && type !== 'tts') {+ throw new Error('Type must be all, stt or tts.');+ }+ const options = {+ apiKey,+ projectId: input.project?.trim() || undefined,+ type,+ language: input.language ?? undefined,+ includeOutdated: input.includeOutdated === true,+ } as const;+ const models =+ input.perBuild === true+ ? await deepgramModels.listModelBuilds(options)+ : await deepgramModels.listModels(options);+ return { models, count: models.length };+}++export type ListModelsInput = {+ type?: string;+ language?: string;+ project?: string;+ includeOutdated?: boolean;+ perBuild?: boolean;+};diff --git a/packages/pieces/community/deepgram/src/actions/list-project-keys.ts b/packages/pieces/community/deepgram/src/actions/list-project-keys.tsnew file mode 100644index 00000000000..54ed270178d--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/list-project-keys.ts@@ -0,0 +1,78 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../common/auth';+import { DEEPGRAM_TIMEOUTS, deepgramClient } from '../common/client';+import { deepgramProjects } from '../common/projects';+import { deepgramProps } from '../common/props';+import { deepgramReports } from '../common/reports';+import { listKeysOutputSchema } from '../output-schemas';++export const listProjectKeysAction = createAction({+ auth: deepgramAuth,+ name: 'list_project_keys',+ classification: 'SEARCH',+ displayName: 'List API Keys',+ description:+ 'Lists the API keys of a Deepgram project (never the secret values). A member key only sees its own keys.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists API key records of a Deepgram project with ID, comment, scopes, creation date and owner email; the secret key value is never returned. Member keys only see keys they created; admin and owner keys see all. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: listKeysOutputSchema,+ props: {+ project: deepgramProps.project(),+ status: Property.StaticDropdown({+ displayName: 'Status',+ description: 'Only list keys with this status. Leave empty for all keys.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Active', value: 'active' },+ { label: 'Expired', value: 'expired' },+ ],+ },+ }),+ },+ async run(context) {+ const apiKey = context.auth.secret_text;+ const projectId = await deepgramProjects.resolveProjectId({+ apiKey,+ project: context.propsValue.project,+ });+ const response = await deepgramClient.request<KeysResponse>({+ apiKey,+ method: HttpMethod.GET,+ path: deepgramProjects.projectPath({ projectId, rest: ['keys'] }),+ query: { status: context.propsValue.status ?? undefined },+ timeoutMs: DEEPGRAM_TIMEOUTS.manage,+ operation: 'list API keys',+ });+ return {+ keys: (response.body?.api_keys ?? []).map((item) => ({+ api_key_id: item.api_key?.api_key_id ?? '',+ comment: item.api_key?.comment ?? null,+ scopes: deepgramReports.joinList(item.api_key?.scopes),+ created: item.api_key?.created ?? null,+ expiration_date: item.api_key?.expiration_date ?? null,+ member_id: item.member?.member_id ?? null,+ member_email: item.member?.email ?? null,+ })),+ };+ },+});++type KeysResponse = {+ api_keys?: {+ member?: { member_id?: string; email?: string };+ api_key?: {+ api_key_id?: string;+ comment?: string;+ scopes?: string[];+ created?: string;+ expiration_date?: string;+ };+ }[];+};diff --git a/packages/pieces/community/deepgram/src/actions/list-project-members.ts b/packages/pieces/community/deepgram/src/actions/list-project-members.tsnew file mode 100644index 00000000000..122abafe80a--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/list-project-members.ts@@ -0,0 +1,76 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../common/auth';+import { DEEPGRAM_TIMEOUTS, deepgramClient } from '../common/client';+import { deepgramProjects } from '../common/projects';+import { deepgramProps } from '../common/props';+import { deepgramReports } from '../common/reports';+import { listMembersOutputSchema } from '../output-schemas';++export const listProjectMembersAction = createAction({+ auth: deepgramAuth,+ name: 'list_project_members',+ classification: 'SEARCH',+ displayName: 'List Project Members',+ description:+ 'Lists the members of a Deepgram project with their roles. Needs an admin or owner API key.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Lists every member of a Deepgram project with email, name and scopes (roles). Use to audit who has access. Requires an admin or owner API key; a member key gets a permission error. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: listMembersOutputSchema,+ props: {+ project: deepgramProps.project(),+ },+ async run(context) {+ return listProjectMembers({+ apiKey: context.auth.secret_text,+ input: context.propsValue,+ });+ },+});++export async function listProjectMembers({+ apiKey,+ input,+}: {+ apiKey: string;+ input: ListMembersInput;+}) {+ const projectId = await deepgramProjects.resolveProjectId({+ apiKey,+ project: input.project,+ });+ const response = await deepgramClient.request<MembersResponse>({+ apiKey,+ method: HttpMethod.GET,+ path: deepgramProjects.projectPath({ projectId, rest: ['members'] }),+ timeoutMs: DEEPGRAM_TIMEOUTS.manage,+ operation: 'list project members',+ });+ return {+ members: (response.body?.members ?? []).map((member) => ({+ member_id: member.member_id ?? '',+ email: member.email ?? null,+ first_name: member.first_name ?? null,+ last_name: member.last_name ?? null,+ scopes: deepgramReports.joinList(member.scopes),+ })),+ };+}++type MembersResponse = {+ members?: {+ member_id?: string;+ email?: string;+ first_name?: string;+ last_name?: string;+ scopes?: string[];+ }[];+};++export type ListMembersInput = {+ project?: string;+};diff --git a/packages/pieces/community/deepgram/src/actions/list-projects.ts b/packages/pieces/community/deepgram/src/actions/list-projects.tsindex ba2e44873f2..236d770820c 100644--- a/packages/pieces/community/deepgram/src/actions/list-projects.ts+++ b/packages/pieces/community/deepgram/src/actions/list-projects.ts@@ -1,30 +1,26 @@import { createAction } from '@activepieces/pieces-framework';import { deepgramAuth } from '../common/auth';-import { httpClient, HttpMethod } from '@activepieces/pieces-common';-import { BASE_URL } from '../common/constants';+import { deepgramProjects } from '../common/projects';+import { listProjectsOutputSchema } from '../output-schemas';export const listProjectsAction = createAction({auth: deepgramAuth,name: 'list_projects',classification: 'SEARCH',displayName: 'List Projects',- description: 'Retrieves a list of all projects associated with the account.',+ description: 'Lists the Deepgram projects this API key can access.',audience: 'both',aiMetadata: {description:'Fetches all Deepgram projects accessible to the authenticated API key, with no inputs or filters. Use it to discover project IDs before project-scoped operations or to verify account access. Read-only and safe to call repeatedly.',idempotent: true,},+ outputSchema: listProjectsOutputSchema,props: {},async run(context) {- const response = await httpClient.sendRequest({- method: HttpMethod.GET,- url: BASE_URL + '/projects',- headers: {- Authorization: `Token ${context.auth.secret_text}`,- },+ const projects = await deepgramProjects.listProjects({+ apiKey: context.auth.secret_text,});-- return response.body;+ return { projects };},});diff --git a/packages/pieces/community/deepgram/src/actions/list-requests.ts b/packages/pieces/community/deepgram/src/actions/list-requests.tsnew file mode 100644index 00000000000..ce510c345aa--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/list-requests.ts@@ -0,0 +1,191 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../common/auth';+import { DEEPGRAM_TIMEOUTS, deepgramClient } from '../common/client';+import { deepgramProjects } from '../common/projects';+import { deepgramProps } from '../common/props';+import { deepgramReports, RequestRow } from '../common/reports';+import { listRequestsOutputSchema } from '../output-schemas';++export const listRequestsAction = createAction({+ auth: deepgramAuth,+ name: 'list_requests',+ classification: 'SEARCH',+ displayName: 'List Requests',+ description:+ 'Lists past API requests of a Deepgram project with status, duration and cost.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Lists past API requests of a Deepgram project, newest first, with status code, audio duration and cost in USD, filterable by date range, endpoint, method and success. Use to audit usage or find a request ID. Returns one page; has_more is true when the page is full, so ask for the next page number. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: listRequestsOutputSchema,+ props: {+ project: deepgramProps.project(),+ start: Property.DateTime({+ displayName: 'From',+ description: 'Only requests made at or after this time.',+ required: false,+ }),+ end: Property.DateTime({+ displayName: 'To',+ description: 'Only requests made at or before this time.',+ required: false,+ }),+ endpoint: Property.StaticDropdown({+ displayName: 'Endpoint',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Speech to text (listen)', value: 'listen' },+ { label: 'Text intelligence (read)', value: 'read' },+ { label: 'Text to speech (speak)', value: 'speak' },+ { label: 'Voice agent (agent)', value: 'agent' },+ ],+ },+ }),+ method: Property.StaticDropdown({+ displayName: 'Method',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Synchronous', value: 'sync' },+ { label: 'Callback (async)', value: 'async' },+ { label: 'Streaming', value: 'streaming' },+ ],+ },+ }),+ status: Property.StaticDropdown({+ displayName: 'Status',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Succeeded', value: 'succeeded' },+ { label: 'Failed', value: 'failed' },+ ],+ },+ }),+ limit: Property.Number({+ displayName: 'Limit',+ description: 'Requests per page, from 1 to 1000. Defaults to 50.',+ required: false,+ defaultValue: 50,+ }),+ page: Property.Number({+ displayName: 'Page',+ description: 'Page number, starting at 0.',+ required: false,+ defaultValue: 0,+ }),+ },+ async run(context) {+ return listRequests({+ apiKey: context.auth.secret_text,+ input: context.propsValue,+ });+ },+});++export async function listRequests({+ apiKey,+ input,+}: {+ apiKey: string;+ input: ListRequestsInput;+}) {+ const { start, end, endpoint, method, status } = input;+ const limit = wholeNumber({+ value: input.limit,+ fallback: 50,+ min: 1,+ max: 1000,+ label: 'Limit',+ });+ const page = wholeNumber({+ value: input.page,+ fallback: 0,+ min: 0,+ max: Number.MAX_SAFE_INTEGER,+ label: 'Page',+ });+ const from = deepgramReports.toInstant(start);+ const to = deepgramReports.toInstant(end);+ deepgramReports.checkRange({ start: from, end: to });+ const projectId = await deepgramProjects.resolveProjectId({+ apiKey,+ project: input.project,+ });+ const response = await deepgramClient.request<RequestsResponse>({+ apiKey,+ method: HttpMethod.GET,+ path: deepgramProjects.projectPath({ projectId, rest: ['requests'] }),+ query: {+ start: from,+ end: to,+ endpoint: endpoint ?? undefined,+ method: method ?? undefined,+ status: status ?? undefined,+ limit,+ page,+ },+ timeoutMs: DEEPGRAM_TIMEOUTS.manage,+ operation: 'list requests',+ });+ const requests = (response.body?.requests ?? []).map((row) =>+ deepgramReports.flattenRequest(row)+ );+ return {+ requests,+ page,+ limit,+ has_more: requests.length === limit,+ };+}++function wholeNumber({+ value,+ fallback,+ min,+ max,+ label,+}: {+ value: unknown;+ fallback: number;+ min: number;+ max: number;+ label: string;+}): number {+ if (value === undefined || value === null || value === '') {+ return fallback;+ }+ const parsed = Number(value);+ if (!Number.isInteger(parsed) || parsed < min || parsed > max) {+ throw new Error(+ `${label} must be a whole number from ${min}${+ max === Number.MAX_SAFE_INTEGER ? ' up' : ` to ${max}`+ }.`+ );+ }+ return parsed;+}++type RequestsResponse = {+ page?: number;+ limit?: number;+ requests?: RequestRow[];+};++export type ListRequestsInput = {+ project?: string;+ start?: string;+ end?: string;+ endpoint?: string;+ method?: string;+ status?: string;+ limit?: number;+ page?: number;+};diff --git a/packages/pieces/community/deepgram/src/actions/text-to-speech.ts b/packages/pieces/community/deepgram/src/actions/text-to-speech.tsindex 1f8a0cb0dba..0b0df72b7fc 100644--- a/packages/pieces/community/deepgram/src/actions/text-to-speech.ts+++ b/packages/pieces/community/deepgram/src/actions/text-to-speech.ts@@ -1,53 +1,32 @@import { Property, createAction } from '@activepieces/pieces-framework';import { deepgramAuth } from '../common/auth';-import { BASE_URL } from '../common/constants';-import { deepgramModels } from '../common/models';-import { httpClient, HttpMethod } from '@activepieces/pieces-common';+import { deepgramProps } from '../common/props';+import { deepgramSpeech } from '../common/speech';+import { textToSpeechOutputSchema } from '../output-schemas';export const textToSpeechAction = createAction({auth: deepgramAuth,name: 'text_to_speech',classification: 'READ',displayName: 'Text to Speech',- description: 'Converts text to audio file.',- audience: 'both',+ description: 'Converts text (up to 2,000 characters) to an audio file.',+ audience: 'human',aiMetadata: {description:- 'Synthesizes speech from text using a Deepgram Aura voice and saves the result as an audio file in a chosen encoding (mp3 by default). Pick this only for generating spoken audio from text, the inverse of the transcription actions. Each run produces a newly generated, billed audio file, so it is not idempotent.',+ 'Synthesizes speech from text using a Deepgram Aura voice and saves the result as an audio file in a chosen encoding (mp3 by default). Pick this only for generating spoken audio from text, the inverse of the transcription actions. Each run produces a newly generated, billed audio file, so it is not idempotent. For agents: use Generate Speech.',idempotent: false,},+ outputSchema: textToSpeechOutputSchema,props: {text: Property.LongText({displayName: 'Text',+ description:+ 'Up to 2,000 characters. Split longer text into several steps.',required: true,}),- model: Property.Dropdown({- auth: deepgramAuth,- displayName: 'Voice',- required: false,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Enter your API key first',- options: [],- };- }- try {- const options = await deepgramModels.fetchTtsModelOptions({- apiKey: auth.secret_text,- });- return { disabled: false, options };- } catch (error) {- return {- disabled: true,- options: [],- placeholder:- "Couldn't load models, check your API key or try again.",- };- }- },+ model: deepgramProps.ttsVoice({+ description:+ 'Leave empty for aura-asteria-en. Aura-2 voices sound more natural and cover more languages.',}),encoding: Property.StaticDropdown({displayName: 'Output Format',@@ -66,30 +45,52 @@ export const textToSpeechAction = createAction({],},}),+ container: Property.StaticDropdown({+ displayName: 'Container',+ description:+ 'For linear16, mulaw and alaw only. WAV (default) adds a file header; None returns raw audio for telephony systems.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'WAV', value: 'wav' },+ { label: 'None (raw audio)', value: 'none' },+ ],+ },+ }),+ sampleRate: Property.Number({+ displayName: 'Sample Rate (Hz)',+ description:+ 'Optional. linear16: 8000-48000 (default 24000); mulaw/alaw: 8000 or 16000; flac: 8000-48000. Not used for mp3, opus or aac.',+ required: false,+ }),+ bitRate: Property.Number({+ displayName: 'Bit Rate (bps)',+ description:+ 'Optional. mp3: 32000 or 48000; opus: 4000-650000; aac: 4000-192000.',+ required: false,+ }),+ speed: Property.Number({+ displayName: 'Speed',+ description:+ 'Speaking rate from 0.5 to 1.5 (1 is normal). Not supported by every voice.',+ required: false,+ }),},async run(context) {- const { text, model = 'aura-asteria-en', encoding } = context.propsValue;-- const response = await httpClient.sendRequest({- method: HttpMethod.POST,- url: BASE_URL + '/speak',- body: { text },- headers: {- Authorization: `Token ${context.auth.secret_text}`,- 'Content-Type': 'application/json',- },- queryParams: {- model,- encoding: encoding || 'mp3',- },- responseType: 'arraybuffer',+ const { text, model, encoding, container, sampleRate, bitRate, speed } =+ context.propsValue;+ return deepgramSpeech.synthesize({+ apiKey: context.auth.secret_text,+ text,+ model: model?.trim() || 'aura-asteria-en',+ encoding,+ container,+ sampleRate,+ bitRate,+ speed,+ writeFile: ({ fileName, data }) =>+ context.files.write({ fileName, data }),});-- return {- file: await context.files.write({- fileName: `audio.${encoding}`,- data: Buffer.from(response.body),- }),- };},});diff --git a/packages/pieces/community/deepgram/src/actions/transcribe-audio.ts b/packages/pieces/community/deepgram/src/actions/transcribe-audio.tsnew file mode 100644index 00000000000..bc563a0ae46--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/transcribe-audio.ts@@ -0,0 +1,273 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { deepgramAudio } from '../common/audio';+import { deepgramAuth } from '../common/auth';+import { DEFAULT_STT_MODEL, REDACT_OPTIONS } from '../common/constants';+import { deepgramProps } from '../common/props';+import { deepgramTranscript } from '../common/transcript';+import { transcribeAudioOutputSchema } from '../output-schemas';++export const transcribeAudioAction = createAction({+ auth: deepgramAuth,+ name: 'transcribe_audio',+ classification: 'READ',+ displayName: 'Transcribe Audio',+ description:+ 'Transcribes an audio or video file or URL and returns the transcript, with optional speakers, paragraphs, summary, topics and more.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Transcribes speech from a public audio/video URL or an uploaded file with Deepgram and returns the full transcript, optionally with speaker labels, paragraphs, detected language, entities and an English-only summary, topics, intents and sentiment. Use for recordings that finish processing within about 8 minutes; for very long files use Create Transcription (Callback). Each call is billed per audio minute, so retries are billed again.',+ idempotent: false,+ },+ outputSchema: transcribeAudioOutputSchema,+ props: {+ audioUrl: Property.ShortText({+ displayName: 'Audio URL',+ description:+ 'A public link to the audio or video file. Deepgram downloads it directly. Use this or Audio File.',+ required: false,+ }),+ audioFile: Property.File({+ displayName: 'Audio File',+ description:+ 'The audio or video file to transcribe. Use this or Audio URL.',+ required: false,+ }),+ model: deepgramProps.sttModel({+ description: `Leave empty for ${DEFAULT_STT_MODEL}, Deepgram's recommended model for most languages.`,+ }),+ language: Property.ShortText({+ displayName: 'Language',+ description:+ 'Spoken language as a BCP-47 code, for example en, es, fr-CA or multi (several languages in one recording, nova-3 only). Leave empty for English, or turn on Detect Language.',+ required: false,+ }),+ detectLanguage: Property.Checkbox({+ displayName: 'Detect Language',+ description:+ 'Let Deepgram detect the main spoken language. Ignores Language.',+ required: false,+ defaultValue: false,+ }),+ smartFormat: Property.Checkbox({+ displayName: 'Smart Format',+ description:+ 'Add punctuation, capitals and readable numbers, dates and currency.',+ required: false,+ defaultValue: true,+ }),+ diarize: Property.Checkbox({+ displayName: 'Identify Speakers',+ description:+ 'Label who speaks when and return a transcript split by speaker.',+ required: false,+ defaultValue: false,+ }),+ paragraphs: Property.Checkbox({+ displayName: 'Paragraphs',+ description: 'Also return the transcript split into paragraphs.',+ required: false,+ defaultValue: false,+ }),+ utterances: Property.Checkbox({+ displayName: 'Utterances',+ description:+ 'Also return the transcript as timed segments (sentences or speaker turns).',+ required: false,+ defaultValue: false,+ }),+ multichannel: Property.Checkbox({+ displayName: 'Transcribe Each Channel Separately',+ description:+ 'For stereo recordings with one speaker per channel, such as call recordings. Billed per channel.',+ required: false,+ defaultValue: false,+ }),+ keyterms: Property.Array({+ displayName: 'Key Terms',+ description:+ 'Names, brands or jargon to recognize more reliably (nova-3 models only). Up to 100 terms.',+ required: false,+ }),+ redact: Property.StaticMultiSelectDropdown({+ displayName: 'Redact',+ description:+ 'Replace sensitive information in the transcript. Billed as an add-on.',+ required: false,+ options: { disabled: false, options: REDACT_OPTIONS },+ }),+ detectEntities: Property.Checkbox({+ displayName: 'Detect Entities',+ description:+ 'Return names, organizations, places, numbers and other entities found in the speech.',+ required: false,+ defaultValue: false,+ }),+ summarize: Property.Checkbox({+ displayName: 'Summarize (English)',+ description:+ 'Return a short summary. English audio only; needs more than about 50 spoken words.',+ required: false,+ defaultValue: false,+ }),+ topics: Property.Checkbox({+ displayName: 'Detect Topics (English)',+ required: false,+ defaultValue: false,+ }),+ intents: Property.Checkbox({+ displayName: 'Detect Intents (English)',+ required: false,+ defaultValue: false,+ }),+ sentiment: Property.Checkbox({+ displayName: 'Analyze Sentiment (English)',+ required: false,+ defaultValue: false,+ }),+ includeWords: Property.Checkbox({+ displayName: 'Include Word Timings',+ description:+ 'Return every word with its start and end time. Makes the output much larger.',+ required: false,+ defaultValue: false,+ }),+ tags: Property.Array({+ displayName: 'Tags',+ description:+ 'Labels for this request that show up in Deepgram usage reports.',+ required: false,+ }),+ },+ async run(context) {+ return transcribeAudio({+ apiKey: context.auth.secret_text,+ input: context.propsValue,+ });+ },+});++export async function transcribeAudio({+ apiKey,+ input,+}: {+ apiKey: string;+ input: TranscribeAudioInput;+}) {+ const props = input;+ const model = props.model?.trim() || DEFAULT_STT_MODEL;+ const language = props.language?.trim() || undefined;+ const detectLanguage = props.detectLanguage === true;+ const intelligence =+ props.summarize === true ||+ props.topics === true ||+ props.intents === true ||+ props.sentiment === true;+ if (intelligence && !detectLanguage && !deepgramAudio.isEnglish(language)) {+ throw new Error(+ 'Summary, topics, intents and sentiment only work on English audio. Clear the Language field or turn these options off.'+ );+ }+ const keyterms = textList({+ value: props.keyterms,+ label: 'Key Terms',+ max: 100,+ });+ if (keyterms.length > 0 && !model.startsWith('nova-3')) {+ throw new Error(+ 'Key Terms only work with nova-3 models. Choose a nova-3 model or remove the key terms.'+ );+ }+ const redact = textList({ value: props.redact, label: 'Redact', max: 4 });+ const unknownRedact = redact.filter(+ (item) => !['pci', 'pii', 'phi', 'numbers'].includes(item)+ );+ if (unknownRedact.length > 0) {+ throw new Error(+ `Unknown redaction type: ${unknownRedact.join(+ ', '+ )}. Use pci, pii, phi or numbers.`+ );+ }+ const tags = textList({ value: props.tags, label: 'Tags', max: 20 });+ const source = deepgramAudio.resolveSource({+ audioUrl: props.audioUrl,+ audioFile: props.audioFile,+ fallbackContentType: 'application/octet-stream',+ });+ const body = await deepgramAudio.listen({+ apiKey: apiKey,+ source,+ query: {+ model,+ language: detectLanguage ? undefined : language,+ detect_language: detectLanguage ? 'true' : undefined,+ smart_format: props.smartFormat === false ? undefined : 'true',+ diarize_model: props.diarize === true ? 'latest' : undefined,+ paragraphs: props.paragraphs === true ? 'true' : undefined,+ utterances: props.utterances === true ? 'true' : undefined,+ multichannel: props.multichannel === true ? 'true' : undefined,+ detect_entities: props.detectEntities === true ? 'true' : undefined,+ summarize: props.summarize === true ? 'v2' : undefined,+ topics: props.topics === true ? 'true' : undefined,+ intents: props.intents === true ? 'true' : undefined,+ sentiment: props.sentiment === true ? 'true' : undefined,+ keyterm: keyterms,+ redact,+ tag: tags,+ },+ operation: 'transcribe the audio',+ });+ return deepgramTranscript.flattenListen({+ body,+ includeWords: props.includeWords === true,+ });+}++function textList({+ value,+ label,+ max,+}: {+ value: unknown;+ label: string;+ max: number;+}): string[] {+ if (value === undefined || value === null || value === '') {+ return [];+ }+ const items = Array.isArray(value) ? value : [value];+ const texts = items+ .map((item) =>+ typeof item === 'string' || typeof item === 'number'+ ? String(item).trim()+ : ''+ )+ .filter((item) => item.length > 0);+ if (texts.length > max) {+ throw new Error(`${label} accepts at most ${max} values.`);+ }+ return texts;+}++export type TranscribeAudioInput = {+ audioUrl?: string;+ audioFile?: unknown;+ model?: string;+ language?: string;+ detectLanguage?: boolean;+ smartFormat?: boolean;+ diarize?: boolean;+ paragraphs?: boolean;+ utterances?: boolean;+ multichannel?: boolean;+ keyterms?: unknown[];+ redact?: string[];+ detectEntities?: boolean;+ summarize?: boolean;+ topics?: boolean;+ intents?: boolean;+ sentiment?: boolean;+ includeWords?: boolean;+ tags?: unknown[];+};diff --git a/packages/pieces/community/deepgram/src/actions/update-project.ts b/packages/pieces/community/deepgram/src/actions/update-project.tsnew file mode 100644index 00000000000..714bae88772--- /dev/null+++ b/packages/pieces/community/deepgram/src/actions/update-project.ts@@ -0,0 +1,54 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { deepgramAuth } from '../common/auth';+import { DEEPGRAM_TIMEOUTS, deepgramClient } from '../common/client';+import { deepgramProjects } from '../common/projects';+import { deepgramProps } from '../common/props';+import { updateProjectOutputSchema } from '../output-schemas';++export const updateProjectAction = createAction({+ auth: deepgramAuth,+ name: 'update_project',+ classification: 'WRITE',+ displayName: 'Rename Project',+ description: 'Changes the name of a Deepgram project.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Renames a Deepgram project and returns the project as stored afterwards. Only the name changes. Setting the same name again changes nothing, so it is idempotent. May require an owner API key, since changing project settings is owner-only.',+ idempotent: true,+ },+ outputSchema: updateProjectOutputSchema,+ props: {+ project: deepgramProps.project(),+ name: Property.ShortText({+ displayName: 'New Name',+ description: 'The new name of the project.',+ required: true,+ }),+ },+ async run(context) {+ const apiKey = context.auth.secret_text;+ const name = (context.propsValue.name ?? '').trim();+ if (name.length === 0) {+ throw new Error('Enter a new name for the project.');+ }+ const projectId = await deepgramProjects.resolveProjectId({+ apiKey,+ project: context.propsValue.project,+ });+ const response = await deepgramClient.request<{ message?: string }>({+ apiKey,+ method: HttpMethod.PATCH,+ path: deepgramProjects.projectPath({ projectId }),+ body: { name },+ timeoutMs: DEEPGRAM_TIMEOUTS.manage,+ operation: 'rename the project',+ });+ const project = await deepgramProjects.getProject({ apiKey, projectId });+ return {+ ...project,+ message: response.body?.message ?? null,+ };+ },+});diff --git a/packages/pieces/community/deepgram/src/common/audio.ts b/packages/pieces/community/deepgram/src/common/audio.tsnew file mode 100644index 00000000000..448b4958924--- /dev/null+++ b/packages/pieces/community/deepgram/src/common/audio.ts@@ -0,0 +1,183 @@+import { HttpMethod } from '@activepieces/pieces-common';+import mime from 'mime-types';+import {+ DEEPGRAM_TIMEOUTS,+ deepgramClient,+ LONG_AUDIO_HINT,+ QueryInput,+} from './client';+import { ListenResponse } from './transcript';++const CALLBACK_PORTS = ['', '80', '443', '8080', '8443'];++function fileBytes(file: unknown): Buffer | null {+ if (file === null || typeof file !== 'object') {+ return null;+ }+ const data = Reflect.get(file, 'data');+ if (Buffer.isBuffer(data)) {+ return data;+ }+ const base64 = Reflect.get(file, 'base64');+ return typeof base64 === 'string' && base64.length > 0+ ? Buffer.from(base64, 'base64')+ : null;+}++function fileContentType({+ file,+ fallback,+}: {+ file: unknown;+ fallback: string;+}): string {+ if (file === null || typeof file !== 'object') {+ return fallback;+ }+ const extension = Reflect.get(file, 'extension');+ const filename = Reflect.get(file, 'filename');+ const lookupKey =+ typeof extension === 'string' && extension.length > 0+ ? extension+ : typeof filename === 'string'+ ? filename+ : '';+ const type = lookupKey ? mime.lookup(lookupKey) : false;+ return type || fallback;+}++function checkPublicUrl({+ value,+ label,+}: {+ value: string;+ label: string;+}): string {+ let parsed: URL;+ try {+ parsed = new URL(value);+ } catch {+ throw new Error(+ `${label} must be a full URL starting with https:// or http://.`+ );+ }+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {+ throw new Error(`${label} must start with https:// or http://.`);+ }+ return value;+}++function resolveSource({+ audioUrl,+ audioFile,+ fallbackContentType,+}: {+ audioUrl: unknown;+ audioFile: unknown;+ fallbackContentType: string;+}): AudioSource {+ const url = typeof audioUrl === 'string' ? audioUrl.trim() : '';+ const hasFile =+ audioFile !== undefined && audioFile !== null && audioFile !== '';+ if (url.length > 0 && hasFile) {+ throw new Error('Provide either an audio URL or an audio file, not both.');+ }+ if (url.length > 0) {+ return {+ kind: 'url',+ url: checkPublicUrl({ value: url, label: 'Audio URL' }),+ };+ }+ if (!hasFile) {+ throw new Error('Provide an audio URL or an audio file to transcribe.');+ }+ const data = fileBytes(audioFile);+ if (!data || data.length === 0) {+ throw new Error('The audio file is empty or could not be read.');+ }+ return {+ kind: 'file',+ data,+ contentType: fileContentType({+ file: audioFile,+ fallback: fallbackContentType,+ }),+ };+}++function checkCallbackUrl(value: unknown): string {+ const text = typeof value === 'string' ? value.trim() : '';+ if (text.length === 0) {+ throw new Error(+ 'Enter the callback URL that should receive the transcript.'+ );+ }+ let parsed: URL;+ try {+ parsed = new URL(text);+ } catch {+ throw new Error(+ 'The callback URL must be a full URL starting with https:// or http://.'+ );+ }+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {+ throw new Error('The callback URL must start with https:// or http://.');+ }+ if (!CALLBACK_PORTS.includes(parsed.port)) {+ throw new Error(+ `Deepgram only calls back on ports 80, 443, 8080 or 8443, and this URL uses port ${parsed.port}.`+ );+ }+ return text;+}++async function listen({+ apiKey,+ source,+ query,+ operation,+}: {+ apiKey: string;+ source: AudioSource;+ query: QueryInput;+ operation: string;+}): Promise<ListenResponse> {+ const response = await deepgramClient.request<ListenResponse>({+ apiKey,+ method: HttpMethod.POST,+ path: '/listen',+ query,+ body:+ source.kind === 'url'+ ? { url: source.url }+ : deepgramClient.audioUploadBody(source.data),+ headers:+ source.kind === 'file'+ ? { 'Content-Type': source.contentType }+ : undefined,+ timeoutMs: DEEPGRAM_TIMEOUTS.listen,+ operation,+ timeoutHint: LONG_AUDIO_HINT,+ });+ return response.body ?? {};+}++function isEnglish(language: string | undefined | null): boolean {+ if (!language) {+ return true;+ }+ const lower = language.trim().toLowerCase();+ return lower === '' || lower === 'en' || lower.startsWith('en-');+}++export const deepgramAudio = {+ resolveSource,+ checkCallbackUrl,+ listen,+ isEnglish,+ fileBytes,+};++export type AudioSource =+ | { kind: 'url'; url: string }+ | { kind: 'file'; data: Buffer; contentType: string };diff --git a/packages/pieces/community/deepgram/src/common/auth.ts b/packages/pieces/community/deepgram/src/common/auth.tsindex 6c995d03484..75d1764f6d9 100644--- a/packages/pieces/community/deepgram/src/common/auth.ts+++ b/packages/pieces/community/deepgram/src/common/auth.ts@@ -1,6 +1,6 @@-import { httpClient, HttpMethod } from '@activepieces/pieces-common';+import { HttpMethod } from '@activepieces/pieces-common';import { PieceAuth } from '@activepieces/pieces-framework';-import { BASE_URL } from './constants';+import { DEEPGRAM_TIMEOUTS, DeepgramApiError, deepgramClient } from './client';export const deepgramAuth = PieceAuth.SecretText({displayName: 'API Key',@@ -8,16 +8,26 @@ export const deepgramAuth = PieceAuth.SecretText({description: `You can obtain your API key from [Deepgram Console](https://console.deepgram.com/).`,validate: async ({ auth }) => {try {- await httpClient.sendRequest({+ await deepgramClient.request({+ apiKey: auth,method: HttpMethod.GET,- url: BASE_URL + '/projects',- headers: {- Authorization: `Token ${auth}`,- },+ path: '/projects',+ timeoutMs: DEEPGRAM_TIMEOUTS.manage,+ operation: 'check the API key',});return { valid: true };} catch (e) {- return { valid: false, error: 'Invalid API key.' };+ if (+ e instanceof DeepgramApiError &&+ (e.status === 401 || e.status === 403)+ ) {+ return { valid: false, error: 'Invalid API key.' };+ }+ const status = e instanceof DeepgramApiError ? ` (HTTP ${e.status})` : '';+ return {+ valid: false,+ error: `Could not reach Deepgram to check the API key${status}. Try again in a moment.`,+ };}},});diff --git a/packages/pieces/community/deepgram/src/common/client.ts b/packages/pieces/community/deepgram/src/common/client.tsnew file mode 100644index 00000000000..7f26abd87c9--- /dev/null+++ b/packages/pieces/community/deepgram/src/common/client.ts@@ -0,0 +1,391 @@+import { Readable } from 'node:stream';+import { httpClient, HttpMethod } from '@activepieces/pieces-common';+import { BASE_URL } from './constants';++const MAX_VENDOR_TEXT = 500;+const UPLOAD_CHUNK_BYTES = 64 * 1024;++let verifiedTlsAgent: Promise<unknown> | undefined;++function verifiedTls(): Promise<unknown> {+ verifiedTlsAgent ??= import('undici').then(+ ({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } })+ );+ return verifiedTlsAgent;+}++function authHeader(apiKey: string): Record<string, string> {+ return { Authorization: `Token ${apiKey.trim()}` };+}++export class DeepgramApiError extends Error {+ readonly status: number;+ readonly code: string | undefined;+ readonly requestId: string | undefined;+ readonly responseBody: unknown;++ constructor({+ operation,+ status,+ responseBody,+ hint,+ }: {+ operation: string;+ status: number;+ responseBody: unknown;+ hint?: string;+ }) {+ const code = errorCode(responseBody);+ const vendor = maskUrlCredentials(vendorText(responseBody));+ const parts = [+ `Deepgram could not ${operation} (HTTP ${status}${+ code ? ` ${code}` : ''+ })`,+ ];+ const detail = vendor ? `: ${vendor}` : '.';+ const help = hint ?? statusHint(status);+ const requestId = requestIdOf(responseBody);+ super(+ `${parts[0]}${detail}${help ? ` ${help}` : ''}${+ requestId ? ` Deepgram request ID: ${requestId}.` : ''+ }`+ );+ this.name = 'DeepgramApiError';+ this.status = status;+ this.code = code;+ this.requestId = requestId;+ this.responseBody = responseBody;+ }+}++async function request<T>({+ apiKey,+ method,+ path,+ query,+ body,+ headers,+ responseType,+ timeoutMs,+ operation,+ timeoutHint,+ baseUrl,+}: DeepgramRequestParams): Promise<DeepgramResponse<T>> {+ const url = buildUrl({ path, query, baseUrl });+ try {+ const dispatcher = await verifiedTls();+ const response = await httpClient.sendRequest<T>(+ {+ method,+ url,+ headers: {+ ...authHeader(apiKey),+ Accept: 'application/json',+ ...(body !== undefined && !(body instanceof Readable)+ ? { 'Content-Type': 'application/json' }+ : {}),+ ...headers,+ },+ body,+ responseType: responseType ?? 'json',+ timeout: timeoutMs,+ followRedirects: false,+ },+ { dispatcher }+ );+ if (response.status >= 300) {+ throw new DeepgramApiError({+ operation,+ status: response.status,+ responseBody: 'Deepgram answered with an unexpected redirect.',+ });+ }+ return {+ status: response.status,+ headers: response.headers ?? {},+ body: response.body,+ };+ } catch (error) {+ if (error instanceof DeepgramApiError) {+ throw error;+ }+ const status = statusOf(error);+ if (status !== undefined) {+ throw new DeepgramApiError({+ operation,+ status,+ responseBody: decodeBody(responseBodyOf(error)),+ hint: status === 504 && timeoutHint ? timeoutHint : undefined,+ });+ }+ if (isAbort(error)) {+ throw new Error(+ `Deepgram did not answer within ${Math.round(+ timeoutMs / 1000+ )} seconds while trying to ${operation}.${+ timeoutHint ? ` ${timeoutHint}` : ''+ }`+ );+ }+ throw error;+ }+}++function buildUrl({+ path,+ query,+ baseUrl,+}: {+ path: string;+ query?: QueryInput;+ baseUrl?: string;+}): string {+ const params = new URLSearchParams();+ for (const [key, value] of Object.entries(query ?? {})) {+ if (value === undefined || value === null) {+ continue;+ }+ const values = Array.isArray(value) ? value : [value];+ for (const item of values) {+ const text = String(item);+ if (text.length > 0) {+ params.append(key, text);+ }+ }+ }+ const search = params.toString();+ return `${baseUrl ?? BASE_URL}${path}${search ? `?${search}` : ''}`;+}++function audioUploadBody(data: Buffer): Readable {+ const size = data.length;+ function* chunks() {+ for (let offset = 0; offset < size; offset += UPLOAD_CHUNK_BYTES) {+ yield data.subarray(offset, Math.min(offset + UPLOAD_CHUNK_BYTES, size));+ }+ }+ const stream = Readable.from(chunks());+ Object.defineProperty(stream, 'toJSON', {+ value: () => `[audio upload, ${size} bytes]`,+ enumerable: false,+ });+ return stream;+}++function maskUrlCredentials(value: string): string {+ return maskAuthorities(maskParsedUrl(value));+}++function maskParsedUrl(value: string): string {+ let url: URL;+ try {+ url = new URL(value);+ } catch {+ return value;+ }+ if (url.username === '' && url.password === '') {+ return value;+ }+ url.username = '***';+ url.password = '';+ return url.toString();+}++function maskAuthorities(value: string): string {+ return URL_SCHEME_FORMS.reduce(+ (text, form) =>+ text.replace(+ form.authority,+ (match, scheme: string, authority: string) => {+ const at = authority.toLowerCase().lastIndexOf(form.at);+ return at < 0 ? match : `${scheme}***${authority.slice(at)}`;+ }+ ),+ value+ );+}++const URL_SCHEME_FORMS = [+ { authority: /(:\/\/)([^/?#\s"'<>]*)/g, at: '@' },+ {+ authority: /(%3A%2F%2F)((?:(?!%2F|%3F|%23)[^&\s"'<>])*)/gi,+ at: '%40',+ },+];++function maskOptional(value: unknown): string | null {+ return typeof value === 'string' ? maskUrlCredentials(value) : null;+}++function vendorText(responseBody: unknown): string {+ if (typeof responseBody === 'string') {+ return truncate(responseBody.trim());+ }+ if (!isRecord(responseBody)) {+ return '';+ }+ const pieces = [+ responseBody['err_msg'],+ responseBody['message'],+ responseBody['details'],+ ].filter(+ (item, index, all): item is string =>+ typeof item === 'string' && item.length > 0 && all.indexOf(item) === index+ );+ return truncate(pieces.join(' - '));+}++function errorCode(responseBody: unknown): string | undefined {+ if (!isRecord(responseBody)) {+ return undefined;+ }+ const code = responseBody['err_code'] ?? responseBody['category'];+ return typeof code === 'string' && code.length > 0 ? code : undefined;+}++function requestIdOf(responseBody: unknown): string | undefined {+ if (!isRecord(responseBody)) {+ return undefined;+ }+ const id = responseBody['request_id'];+ return typeof id === 'string' ? id : undefined;+}++function statusHint(status: number): string | undefined {+ if (status === 401) {+ return 'Check that the API key is correct and has permission for this action.';+ }+ if (status === 403) {+ return "This API key's role or scopes do not allow this action. Use a key with the Member, Admin or Owner role; members, keys, balances and costs need Admin or Owner.";+ }+ if (status === 402) {+ return 'The Deepgram project is out of credit. Add funds or a card in the Deepgram Console.';+ }+ if (status === 404) {+ return 'Check the project or request ID.';+ }+ if (status === 413) {+ return 'The input is too large for Deepgram.';+ }+ if (status === 429) {+ return 'Deepgram rate limit reached. Wait a moment and try again.';+ }+ if (status === 504) {+ return 'Deepgram took too long to process the request.';+ }+ if (status >= 500) {+ return 'Deepgram had a server error. Try again later.';+ }+ return undefined;+}++function truncate(text: string): string {+ return text.length > MAX_VENDOR_TEXT+ ? `${text.slice(0, MAX_VENDOR_TEXT)}...`+ : text;+}++function statusOf(error: unknown): number | undefined {+ if (!isRecord(error)) {+ return undefined;+ }+ const response = Reflect.get(error, 'response');+ if (!isRecord(response)) {+ return undefined;+ }+ const status = response['status'];+ return typeof status === 'number' ? status : undefined;+}++function responseBodyOf(error: unknown): unknown {+ if (!isRecord(error)) {+ return undefined;+ }+ const response = Reflect.get(error, 'response');+ return isRecord(response) ? response['body'] : undefined;+}++function decodeBody(body: unknown): unknown {+ const text = bytesToText(body) ?? (typeof body === 'string' ? body : null);+ if (text === null) {+ return body;+ }+ try {+ const parsed: unknown = JSON.parse(text);+ return isRecord(parsed) ? parsed : text;+ } catch {+ return text;+ }+}++function bytesToText(body: unknown): string | null {+ if (Buffer.isBuffer(body)) {+ return body.toString('utf8');+ }+ if (body instanceof ArrayBuffer) {+ return Buffer.from(body).toString('utf8');+ }+ if (ArrayBuffer.isView(body)) {+ return Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString(+ 'utf8'+ );+ }+ return null;+}++function isAbort(error: unknown): boolean {+ if (!isRecord(error)) {+ return false;+ }+ const name = Reflect.get(error, 'name');+ return name === 'AbortError' || name === 'TimeoutError';+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++export const deepgramClient = {+ request,+ authHeader,+ buildUrl,+ audioUploadBody,+ maskUrlCredentials,+ maskOptional,+ vendorText,+ isRecord,+};++export const DEEPGRAM_TIMEOUTS = {+ listen: 480_000,+ speak: 120_000,+ read: 120_000,+ manage: 30_000,+};++export const LONG_AUDIO_HINT =+ 'Use Create Transcription (Callback) for recordings that take longer to process.';++type QueryValue = string | number | boolean | undefined | null;++export type QueryInput = Record<string, QueryValue | QueryValue[]>;++export type DeepgramRequestParams = {+ apiKey: string;+ method: HttpMethod;+ path: string;+ query?: QueryInput;+ body?: unknown;+ headers?: Record<string, string>;+ responseType?: 'json' | 'arraybuffer';+ timeoutMs: number;+ operation: string;+ timeoutHint?: string;+ baseUrl?: string;+};++export type DeepgramResponse<T> = {+ status: number;+ headers: Record<string, string | string[] | undefined>;+ body: T;+};diff --git a/packages/pieces/community/deepgram/src/common/constants.ts b/packages/pieces/community/deepgram/src/common/constants.tsindex 4ecc44d6606..32e799b6597 100644--- a/packages/pieces/community/deepgram/src/common/constants.ts+++ b/packages/pieces/community/deepgram/src/common/constants.ts@@ -1,4 +1,5 @@export const BASE_URL = 'https://api.deepgram.com/v1';+export const AGENT_BASE_URL = 'https://agent.deepgram.com/v1';export const LANG_OPTIONS = [{ label: 'bg', value: 'bg' },@@ -58,3 +59,26 @@ export const LANG_OPTIONS = [{ label: 'uk', value: 'uk' },{ label: 'vi', value: 'vi' },];++export const DEFAULT_STT_MODEL = 'nova-3';++export const DEFAULT_AI_VOICE = 'aura-2-thalia-en';++export const MAX_TTS_CHARACTERS = 2000;++export const TTS_ENCODING_OPTIONS = [+ { label: 'MP3', value: 'mp3' },+ { label: 'Linear PCM 16-bit (WAV)', value: 'linear16' },+ { label: 'FLAC', value: 'flac' },+ { label: 'μ-law (WAV)', value: 'mulaw' },+ { label: 'A-law (WAV)', value: 'alaw' },+ { label: 'Opus (OGG)', value: 'opus' },+ { label: 'AAC', value: 'aac' },+];++export const REDACT_OPTIONS = [+ { label: 'Payment card data (PCI)', value: 'pci' },+ { label: 'Personal information (PII)', value: 'pii' },+ { label: 'Health information (PHI)', value: 'phi' },+ { label: 'Numbers', value: 'numbers' },+];diff --git a/packages/pieces/community/deepgram/src/common/models.ts b/packages/pieces/community/deepgram/src/common/models.tsindex 5dc7c1d4e35..dcf38b748ed 100644--- a/packages/pieces/community/deepgram/src/common/models.ts+++ b/packages/pieces/community/deepgram/src/common/models.ts@@ -1,28 +1,153 @@-import { httpClient, HttpMethod } from '@activepieces/pieces-common';-import { BASE_URL } from './constants';+import { HttpMethod } from '@activepieces/pieces-common';+import { DEEPGRAM_TIMEOUTS, deepgramClient } from './client';async function fetchModels({apiKey,+ projectId,+ includeOutdated,}: {apiKey: string;+ projectId?: string;+ includeOutdated?: boolean;}): Promise<ModelsResponse> {- const response = await httpClient.sendRequest<ModelsResponse>({+ const response = await deepgramClient.request<ModelsResponse>({+ apiKey,method: HttpMethod.GET,- url: BASE_URL + '/models',- headers: {- Authorization: `Token ${apiKey}`,- },+ path: projectId+ ? `/projects/${encodeURIComponent(projectId)}/models`+ : '/models',+ query: { include_outdated: includeOutdated ? 'true' : undefined },+ timeoutMs: DEEPGRAM_TIMEOUTS.manage,+ operation: 'list models',});- return response.body;+ return response.body ?? {};}-function toOptions({ models }: { models: DeepgramModel[] }): ModelOption[] {- return models- .map((model) => ({- label: model.canonical_name,- value: model.canonical_name,- }))- .sort((a, b) => a.label.localeCompare(b.label));+function dedupe({ models }: { models: DeepgramModel[] }): DeepgramModel[] {+ const byName = new Map<string, DeepgramModel>();+ for (const model of models) {+ if (!isUsable(model)) {+ continue;+ }+ const existing = byName.get(model.canonical_name);+ byName.set(+ model.canonical_name,+ existing ? merge({ current: existing, next: model }) : model+ );+ }+ return [...byName.values()];+}++function merge({+ current,+ next,+}: {+ current: DeepgramModel;+ next: DeepgramModel;+}): DeepgramModel {+ const newer =+ (next.version ?? '').localeCompare(current.version ?? '') > 0+ ? next+ : current;+ return {+ ...newer,+ languages: [+ ...new Set([...(current.languages ?? []), ...(next.languages ?? [])]),+ ],+ batch: Boolean(current.batch) || Boolean(next.batch),+ streaming: Boolean(current.streaming) || Boolean(next.streaming),+ };+}++function isUsable(model: DeepgramModel): boolean {+ const name = model.canonical_name;+ if (typeof name !== 'string' || name.length === 0) {+ return false;+ }+ return name !== 'phoneme' && !name.includes('dQw4w9WgXcQ');+}++function sttRank(name: string): number {+ if (name.startsWith('nova-3')) {+ return 0;+ }+ if (name.startsWith('nova-2')) {+ return 1;+ }+ return 2;+}++function sortStt(models: DeepgramModel[]): DeepgramModel[] {+ return [...models].sort(+ (a, b) =>+ sttRank(a.canonical_name) - sttRank(b.canonical_name) ||+ a.canonical_name.localeCompare(b.canonical_name)+ );+}++function sortTts(models: DeepgramModel[]): DeepgramModel[] {+ return [...models].sort(+ (a, b) =>+ ttsRank(a) - ttsRank(b) ||+ a.canonical_name.localeCompare(b.canonical_name)+ );+}++function ttsRank(model: DeepgramModel): number {+ return model.architecture === 'aura-2' ? 0 : 1;+}++function sttLabel(model: DeepgramModel): string {+ return model.architecture && model.architecture !== 'unknown'+ ? `${model.canonical_name} (${model.architecture})`+ : model.canonical_name;+}++function ttsLabel(model: DeepgramModel): string {+ const metadata = model.metadata ?? {};+ const name = metadata.display_name ?? capitalize(model.name ?? '');+ const family = model.architecture === 'aura-2' ? 'Aura-2' : 'Aura';+ const language = (model.languages ?? [])[0];+ const accent = metadata.accent;+ const gender = genderOf(model);+ const details = [+ family,+ language ? `${language}${accent ? ` (${accent})` : ''}` : accent,+ gender,+ ].filter(+ (item): item is string => typeof item === 'string' && item.length > 0+ );+ return name+ ? `${name} - ${details.join(', ')} [${model.canonical_name}]`+ : model.canonical_name;+}++function genderOf(model: DeepgramModel): string | null {+ const tags = model.metadata?.tags ?? [];+ if (tags.includes('feminine')) {+ return 'feminine';+ }+ if (tags.includes('masculine')) {+ return 'masculine';+ }+ return null;+}++function capitalize(text: string): string {+ return text.length > 0 ? text[0].toUpperCase() + text.slice(1) : text;+}++function toSttOptions({ models }: { models: DeepgramModel[] }): ModelOption[] {+ return sortStt(dedupe({ models }).filter((model) => model.batch)).map(+ (model) => ({ label: sttLabel(model), value: model.canonical_name })+ );+}++function toTtsOptions({ models }: { models: DeepgramModel[] }): ModelOption[] {+ return sortTts(dedupe({ models })).map((model) => ({+ label: ttsLabel(model),+ value: model.canonical_name,+ }));}async function fetchSttModelOptions({@@ -31,7 +156,7 @@ async function fetchSttModelOptions({apiKey: string;}): Promise<ModelOption[]> {const body = await fetchModels({ apiKey });- return toOptions({ models: body.stt ?? [] });+ return toSttOptions({ models: body.stt ?? [] });}async function fetchTtsModelOptions({@@ -40,14 +165,192 @@ async function fetchTtsModelOptions({apiKey: string;}): Promise<ModelOption[]> {const body = await fetchModels({ apiKey });- return toOptions({ models: body.tts ?? [] });+ return toTtsOptions({ models: body.tts ?? [] });}-export const deepgramModels = { fetchSttModelOptions, fetchTtsModelOptions };+function flattenModel({+ model,+ type,+}: {+ model: DeepgramModel;+ type: 'stt' | 'tts';+}): FlatModel {+ const metadata = model.metadata ?? {};+ return {+ canonical_name: model.canonical_name,+ type,+ name:+ type === 'tts'+ ? metadata.display_name ?? model.name ?? null+ : model.name ?? null,+ architecture: model.architecture ?? null,+ languages: (model.languages ?? []).join(', '),+ version: model.version ?? null,+ batch: type === 'stt' ? Boolean(model.batch) : null,+ streaming: type === 'stt' ? Boolean(model.streaming) : null,+ accent: metadata.accent ?? null,+ age: metadata.age ?? null,+ gender: genderOf(model),+ voice_tags: (metadata.tags ?? []).join(', '),+ sample_url: metadata.sample ?? null,+ };+}++function matchesLanguage({+ model,+ language,+}: {+ model: DeepgramModel;+ language: string;+}): boolean {+ const wanted = language.toLowerCase();+ return (model.languages ?? []).some((tag) => {+ const lower = tag.toLowerCase();+ return lower === wanted || lower.startsWith(`${wanted}-`);+ });+}++async function listModels({+ apiKey,+ projectId,+ type,+ language,+ includeOutdated,+}: {+ apiKey: string;+ projectId?: string;+ type: 'stt' | 'tts' | 'all';+ language?: string;+ includeOutdated?: boolean;+}): Promise<FlatModel[]> {+ const body = await fetchModels({ apiKey, projectId, includeOutdated });+ const wantedLanguage = language?.trim();+ const pick = (models: DeepgramModel[]) =>+ wantedLanguage+ ? models.filter((model) =>+ matchesLanguage({ model, language: wantedLanguage })+ )+ : models;+ const stt =+ type === 'tts'+ ? []+ : pick(sortStt(dedupe({ models: body.stt ?? [] }))).map((model) =>+ flattenModel({ model, type: 'stt' })+ );+ const tts =+ type === 'stt'+ ? []+ : pick(sortTts(dedupe({ models: body.tts ?? [] }))).map((model) =>+ flattenModel({ model, type: 'tts' })+ );+ return [...stt, ...tts];+}++async function listModelBuilds({+ apiKey,+ projectId,+ type,+ language,+ includeOutdated,+}: {+ apiKey: string;+ projectId?: string;+ type: 'stt' | 'tts' | 'all';+ language?: string;+ includeOutdated?: boolean;+}): Promise<FlatModelBuild[]> {+ const body = await fetchModels({ apiKey, projectId, includeOutdated });+ const wantedLanguage = language?.trim();+ const pick = (models: DeepgramModel[]) =>+ models+ .filter((model) => isUsable(model))+ .filter(+ (model) =>+ !wantedLanguage ||+ matchesLanguage({ model, language: wantedLanguage })+ );+ const stt =+ type === 'tts'+ ? []+ : sortStt(pick(body.stt ?? [])).map((model) =>+ flattenBuild({ model, type: 'stt' })+ );+ const tts =+ type === 'stt'+ ? []+ : sortTts(pick(body.tts ?? [])).map((model) =>+ flattenBuild({ model, type: 'tts' })+ );+ return [...stt, ...tts];+}++function flattenBuild({+ model,+ type,+}: {+ model: DeepgramModel;+ type: 'stt' | 'tts';+}): FlatModelBuild {+ return { uuid: model.uuid ?? '', ...flattenModel({ model, type }) };+}++async function getModel({+ apiKey,+ projectId,+ modelId,+}: {+ apiKey: string;+ projectId?: string;+ modelId: string;+}): Promise<FlatModelBuild> {+ const id = encodeURIComponent(modelId);+ const response = await deepgramClient.request<DeepgramModel>({+ apiKey,+ method: HttpMethod.GET,+ path: projectId+ ? `/projects/${encodeURIComponent(projectId)}/models/${id}`+ : `/models/${id}`,+ timeoutMs: DEEPGRAM_TIMEOUTS.manage,+ operation: 'get the model',+ });+ const model = response.body ?? { canonical_name: '' };+ const type =+ model.metadata !== undefined || /^aura/.test(model.canonical_name ?? '')+ ? 'tts'+ : 'stt';+ return {+ ...flattenBuild({ model, type }),+ uuid: model.uuid ?? modelId,+ canonical_name: model.canonical_name ?? '',+ };+}++export const deepgramModels = {+ listModelBuilds,+ getModel,+ fetchSttModelOptions,+ fetchTtsModelOptions,+ toSttOptions,+ toTtsOptions,+ listModels,+};type DeepgramModel = {- name: string;+ uuid?: string;+ name?: string;canonical_name: string;+ architecture?: string;+ languages?: string[];+ version?: string;+ batch?: boolean;+ streaming?: boolean;+ metadata?: {+ accent?: string | null;+ age?: string | null;+ display_name?: string | null;+ sample?: string | null;+ tags?: string[];+ };};type ModelsResponse = {@@ -59,3 +362,21 @@ type ModelOption = {label: string;value: string;};++export type FlatModel = {+ canonical_name: string;+ type: 'stt' | 'tts';+ name: string | null;+ architecture: string | null;+ languages: string;+ version: string | null;+ batch: boolean | null;+ streaming: boolean | null;+ accent: string | null;+ age: string | null;+ gender: string | null;+ voice_tags: string;+ sample_url: string | null;+};++export type FlatModelBuild = FlatModel & { uuid: string };diff --git a/packages/pieces/community/deepgram/src/common/projects.ts b/packages/pieces/community/deepgram/src/common/projects.tsnew file mode 100644index 00000000000..3f7098dbc22--- /dev/null+++ b/packages/pieces/community/deepgram/src/common/projects.ts@@ -0,0 +1,111 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { DEEPGRAM_TIMEOUTS, deepgramClient } from './client';++async function listProjects({+ apiKey,+}: {+ apiKey: string;+}): Promise<DeepgramProject[]> {+ const response = await deepgramClient.request<ProjectsResponse>({+ apiKey,+ method: HttpMethod.GET,+ path: '/projects',+ timeoutMs: DEEPGRAM_TIMEOUTS.manage,+ operation: 'list projects',+ });+ return response.body?.projects ?? [];+}++async function resolveProjectId({+ apiKey,+ project,+}: {+ apiKey: string;+ project: string | undefined | null;+}): Promise<string> {+ const chosen = typeof project === 'string' ? project.trim() : '';+ if (chosen.length > 0) {+ return chosen;+ }+ const projects = await listProjects({ apiKey });+ if (projects.length === 1) {+ return projects[0].project_id;+ }+ if (projects.length === 0) {+ throw new Error(+ 'This Deepgram API key has no projects. Create a project in the Deepgram Console or use a key from another project.'+ );+ }+ const shown = projects+ .slice(0, 10)+ .map((item) => `${item.name} (${item.project_id})`)+ .join(', ');+ const more = projects.length > 10 ? ` and ${projects.length - 10} more` : '';+ throw new Error(+ `This API key can access ${projects.length} Deepgram projects. Choose one in the Project field: ${shown}${more}.`+ );+}++function projectPath({+ projectId,+ rest,+}: {+ projectId: string;+ rest?: string[];+}): string {+ const tail = (rest ?? [])+ .map((segment) => `/${encodeURIComponent(segment)}`)+ .join('');+ return `/projects/${encodeURIComponent(projectId)}${tail}`;+}++async function getProject({+ apiKey,+ projectId,+}: {+ apiKey: string;+ projectId: string;+}): Promise<FlatProject> {+ const response = await deepgramClient.request<ProjectResponse>({+ apiKey,+ method: HttpMethod.GET,+ path: projectPath({ projectId }),+ timeoutMs: DEEPGRAM_TIMEOUTS.manage,+ operation: 'get the project',+ });+ const body = response.body ?? {};+ return {+ project_id: body.project_id ?? projectId,+ name: body.name ?? null,+ mip_opt_out:+ typeof body.mip_opt_out === 'boolean' ? body.mip_opt_out : null,+ };+}++export const deepgramProjects = {+ listProjects,+ resolveProjectId,+ projectPath,+ getProject,+};++type ProjectResponse = {+ project_id?: string;+ name?: string;+ mip_opt_out?: boolean;+};++type FlatProject = {+ project_id: string;+ name: string | null;+ mip_opt_out: boolean | null;+};++type ProjectsResponse = {+ projects?: DeepgramProject[];+};++export type DeepgramProject = {+ project_id: string;+ name: string;+};diff --git a/packages/pieces/community/deepgram/src/common/props.ts b/packages/pieces/community/deepgram/src/common/props.tsnew file mode 100644index 00000000000..2b32dbba69f--- /dev/null+++ b/packages/pieces/community/deepgram/src/common/props.ts@@ -0,0 +1,123 @@+import { Property } from '@activepieces/pieces-framework';+import { deepgramAuth } from './auth';+import { deepgramModels } from './models';+import { deepgramProjects } from './projects';++function sttModel({ description }: { description?: string } = {}) {+ return Property.Dropdown({+ auth: deepgramAuth,+ displayName: 'Model',+ description,+ required: false,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return {+ disabled: true,+ placeholder: 'Enter your API key first',+ options: [],+ };+ }+ try {+ const options = await deepgramModels.fetchSttModelOptions({+ apiKey: auth.secret_text,+ });+ return { disabled: false, options };+ } catch (error) {+ return {+ disabled: true,+ options: [],+ placeholder: "Couldn't load models, check your API key or try again.",+ };+ }+ },+ });+}++function ttsVoice({ description }: { description?: string } = {}) {+ return Property.Dropdown({+ auth: deepgramAuth,+ displayName: 'Voice',+ description,+ required: false,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return {+ disabled: true,+ placeholder: 'Enter your API key first',+ options: [],+ };+ }+ try {+ const options = await deepgramModels.fetchTtsModelOptions({+ apiKey: auth.secret_text,+ });+ return { disabled: false, options };+ } catch (error) {+ return {+ disabled: true,+ options: [],+ placeholder: "Couldn't load voices, check your API key or try again.",+ };+ }+ },+ });+}++function project() {+ return Property.Dropdown({+ auth: deepgramAuth,+ displayName: 'Project',+ description:+ 'The Deepgram project to use. Leave empty when your API key belongs to a single project.',+ required: false,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return {+ disabled: true,+ placeholder: 'Enter your API key first',+ options: [],+ };+ }+ try {+ const projects = await deepgramProjects.listProjects({+ apiKey: auth.secret_text,+ });+ if (projects.length === 0) {+ return {+ disabled: true,+ options: [],+ placeholder: 'This API key has no projects.',+ };+ }+ return {+ disabled: false,+ options: projects.map((item) => ({+ label: item.name,+ value: item.project_id,+ })),+ };+ } catch (error) {+ return {+ disabled: true,+ options: [],+ placeholder:+ "Couldn't load projects, check your API key or try again.",+ };+ }+ },+ });+}++function projectId() {+ return Property.ShortText({+ displayName: 'Project ID',+ description:+ 'The Deepgram project ID, from List Projects (list_projects). Leave empty when the API key belongs to a single project.',+ required: false,+ });+}++export const deepgramProps = { sttModel, ttsVoice, project, projectId };diff --git a/packages/pieces/community/deepgram/src/common/read.ts b/packages/pieces/community/deepgram/src/common/read.tsnew file mode 100644index 00000000000..81509942611--- /dev/null+++ b/packages/pieces/community/deepgram/src/common/read.ts@@ -0,0 +1,26 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { DEEPGRAM_TIMEOUTS, deepgramClient, QueryInput } from './client';+import { ReadResponse } from './transcript';++async function readText({+ apiKey,+ query,+ source,+}: {+ apiKey: string;+ query: QueryInput;+ source: { text: string } | { url: string };+}): Promise<ReadResponse> {+ const response = await deepgramClient.request<ReadResponse>({+ apiKey,+ method: HttpMethod.POST,+ path: '/read',+ query,+ body: source,+ timeoutMs: DEEPGRAM_TIMEOUTS.read,+ operation: 'analyze the text',+ });+ return response.body ?? {};+}++export const deepgramRead = { readText };diff --git a/packages/pieces/community/deepgram/src/common/reports.ts b/packages/pieces/community/deepgram/src/common/reports.tsnew file mode 100644index 00000000000..d117e6295ec--- /dev/null+++ b/packages/pieces/community/deepgram/src/common/reports.ts@@ -0,0 +1,494 @@+import { deepgramClient } from './client';++function endpointOf(path: unknown): string | null {+ if (typeof path !== 'string') {+ return null;+ }+ const match = /^\/v\d+\/([a-z-]+)/i.exec(path);+ return match ? match[1] : null;+}++function joinList(value: unknown): string {+ return Array.isArray(value)+ ? value+ .filter((item) => item !== null && item !== undefined)+ .map(String)+ .join(', ')+ : '';+}++function numberOrNull(value: unknown): number | null {+ return typeof value === 'number' && Number.isFinite(value) ? value : null;+}++function stringOrNull(value: unknown): string | null {+ return typeof value === 'string' && value.length > 0 ? value : null;+}++function flattenRequest(row: RequestRow): FlatRequest {+ const response = row.response ?? {};+ const details = response.details ?? {};+ return {+ request_id: row.request_id ?? '',+ created: stringOrNull(row.created),+ completed: stringOrNull(response.completed),+ endpoint: endpointOf(row.path),+ path: deepgramClient.maskOptional(row.path),+ api_key_id: stringOrNull(row.api_key_id),+ status_code: numberOrNull(response.code ?? row.code),+ method: stringOrNull(details.method),+ deployment: stringOrNull(response.deployment ?? row.deployment),+ duration_seconds: numberOrNull(details.duration),+ total_audio_seconds: numberOrNull(details.total_audio),+ channels: numberOrNull(details.channels),+ usd: numberOrNull(details.usd),+ models: joinList(details.models),+ features: joinList(details.features),+ tags: joinList(details.tags),+ tier: stringOrNull(details.tier),+ callback_status_code: numberOrNull(callbackOf(row.callback).code),+ callback_attempts: numberOrNull(callbackOf(row.callback).attempts),+ };+}++function callbackOf(callback: RequestRow['callback']): {+ code?: number;+ attempts?: number;+} {+ return callback !== null && typeof callback === 'object' ? callback : {};+}++function roundToMillionths(value: number): number {+ return Math.round(value * 1_000_000) / 1_000_000;+}++function flattenUsage(body: UsageBreakdownResponse): FlatUsage {+ const results = (body.results ?? []).map((row) => {+ const grouping = row.grouping ?? {};+ return {+ start: stringOrNull(grouping.start),+ end: stringOrNull(grouping.end),+ hours: numberOrNull(row.hours) ?? 0,+ total_hours: numberOrNull(row.total_hours) ?? 0,+ agent_hours: numberOrNull(row.agent_hours) ?? 0,+ requests: numberOrNull(row.requests) ?? 0,+ tts_characters: numberOrNull(row.tts_characters) ?? 0,+ tokens_in: numberOrNull(row.tokens_in) ?? 0,+ tokens_out: numberOrNull(row.tokens_out) ?? 0,+ endpoint: stringOrNull(grouping.endpoint),+ method: stringOrNull(grouping.method),+ models: joinList(grouping.models),+ tags: joinList(grouping.tags),+ accessor: stringOrNull(grouping.accessor),+ feature_set: stringOrNull(grouping.feature_set),+ deployment: stringOrNull(grouping.deployment),+ };+ });+ const sum = (pick: (row: (typeof results)[number]) => number) =>+ results.reduce((total, row) => total + pick(row), 0);+ return {+ start: stringOrNull(body.start),+ end: stringOrNull(body.end),+ resolution: body.resolution+ ? `${body.resolution.amount ?? 1} ${body.resolution.units ?? ''}`.trim()+ : null,+ total_hours: roundToMillionths(sum((row) => row.total_hours)),+ total_requests: sum((row) => row.requests),+ total_tts_characters: sum((row) => row.tts_characters),+ total_tokens_in: sum((row) => row.tokens_in),+ total_tokens_out: sum((row) => row.tokens_out),+ results,+ };+}++function flattenBilling(body: BillingBreakdownResponse): FlatBilling {+ const results = (body.results ?? []).map((row) => {+ const grouping = row.grouping ?? {};+ return {+ dollars: numberOrNull(row.dollars) ?? 0,+ start: stringOrNull(grouping.start),+ end: stringOrNull(grouping.end),+ line_item: stringOrNull(grouping.line_item),+ accessor: stringOrNull(grouping.accessor),+ deployment: stringOrNull(grouping.deployment),+ tags: joinList(grouping.tags),+ };+ });+ return {+ start: stringOrNull(body.start),+ end: stringOrNull(body.end),+ total_dollars: roundToMillionths(+ results.reduce((total, row) => total + row.dollars, 0)+ ),+ results,+ };+}++function toDay(value: string | undefined): string | undefined {+ if (value === undefined || value === null || value.trim().length === 0) {+ return undefined;+ }+ const trimmed = value.trim();+ if (/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) {+ return trimmed;+ }+ const parsed = new Date(trimmed);+ if (Number.isNaN(parsed.getTime())) {+ throw new Error(`"${trimmed}" is not a valid date. Use YYYY-MM-DD.`);+ }+ return parsed.toISOString().slice(0, 10);+}++function toInstant(value: string | undefined): string | undefined {+ if (value === undefined || value === null || value.trim().length === 0) {+ return undefined;+ }+ const trimmed = value.trim();+ const parsed = new Date(trimmed);+ if (Number.isNaN(parsed.getTime())) {+ throw new Error(`"${trimmed}" is not a valid date or time.`);+ }+ return parsed.toISOString().replace(/\.\d{3}Z$/, 'Z');+}++function checkRange({+ start,+ end,+}: {+ start: string | undefined;+ end: string | undefined;+}): void {+ if (start && end && start > end) {+ throw new Error('The start date must be on or before the end date.');+ }+}++function stringList(value: unknown): string[] {+ return Array.isArray(value)+ ? value.filter(+ (item): item is string => typeof item === 'string' && item.length > 0+ )+ : [];+}++function stripTagPrefix(tag: string): string {+ return tag.startsWith('tag=') ? tag.slice(4) : tag;+}++function flattenUsageFields(body: UsageFieldsResponse): FlatUsageFields {+ return {+ accessors: stringList(body.accessors),+ tags: [...new Set(stringList(body.tags).map(stripTagPrefix))],+ models: (body.models ?? []).map((model) => ({+ model_id: model.model_id ?? '',+ name: stringOrNull(model.name),+ language: stringOrNull(model.language),+ version: stringOrNull(model.version),+ })),+ processing_methods: stringList(body.processing_methods),+ features: stringList(body.features),+ };+}++function flattenUsageSummary(body: UsageSummaryResponse): FlatUsageSummary {+ const results = (body.results ?? []).map((row) => ({+ start: stringOrNull(row.start),+ end: stringOrNull(row.end),+ hours: numberOrNull(row.hours) ?? 0,+ total_hours: numberOrNull(row.total_hours) ?? 0,+ requests: numberOrNull(row.requests) ?? 0,+ tts_characters: numberOrNull(row.tts?.characters) ?? 0,+ tts_requests: numberOrNull(row.tts?.requests) ?? 0,+ tokens_in: numberOrNull(row.tokens?.in) ?? 0,+ tokens_out: numberOrNull(row.tokens?.out) ?? 0,+ }));+ const sum = (pick: (row: (typeof results)[number]) => number) =>+ results.reduce((total, row) => total + pick(row), 0);+ return {+ start: stringOrNull(body.start),+ end: stringOrNull(body.end),+ resolution: body.resolution+ ? `${body.resolution.amount ?? 1} ${body.resolution.units ?? ''}`.trim()+ : null,+ total_hours: roundToMillionths(sum((row) => row.total_hours)),+ total_requests: sum((row) => row.requests),+ total_tts_characters: sum((row) => row.tts_characters),+ total_tts_requests: sum((row) => row.tts_requests),+ total_tokens_in: sum((row) => row.tokens_in),+ total_tokens_out: sum((row) => row.tokens_out),+ results,+ };+}++function flattenBillingFields(body: BillingFieldsResponse): FlatBillingFields {+ const lineItems =+ body.line_items !== null && typeof body.line_items === 'object'+ ? Object.entries(body.line_items)+ : [];+ return {+ accessors: stringList(body.accessors),+ deployments: stringList(body.deployments),+ tags: stringList(body.tags),+ line_items: lineItems.map(([line_item, description]) => ({+ line_item,+ description: typeof description === 'string' ? description : null,+ })),+ };+}++function flattenPurchase(order: PurchaseRow): FlatPurchase {+ return {+ order_id: order.order_id ?? '',+ created: stringOrNull(order.created),+ expiration: stringOrNull(order.expiration),+ amount: numberOrNull(order.amount),+ units: stringOrNull(order.units),+ order_type: stringOrNull(order.order_type),+ };+}++export const deepgramReports = {+ flattenUsageFields,+ flattenUsageSummary,+ flattenBillingFields,+ flattenPurchase,+ stripTagPrefix,+ flattenRequest,+ flattenUsage,+ flattenBilling,+ toDay,+ toInstant,+ checkRange,+ joinList,+};++export type RequestRow = {+ request_id?: string;+ project_uuid?: string;+ created?: string;+ path?: string;+ api_key_id?: string;+ code?: number;+ deployment?: string;+ callback?: { attempts?: number; code?: number } | string | null;+ response?: {+ code?: number;+ completed?: string;+ deployment?: string;+ details?: {+ channels?: number;+ duration?: number;+ total_audio?: number;+ method?: string;+ models?: string[];+ features?: string[];+ tags?: string[];+ usd?: number;+ tier?: string;+ };+ };+};++export type FlatRequest = {+ request_id: string;+ created: string | null;+ completed: string | null;+ endpoint: string | null;+ path: string | null;+ api_key_id: string | null;+ status_code: number | null;+ method: string | null;+ deployment: string | null;+ duration_seconds: number | null;+ total_audio_seconds: number | null;+ channels: number | null;+ usd: number | null;+ models: string;+ features: string;+ tags: string;+ tier: string | null;+ callback_status_code: number | null;+ callback_attempts: number | null;+};++export type UsageBreakdownResponse = {+ start?: string;+ end?: string;+ resolution?: { units?: string; amount?: number };+ results?: {+ hours?: number;+ total_hours?: number;+ agent_hours?: number;+ tokens_in?: number;+ tokens_out?: number;+ tts_characters?: number;+ requests?: number;+ grouping?: {+ start?: string;+ end?: string;+ accessor?: string;+ endpoint?: string;+ feature_set?: string;+ models?: string[];+ method?: string;+ tags?: string[];+ deployment?: string;+ };+ }[];+};++export type FlatUsage = {+ start: string | null;+ end: string | null;+ resolution: string | null;+ total_hours: number;+ total_requests: number;+ total_tts_characters: number;+ total_tokens_in: number;+ total_tokens_out: number;+ results: {+ start: string | null;+ end: string | null;+ hours: number;+ total_hours: number;+ agent_hours: number;+ requests: number;+ tts_characters: number;+ tokens_in: number;+ tokens_out: number;+ endpoint: string | null;+ method: string | null;+ models: string;+ tags: string;+ accessor: string | null;+ feature_set: string | null;+ deployment: string | null;+ }[];+};++export type BillingBreakdownResponse = {+ start?: string;+ end?: string;+ results?: {+ dollars?: number;+ grouping?: {+ start?: string;+ end?: string;+ accessor?: string;+ deployment?: string;+ line_item?: string;+ tags?: string[];+ };+ }[];+};++export type FlatBilling = {+ start: string | null;+ end: string | null;+ total_dollars: number;+ results: {+ dollars: number;+ start: string | null;+ end: string | null;+ line_item: string | null;+ accessor: string | null;+ deployment: string | null;+ tags: string;+ }[];+};++export type UsageFieldsResponse = {+ accessors?: string[];+ tags?: string[];+ models?: {+ name?: string;+ language?: string;+ version?: string;+ model_id?: string;+ }[];+ processing_methods?: string[];+ features?: string[];+};++export type FlatUsageFields = {+ accessors: string[];+ tags: string[];+ models: {+ model_id: string;+ name: string | null;+ language: string | null;+ version: string | null;+ }[];+ processing_methods: string[];+ features: string[];+};++export type BillingFieldsResponse = {+ accessors?: string[];+ deployments?: string[];+ tags?: string[];+ line_items?: Record<string, unknown> | null;+};++export type FlatBillingFields = {+ accessors: string[];+ deployments: string[];+ tags: string[];+ line_items: { line_item: string; description: string | null }[];+};++export type PurchaseRow = {+ order_id?: string;+ expiration?: string;+ created?: string;+ amount?: number;+ units?: string;+ order_type?: string;+};++export type FlatPurchase = {+ order_id: string;+ created: string | null;+ expiration: string | null;+ amount: number | null;+ units: string | null;+ order_type: string | null;+};++export type UsageSummaryResponse = {+ start?: string;+ end?: string;+ resolution?: { units?: string; amount?: number };+ results?: {+ start?: string;+ end?: string;+ hours?: number;+ total_hours?: number;+ requests?: number;+ tokens?: { in?: number; out?: number };+ tts?: { characters?: number; requests?: number };+ }[];+};++export type FlatUsageSummary = {+ start: string | null;+ end: string | null;+ resolution: string | null;+ total_hours: number;+ total_requests: number;+ total_tts_characters: number;+ total_tts_requests: number;+ total_tokens_in: number;+ total_tokens_out: number;+ results: {+ start: string | null;+ end: string | null;+ hours: number;+ total_hours: number;+ requests: number;+ tts_characters: number;+ tts_requests: number;+ tokens_in: number;+ tokens_out: number;+ }[];+};diff --git a/packages/pieces/community/deepgram/src/common/speech.ts b/packages/pieces/community/deepgram/src/common/speech.tsnew file mode 100644index 00000000000..31300fd6633--- /dev/null+++ b/packages/pieces/community/deepgram/src/common/speech.ts@@ -0,0 +1,161 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { DEEPGRAM_TIMEOUTS, deepgramClient } from './client';+import { MAX_TTS_CHARACTERS } from './constants';++const WAV_ENCODINGS = ['linear16', 'mulaw', 'alaw'];++const EXTENSIONS: Record<string, string> = {+ mp3: 'mp3',+ opus: 'ogg',+ flac: 'flac',+ aac: 'aac',+};++function checkText(text: unknown): string {+ const value = typeof text === 'string' ? text : '';+ if (value.trim().length === 0) {+ throw new Error('Enter the text to convert to speech.');+ }+ if (value.length > MAX_TTS_CHARACTERS) {+ throw new Error(+ `Deepgram converts at most ${MAX_TTS_CHARACTERS} characters per request and this text has ${value.length}. Split the text into smaller parts and convert each one.`+ );+ }+ return value;+}++function checkSpeed(speed: unknown): number | undefined {+ if (speed === undefined || speed === null || speed === '') {+ return undefined;+ }+ const value = Number(speed);+ if (!Number.isFinite(value) || value < 0.5 || value > 1.5) {+ throw new Error(+ 'Speed must be a number from 0.5 to 1.5 (1 is normal speed).'+ );+ }+ return value;+}++function checkPositiveInteger({+ value,+ label,+}: {+ value: unknown;+ label: string;+}): number | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const parsed = Number(value);+ if (!Number.isInteger(parsed) || parsed <= 0) {+ throw new Error(`${label} must be a whole number greater than 0.`);+ }+ return parsed;+}++function fileExtension({+ encoding,+ container,+}: {+ encoding: string;+ container: string | undefined;+}): string {+ if (WAV_ENCODINGS.includes(encoding)) {+ return container === 'none' ? 'raw' : 'wav';+ }+ return EXTENSIONS[encoding] ?? 'mp3';+}++function headerValue(value: string | string[] | undefined): string | null {+ if (Array.isArray(value)) {+ return value[0] ?? null;+ }+ return typeof value === 'string' && value.length > 0 ? value : null;+}++async function synthesize({+ apiKey,+ text,+ model,+ encoding,+ container,+ sampleRate,+ bitRate,+ speed,+ writeFile,+}: {+ apiKey: string;+ text: unknown;+ model: string;+ encoding: string | undefined | null;+ container?: string | null;+ sampleRate?: unknown;+ bitRate?: unknown;+ speed?: unknown;+ writeFile: (params: { fileName: string; data: Buffer }) => Promise<string>;+}): Promise<SpeechOutput> {+ const content = checkText(text);+ const chosenEncoding = encoding && encoding.length > 0 ? encoding : 'mp3';+ const chosenContainer =+ container && WAV_ENCODINGS.includes(chosenEncoding) ? container : undefined;+ const response = await deepgramClient.request<Buffer>({+ apiKey,+ method: HttpMethod.POST,+ path: '/speak',+ query: {+ model,+ encoding: chosenEncoding,+ container: chosenContainer,+ sample_rate: checkPositiveInteger({+ value: sampleRate,+ label: 'Sample rate',+ }),+ bit_rate: checkPositiveInteger({ value: bitRate, label: 'Bit rate' }),+ speed: checkSpeed(speed),+ },+ body: { text: content },+ headers: { Accept: '*/*' },+ responseType: 'arraybuffer',+ timeoutMs: DEEPGRAM_TIMEOUTS.speak,+ operation: 'convert the text to speech',+ });+ const data = Buffer.from(response.body);+ const fileName = `audio.${fileExtension({+ encoding: chosenEncoding,+ container: chosenContainer,+ })}`;+ const file = await writeFile({ fileName, data });+ const characters = Number(headerValue(response.headers['dg-char-count']));+ return {+ file,+ file_name: fileName,+ content_type: headerValue(response.headers['content-type']),+ size_bytes: data.length,+ characters:+ Number.isFinite(characters) && characters > 0+ ? characters+ : content.length,+ request_id: headerValue(response.headers['dg-request-id']),+ model,+ encoding: chosenEncoding,+ };+}++export const deepgramSpeech = {+ synthesize,+ checkText,+ checkSpeed,+ fileExtension,+};++export type SpeechOutput = {+ file: string;+ file_name: string;+ content_type: string | null;+ size_bytes: number;+ characters: number;+ request_id: string | null;+ model: string;+ encoding: string;+};diff --git a/packages/pieces/community/deepgram/src/common/transcript.ts b/packages/pieces/community/deepgram/src/common/transcript.tsnew file mode 100644index 00000000000..a093dac3041--- /dev/null+++ b/packages/pieces/community/deepgram/src/common/transcript.ts@@ -0,0 +1,462 @@+function firstAlternative(+ channel: ListenChannel | undefined+): ListenAlternative {+ return channel?.alternatives?.[0] ?? {};+}++function joinChannels({+ channels,+ pick,+}: {+ channels: ListenChannel[];+ pick: (alternative: ListenAlternative) => string | undefined;+}): string | null {+ const parts = channels+ .map((channel) => pick(firstAlternative(channel)))+ .filter(+ (text): text is string => typeof text === 'string' && text.length > 0+ );+ return parts.length > 0 ? parts.join('\n\n') : null;+}++function segmentsOf({+ node,+ key,+}: {+ node: IntelligenceNode | undefined;+ key: 'topics' | 'intents';+}): IntelligenceSegment[] {+ if (!node) {+ return [];+ }+ const nested = node.results?.[key]?.segments;+ return node.segments ?? nested ?? [];+}++function flattenTopics(node: IntelligenceNode | undefined): FlatLabel[] {+ return segmentsOf({ node, key: 'topics' }).flatMap((segment) =>+ (segment.topics ?? []).map((item) => ({+ label: item.topic ?? '',+ confidence: item.confidence_score ?? null,+ text: segment.text ?? '',+ }))+ );+}++function flattenIntents(node: IntelligenceNode | undefined): FlatLabel[] {+ return segmentsOf({ node, key: 'intents' }).flatMap((segment) =>+ (segment.intents ?? []).map((item) => ({+ label: item.intent ?? '',+ confidence: item.confidence_score ?? null,+ text: segment.text ?? '',+ }))+ );+}++function renameLabel({+ items,+ key,+}: {+ items: FlatLabel[];+ key: 'topic' | 'intent';+}): Record<string, string | number | null>[] {+ return items.map((item) => ({+ [key]: item.label,+ confidence: item.confidence,+ text: item.text,+ }));+}++function flattenSentiment(sentiments: SentimentNode | undefined): {+ sentiment: string | null;+ sentiment_score: number | null;+ sentiment_segments: {+ text: string;+ sentiment: string | null;+ sentiment_score: number | null;+ }[];+} {+ return {+ sentiment: sentiments?.average?.sentiment ?? null,+ sentiment_score: sentiments?.average?.sentiment_score ?? null,+ sentiment_segments: (sentiments?.segments ?? []).map((segment) => ({+ text: segment.text ?? '',+ sentiment: segment.sentiment ?? null,+ sentiment_score: segment.sentiment_score ?? null,+ })),+ };+}++function listenSummary(summary: ListenSummary | undefined): {+ summary: string | null;+ warning: string | null;+} {+ if (!summary) {+ return { summary: null, warning: null };+ }+ if (+ summary.result === 'success' &&+ typeof summary.short === 'string' &&+ summary.short.length > 0+ ) {+ return { summary: summary.short, warning: null };+ }+ return {+ summary: null,+ warning: `Summary not available${+ summary.short ? `: ${summary.short}` : '.'+ }`,+ };+}++function speakerTranscript(words: FlatWord[]): string | null {+ if (!words.some((word) => word.speaker !== null)) {+ return null;+ }+ const lines: { speaker: number | null; text: string[] }[] = [];+ for (const word of words) {+ const last = lines[lines.length - 1];+ if (last && last.speaker === word.speaker) {+ last.text.push(word.punctuated_word);+ } else {+ lines.push({ speaker: word.speaker, text: [word.punctuated_word] });+ }+ }+ return lines+ .map((line) => `Speaker ${line.speaker ?? '?'}: ${line.text.join(' ')}`)+ .join('\n');+}++function flattenWords(channels: ListenChannel[]): FlatWord[] {+ return channels.flatMap((channel, index) =>+ (firstAlternative(channel).words ?? []).map((word) => ({+ word: word.word ?? '',+ punctuated_word: word.punctuated_word ?? word.word ?? '',+ start: word.start ?? null,+ end: word.end ?? null,+ confidence: word.confidence ?? null,+ speaker: typeof word.speaker === 'number' ? word.speaker : null,+ channel: index,+ }))+ );+}++function flattenListen({+ body,+ includeWords,+}: {+ body: ListenResponse;+ includeWords: boolean;+}): FlatTranscription {+ const metadata = body.metadata ?? {};+ const results = body.results ?? {};+ const channels = results.channels ?? [];+ const first = firstAlternative(channels[0]);+ const modelId = (metadata.models ?? [])[0];+ const modelInfo = modelId ? metadata.model_info?.[modelId] : undefined;+ const words = flattenWords(channels);+ const speakers = new Set(+ words+ .map((word) => word.speaker)+ .filter((speaker): speaker is number => speaker !== null)+ );+ const summary = listenSummary(results.summary);+ const sentiment = flattenSentiment(results.sentiments);+ const vendorWarnings = (metadata.warnings ?? []).map((warning) =>+ [warning.parameter, warning.message].filter(Boolean).join(': ')+ );+ return {+ request_id: metadata.request_id ?? null,+ transcript: joinChannels({ channels, pick: (alt) => alt.transcript }) ?? '',+ confidence: first.confidence ?? null,+ duration_seconds: metadata.duration ?? null,+ detected_language: channels[0]?.detected_language ?? null,+ language_confidence: channels[0]?.language_confidence ?? null,+ model_name: modelInfo?.name ?? null,+ model_version: modelInfo?.version ?? null,+ channel_count: metadata.channels ?? channels.length,+ paragraphs_text: joinChannels({+ channels,+ pick: (alt) => alt.paragraphs?.transcript?.trim(),+ }),+ speaker_count: speakers.size > 0 ? speakers.size : null,+ speaker_transcript: speakerTranscript(words),+ summary: summary.summary,+ topics: renameLabel({ items: flattenTopics(results.topics), key: 'topic' }),+ intents: renameLabel({+ items: flattenIntents(results.intents),+ key: 'intent',+ }),+ sentiment: sentiment.sentiment,+ sentiment_score: sentiment.sentiment_score,+ utterances: (results.utterances ?? []).map((utterance) => ({+ speaker: typeof utterance.speaker === 'number' ? utterance.speaker : null,+ channel: utterance.channel ?? null,+ start: utterance.start ?? null,+ end: utterance.end ?? null,+ confidence: utterance.confidence ?? null,+ transcript: utterance.transcript ?? '',+ })),+ channels: channels.map((channel, index) => ({+ channel: index,+ transcript: firstAlternative(channel).transcript ?? '',+ confidence: firstAlternative(channel).confidence ?? null,+ detected_language: channel.detected_language ?? null,+ })),+ entities: channels.flatMap((channel, index) =>+ (firstAlternative(channel).entities ?? []).map((entity) => ({+ label: entity.label ?? '',+ value: (entity.value ?? '').trim(),+ confidence: entity.confidence ?? null,+ channel: index,+ }))+ ),+ words: includeWords ? words : [],+ warnings: [+ ...vendorWarnings,+ ...(summary.warning ? [summary.warning] : []),+ ],+ };+}++function readSummary(summary: ReadSummaryNode | undefined): string | null {+ if (!summary) {+ return null;+ }+ const text = summary.text ?? summary.results?.summary?.text;+ return typeof text === 'string' && text.length > 0 ? text : null;+}++function flattenRead(body: ReadResponse): FlatAnalysis {+ const inner = body.metadata?.metadata ?? body.metadata ?? {};+ const results = body.results ?? {};+ const sentiment = flattenSentiment(results.sentiments);+ const infos = [+ inner.summary_info,+ inner.topics_info,+ inner.intents_info,+ inner.sentiment_info,+ ];+ const inputTokens = infos.reduce(+ (max, info) => Math.max(max, info?.input_tokens ?? 0),+ 0+ );+ const outputTokens = infos.reduce(+ (sum, info) => sum + (info?.output_tokens ?? 0),+ 0+ );+ return {+ request_id: inner.request_id ?? null,+ language: inner.language ?? null,+ summary: readSummary(results.summary),+ topics: renameLabel({ items: flattenTopics(results.topics), key: 'topic' }),+ intents: renameLabel({+ items: flattenIntents(results.intents),+ key: 'intent',+ }),+ sentiment: sentiment.sentiment,+ sentiment_score: sentiment.sentiment_score,+ sentiment_segments: sentiment.sentiment_segments,+ input_tokens: inputTokens > 0 ? inputTokens : null,+ output_tokens: outputTokens > 0 ? outputTokens : null,+ };+}++function summaryOutcome(body: ListenResponse): ListenSummary | undefined {+ return body.results?.summary;+}++function firstTranscript(body: ListenResponse): string | undefined {+ const text = firstAlternative(body.results?.channels?.[0]).transcript;+ return typeof text === 'string' && text.length > 0 ? text : undefined;+}++export const deepgramTranscript = {+ flattenListen,+ flattenRead,+ summaryOutcome,+ firstTranscript,+};++type FlatLabel = {+ label: string;+ confidence: number | null;+ text: string;+};++type FlatWord = {+ word: string;+ punctuated_word: string;+ start: number | null;+ end: number | null;+ confidence: number | null;+ speaker: number | null;+ channel: number;+};++type IntelligenceSegment = {+ text?: string;+ start_word?: number;+ end_word?: number;+ topics?: { topic?: string; confidence_score?: number }[];+ intents?: { intent?: string; confidence_score?: number }[];+};++type IntelligenceNode = {+ segments?: IntelligenceSegment[];+ results?: {+ topics?: { segments?: IntelligenceSegment[] };+ intents?: { segments?: IntelligenceSegment[] };+ };+};++type SentimentNode = {+ segments?: {+ text?: string;+ sentiment?: string;+ sentiment_score?: number;+ }[];+ average?: { sentiment?: string; sentiment_score?: number };+};++type ListenWord = {+ word?: string;+ punctuated_word?: string;+ start?: number;+ end?: number;+ confidence?: number;+ speaker?: number;+};++type ListenAlternative = {+ transcript?: string;+ confidence?: number;+ words?: ListenWord[];+ paragraphs?: { transcript?: string };+ entities?: { label?: string; value?: string; confidence?: number }[];+};++type ListenChannel = {+ alternatives?: ListenAlternative[];+ detected_language?: string;+ language_confidence?: number;+};++type ListenSummary = {+ result?: string;+ short?: string;+};++type ModelInfo = { name?: string; version?: string; arch?: string };++type TokenInfo = { input_tokens?: number; output_tokens?: number };++type ReadSummaryNode = {+ text?: string;+ results?: { summary?: { text?: string } };+};++export type ListenResponse = {+ request_id?: string;+ metadata?: {+ request_id?: string;+ duration?: number;+ channels?: number;+ models?: string[];+ model_info?: Record<string, ModelInfo>;+ warnings?: { parameter?: string; type?: string; message?: string }[];+ };+ results?: {+ channels?: ListenChannel[];+ utterances?: {+ speaker?: number;+ channel?: number;+ start?: number;+ end?: number;+ confidence?: number;+ transcript?: string;+ }[];+ summary?: ListenSummary;+ topics?: IntelligenceNode;+ intents?: IntelligenceNode;+ sentiments?: SentimentNode;+ };+};++export type ReadResponse = {+ metadata?: ReadMetadata & { metadata?: ReadMetadata };+ results?: {+ summary?: ReadSummaryNode;+ topics?: IntelligenceNode;+ intents?: IntelligenceNode;+ sentiments?: SentimentNode;+ };+};++type ReadMetadata = {+ request_id?: string;+ language?: string;+ summary_info?: TokenInfo;+ topics_info?: TokenInfo;+ intents_info?: TokenInfo;+ sentiment_info?: TokenInfo;+};++export type FlatTranscription = {+ request_id: string | null;+ transcript: string;+ confidence: number | null;+ duration_seconds: number | null;+ detected_language: string | null;+ language_confidence: number | null;+ model_name: string | null;+ model_version: string | null;+ channel_count: number;+ paragraphs_text: string | null;+ speaker_count: number | null;+ speaker_transcript: string | null;+ summary: string | null;+ topics: Record<string, string | number | null>[];+ intents: Record<string, string | number | null>[];+ sentiment: string | null;+ sentiment_score: number | null;+ utterances: {+ speaker: number | null;+ channel: number | null;+ start: number | null;+ end: number | null;+ confidence: number | null;+ transcript: string;+ }[];+ channels: {+ channel: number;+ transcript: string;+ confidence: number | null;+ detected_language: string | null;+ }[];+ entities: {+ label: string;+ value: string;+ confidence: number | null;+ channel: number;+ }[];+ words: FlatWord[];+ warnings: string[];+};++export type FlatAnalysis = {+ request_id: string | null;+ language: string | null;+ summary: string | null;+ topics: Record<string, string | number | null>[];+ intents: Record<string, string | number | null>[];+ sentiment: string | null;+ sentiment_score: number | null;+ sentiment_segments: {+ text: string;+ sentiment: string | null;+ sentiment_score: number | null;+ }[];+ input_tokens: number | null;+ output_tokens: number | null;+};diff --git a/packages/pieces/community/deepgram/src/i18n/translation.json b/packages/pieces/community/deepgram/src/i18n/translation.jsonindex 0406ba92095..894d7635ced 100644--- a/packages/pieces/community/deepgram/src/i18n/translation.json+++ b/packages/pieces/community/deepgram/src/i18n/translation.json@@ -1,25 +1,131 @@{"Deepgram is an AI-powered speech recognition platform that provides real-time transcription, text-to-speech, and audio analysis capabilities.": "Deepgram is an AI-powered speech recognition platform that provides real-time transcription, text-to-speech, and audio analysis capabilities.","You can obtain your API key from [Deepgram Console](https://console.deepgram.com/).": "You can obtain your API key from [Deepgram Console](https://console.deepgram.com/).",+ "Transcribe Audio": "Transcribe Audio",+ "Analyze Text": "Analyze Text","Create Summary": "Create Summary","Create Transcription (Callback)": "Create Transcription (Callback)",- "List Projects": "List Projects","Text to Speech": "Text to Speech",+ "Generate Speech": "Generate Speech",+ "List Models and Voices": "List Models and Voices",+ "List Projects": "List Projects",+ "Get Project": "Get Project",+ "Rename Project": "Rename Project",+ "List Project Members": "List Project Members",+ "List API Keys": "List API Keys",+ "List Requests": "List Requests",+ "Get Request": "Get Request",+ "Get Usage Breakdown": "Get Usage Breakdown",+ "Get Credit Balance": "Get Credit Balance",+ "Get Cost Breakdown": "Get Cost Breakdown",+ "Transcribe Audio (Agent)": "Transcribe Audio (Agent)",+ "List Models and Voices (Agent)": "List Models and Voices (Agent)",+ "Get Model": "Get Model",+ "List Requests (Agent)": "List Requests (Agent)",+ "Get Request (Agent)": "Get Request (Agent)",+ "List Project Members (Agent)": "List Project Members (Agent)",+ "Get Usage Breakdown (Agent)": "Get Usage Breakdown (Agent)",+ "Get Usage Summary": "Get Usage Summary",+ "List Usage Filter Values": "List Usage Filter Values",+ "List Credit Balances": "List Credit Balances",+ "Get Credit Balance by ID": "Get Credit Balance by ID",+ "Get Cost Breakdown (Agent)": "Get Cost Breakdown (Agent)",+ "List Billing Filter Values": "List Billing Filter Values",+ "List Purchases": "List Purchases",+ "List Voice Agent LLMs": "List Voice Agent LLMs","Custom API Call": "Custom API Call",- "Produces a summary of the content from an audio file.": "Produces a summary of the content from an audio file.",- "Creates a transcription using a callback URL.": "Creates a transcription using a callback URL.",- "Retrieves a list of all projects associated with the account.": "Retrieves a list of all projects associated with the account.",- "Converts text to audio file.": "Converts text to audio file.",+ "Transcribes an audio or video file or URL and returns the transcript, with optional speakers, paragraphs, summary, topics and more.": "Transcribes an audio or video file or URL and returns the transcript, with optional speakers, paragraphs, summary, topics and more.",+ "Summarizes English text and detects its topics, intents and sentiment.": "Summarizes English text and detects its topics, intents and sentiment.",+ "Produces a summary of the content from an English audio file.": "Produces a summary of the content from an English audio file.",+ "Starts a transcription and has Deepgram send the result to a callback URL. To receive it in another flow, use the Catch Webhook URL of the Webhook piece.": "Starts a transcription and has Deepgram send the result to a callback URL. To receive it in another flow, use the Catch Webhook URL of the Webhook piece.",+ "Converts text (up to 2,000 characters) to an audio file.": "Converts text (up to 2,000 characters) to an audio file.",+ "Converts text to an audio file with a Deepgram Aura voice ID.": "Converts text to an audio file with a Deepgram Aura voice ID.",+ "Lists Deepgram speech-to-text models and text-to-speech voices, one row per model.": "Lists Deepgram speech-to-text models and text-to-speech voices, one row per model.",+ "Lists the Deepgram projects this API key can access.": "Lists the Deepgram projects this API key can access.",+ "Gets the name and settings of a Deepgram project.": "Gets the name and settings of a Deepgram project.",+ "Changes the name of a Deepgram project.": "Changes the name of a Deepgram project.",+ "Lists the members of a Deepgram project with their roles. Needs an admin or owner API key.": "Lists the members of a Deepgram project with their roles. Needs an admin or owner API key.",+ "Lists the API keys of a Deepgram project (never the secret values). A member key only sees its own keys.": "Lists the API keys of a Deepgram project (never the secret values). A member key only sees its own keys.",+ "Lists past API requests of a Deepgram project with status, duration and cost.": "Lists past API requests of a Deepgram project with status, duration and cost.",+ "Gets one past Deepgram request by ID with its status, duration and cost.": "Gets one past Deepgram request by ID with its status, duration and cost.",+ "Gets audio hours, requests, characters and tokens used by a Deepgram project, optionally grouped.": "Gets audio hours, requests, characters and tokens used by a Deepgram project, optionally grouped.",+ "Gets the remaining prepaid credit of a Deepgram project. Needs an admin or owner API key.": "Gets the remaining prepaid credit of a Deepgram project. Needs an admin or owner API key.",+ "Gets what a Deepgram project spent in dollars for a date range, optionally grouped. Needs an admin or owner API key.": "Gets what a Deepgram project spent in dollars for a date range, optionally grouped. Needs an admin or owner API key.",+ "Lists Deepgram speech-to-text models and text-to-speech voices, one row per model or one row per build.": "Lists Deepgram speech-to-text models and text-to-speech voices, one row per model or one row per build.",+ "Gets one Deepgram model build by its UUID.": "Gets one Deepgram model build by its UUID.",+ "Lists the members of a Deepgram project with their scopes.": "Lists the members of a Deepgram project with their scopes.",+ "Gets the usage summary of a Deepgram project for a date range, with optional filters.": "Gets the usage summary of a Deepgram project for a date range, with optional filters.",+ "Lists the tags, model builds, methods and features used by a Deepgram project in a date range.": "Lists the tags, model builds, methods and features used by a Deepgram project in a date range.",+ "Lists the prepaid credit balances of a Deepgram project.": "Lists the prepaid credit balances of a Deepgram project.",+ "Gets one prepaid credit balance of a Deepgram project by ID.": "Gets one prepaid credit balance of a Deepgram project by ID.",+ "Gets what a Deepgram project spent in dollars for a date range, optionally grouped.": "Gets what a Deepgram project spent in dollars for a date range, optionally grouped.",+ "Lists the API keys, deployments, tags and line items billed to a Deepgram project in a date range.": "Lists the API keys, deployments, tags and line items billed to a Deepgram project in a date range.",+ "Lists the most recent credit purchases of a Deepgram project.": "Lists the most recent credit purchases of a Deepgram project.",+ "Lists the language models a Deepgram Voice Agent can use to think.": "Lists the language models a Deepgram Voice Agent can use to think.","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",+ "Audio URL": "Audio URL","Audio File": "Audio File","Model": "Model","Language": "Language",+ "Detect Language": "Detect Language",+ "Smart Format": "Smart Format",+ "Identify Speakers": "Identify Speakers",+ "Paragraphs": "Paragraphs",+ "Utterances": "Utterances",+ "Transcribe Each Channel Separately": "Transcribe Each Channel Separately",+ "Key Terms": "Key Terms",+ "Redact": "Redact",+ "Detect Entities": "Detect Entities",+ "Summarize (English)": "Summarize (English)",+ "Detect Topics (English)": "Detect Topics (English)",+ "Detect Intents (English)": "Detect Intents (English)",+ "Analyze Sentiment (English)": "Analyze Sentiment (English)",+ "Include Word Timings": "Include Word Timings",+ "Tags": "Tags",+ "Text": "Text",+ "Text URL": "Text URL",+ "Summarize": "Summarize",+ "Detect Topics": "Detect Topics",+ "Detect Intents": "Detect Intents",+ "Analyze Sentiment": "Analyze Sentiment",+ "Custom Topics": "Custom Topics",+ "Custom Topic Mode": "Custom Topic Mode",+ "Custom Intents": "Custom Intents",+ "Custom Intent Mode": "Custom Intent Mode","Fallback to Full Transcript": "Fallback to Full Transcript","Callback URL": "Callback URL",- "Text": "Text",+ "Callback Method": "Callback Method","Voice": "Voice","Output Format": "Output Format",+ "Container": "Container",+ "Sample Rate (Hz)": "Sample Rate (Hz)",+ "Bit Rate (bps)": "Bit Rate (bps)",+ "Speed": "Speed",+ "Voice ID": "Voice ID",+ "Audio Format": "Audio Format",+ "Type": "Type",+ "Project": "Project",+ "Include Older Versions": "Include Older Versions",+ "New Name": "New Name",+ "Status": "Status",+ "From": "From",+ "To": "To",+ "Endpoint": "Endpoint","Method": "Method",+ "Limit": "Limit",+ "Page": "Page",+ "Request ID": "Request ID",+ "Start Date": "Start Date",+ "End Date": "End Date",+ "Group By": "Group By",+ "Tag": "Tag",+ "Line Item": "Line Item",+ "Project ID": "Project ID",+ "One Row per Build": "One Row per Build",+ "Model UUID": "Model UUID",+ "API Key ID": "API Key ID",+ "Deployment": "Deployment",+ "Balance ID": "Balance ID","Headers": "Headers","Query Parameters": "Query Parameters","Body Type": "Body Type",@@ -28,15 +134,86 @@"Return Error as Output": "Return Error as Output","Timeout": "Timeout","Follow redirects": "Follow redirects",- "en": "en",+ "A public link to the audio or video file. Deepgram downloads it directly. Use this or Audio File.": "A public link to the audio or video file. Deepgram downloads it directly. Use this or Audio File.",+ "The audio or video file to transcribe. Use this or Audio URL.": "The audio or video file to transcribe. Use this or Audio URL.",+ "Leave empty for nova-3, Deepgram's recommended model for most languages.": "Leave empty for nova-3, Deepgram's recommended model for most languages.",+ "Spoken language as a BCP-47 code, for example en, es, fr-CA or multi (several languages in one recording, nova-3 only). Leave empty for English, or turn on Detect Language.": "Spoken language as a BCP-47 code, for example en, es, fr-CA or multi (several languages in one recording, nova-3 only). Leave empty for English, or turn on Detect Language.",+ "Let Deepgram detect the main spoken language. Ignores Language.": "Let Deepgram detect the main spoken language. Ignores Language.",+ "Add punctuation, capitals and readable numbers, dates and currency.": "Add punctuation, capitals and readable numbers, dates and currency.",+ "Label who speaks when and return a transcript split by speaker.": "Label who speaks when and return a transcript split by speaker.",+ "Also return the transcript split into paragraphs.": "Also return the transcript split into paragraphs.",+ "Also return the transcript as timed segments (sentences or speaker turns).": "Also return the transcript as timed segments (sentences or speaker turns).",+ "For stereo recordings with one speaker per channel, such as call recordings. Billed per channel.": "For stereo recordings with one speaker per channel, such as call recordings. Billed per channel.",+ "Names, brands or jargon to recognize more reliably (nova-3 models only). Up to 100 terms.": "Names, brands or jargon to recognize more reliably (nova-3 models only). Up to 100 terms.",+ "Replace sensitive information in the transcript. Billed as an add-on.": "Replace sensitive information in the transcript. Billed as an add-on.",+ "Return names, organizations, places, numbers and other entities found in the speech.": "Return names, organizations, places, numbers and other entities found in the speech.",+ "Return a short summary. English audio only; needs more than about 50 spoken words.": "Return a short summary. English audio only; needs more than about 50 spoken words.",+ "Return every word with its start and end time. Makes the output much larger.": "Return every word with its start and end time. Makes the output much larger.",+ "Labels for this request that show up in Deepgram usage reports.": "Labels for this request that show up in Deepgram usage reports.",+ "The English text to analyze. Use this or Text URL.": "The English text to analyze. Use this or Text URL.",+ "A public link to a plain-text file. Deepgram downloads it directly. Use this or Text.": "A public link to a plain-text file. Deepgram downloads it directly. Use this or Text.",+ "Topics to look for in addition to (or instead of) the detected ones. Up to 100.": "Topics to look for in addition to (or instead of) the detected ones. Up to 100.",+ "Extended adds your topics to the detected ones; Strict only returns your topics.": "Extended adds your topics to the detected ones; Strict only returns your topics.",+ "Intents to look for in addition to (or instead of) the detected ones. Up to 100.": "Intents to look for in addition to (or instead of) the detected ones. Up to 100.",+ "Extended adds your intents to the detected ones; Strict only returns your intents.": "Extended adds your intents to the detected ones; Strict only returns your intents.",+ "The English audio or video file to summarize.": "The English audio or video file to summarize.",+ "Leave empty for nova (Nova-1). For better accuracy choose nova-3-general.": "Leave empty for nova (Nova-1). For better accuracy choose nova-3-general.",+ "Summaries are only available for English (en, en-US, en-GB, en-AU, en-IN, en-NZ). Leave empty for en.": "Summaries are only available for English (en, en-US, en-GB, en-AU, en-IN, en-NZ). Leave empty for en.","Return full transcript if summary is not available.": "Return full transcript if summary is not available.",- "URL to receive the transcription when ready.": "URL to receive the transcription when ready.",+ "Leave empty for nova (Nova-1, English, Spanish and Hindi only). For other languages choose nova-3-general or nova-2-general.": "Leave empty for nova (Nova-1, English, Spanish and Hindi only). For other languages choose nova-3-general or nova-2-general.",+ "Spoken language. Leave empty for en. The default model nova only supports en, es and hi-Latn; pick a nova-3 or nova-2 model for other languages.": "Spoken language. Leave empty for en. The default model nova only supports en, es and hi-Latn; pick a nova-3 or nova-2 model for other languages.",+ "URL to receive the transcription when ready. Must use port 80, 443, 8080 or 8443. Basic-auth credentials (https://user:password@host) are allowed and hidden in the output.": "URL to receive the transcription when ready. Must use port 80, 443, 8080 or 8443. Basic-auth credentials (https://user:password@host) are allowed and hidden in the output.",+ "How Deepgram sends the result. Defaults to POST.": "How Deepgram sends the result. Defaults to POST.",+ "Label who speaks when.": "Label who speaks when.",+ "Up to 2,000 characters. Split longer text into several steps.": "Up to 2,000 characters. Split longer text into several steps.",+ "Leave empty for aura-asteria-en. Aura-2 voices sound more natural and cover more languages.": "Leave empty for aura-asteria-en. Aura-2 voices sound more natural and cover more languages.",+ "For linear16, mulaw and alaw only. WAV (default) adds a file header; None returns raw audio for telephony systems.": "For linear16, mulaw and alaw only. WAV (default) adds a file header; None returns raw audio for telephony systems.",+ "Optional. linear16: 8000-48000 (default 24000); mulaw/alaw: 8000 or 16000; flac: 8000-48000. Not used for mp3, opus or aac.": "Optional. linear16: 8000-48000 (default 24000); mulaw/alaw: 8000 or 16000; flac: 8000-48000. Not used for mp3, opus or aac.",+ "Optional. mp3: 32000 or 48000; opus: 4000-650000; aac: 4000-192000.": "Optional. mp3: 32000 or 48000; opus: 4000-650000; aac: 4000-192000.",+ "Speaking rate from 0.5 to 1.5 (1 is normal). Not supported by every voice.": "Speaking rate from 0.5 to 1.5 (1 is normal). Not supported by every voice.",+ "The text to speak, up to 2,000 characters.": "The text to speak, up to 2,000 characters.",+ "A Deepgram voice ID such as aura-2-thalia-en or aura-2-celeste-es. Leave empty for aura-2-thalia-en.": "A Deepgram voice ID such as aura-2-thalia-en or aura-2-celeste-es. Leave empty for aura-2-thalia-en.",+ "Only list models for this language code, for example en, es or de. \"en\" also matches en-US and en-GB.": "Only list models for this language code, for example en, es or de. \"en\" also matches en-US and en-GB.",+ "Pick a project to also list custom models trained for it. Leave empty for the public catalog.": "Pick a project to also list custom models trained for it. Leave empty for the public catalog.",+ "Also consider models that are no longer the latest version.": "Also consider models that are no longer the latest version.",+ "The Deepgram project to use. Leave empty when your API key belongs to a single project.": "The Deepgram project to use. Leave empty when your API key belongs to a single project.",+ "The new name of the project.": "The new name of the project.",+ "Only list keys with this status. Leave empty for all keys.": "Only list keys with this status. Leave empty for all keys.",+ "Only requests made at or after this time.": "Only requests made at or after this time.",+ "Only requests made at or before this time.": "Only requests made at or before this time.",+ "Requests per page, from 1 to 1000. Defaults to 50.": "Requests per page, from 1 to 1000. Defaults to 50.",+ "Page number, starting at 0.": "Page number, starting at 0.",+ "The request ID returned by a Deepgram action, for example Create Transcription (Callback).": "The request ID returned by a Deepgram action, for example Create Transcription (Callback).",+ "First day to include. Deepgram defaults to 30 days ago.": "First day to include. Deepgram defaults to 30 days ago.",+ "Last day to include. Deepgram defaults to today.": "Last day to include. Deepgram defaults to today.",+ "Only count requests to this endpoint.": "Only count requests to this endpoint.",+ "Only count requests sent with this tag.": "Only count requests sent with this tag.",+ "First day to include.": "First day to include.",+ "Last day to include.": "Last day to include.",+ "Only include this line item, for example streaming::nova-3.": "Only include this line item, for example streaming::nova-3.",+ "A Deepgram speech-to-text model: a short alias such as nova-3 or nova-2, or a canonical name from deepgram_list_models such as nova-3-general. Leave empty for nova-3.": "A Deepgram speech-to-text model: a short alias such as nova-3 or nova-2, or a canonical name from deepgram_list_models such as nova-3-general. Leave empty for nova-3.",+ "A project ID from List Projects (list_projects) to also list custom models trained for it. Leave empty for the public catalog.": "A project ID from List Projects (list_projects) to also list custom models trained for it. Leave empty for the public catalog.",+ "Return one row per language/version build with its UUID instead of one merged row per model.": "Return one row per language/version build with its UUID instead of one merged row per model.",+ "The build UUID from deepgram_list_models with One Row per Build on.": "The build UUID from deepgram_list_models with One Row per Build on.",+ "A project ID from List Projects (list_projects) to read a custom model of that project. Leave empty for the public catalog.": "A project ID from List Projects (list_projects) to read a custom model of that project. Leave empty for the public catalog.",+ "The Deepgram project ID, from List Projects (list_projects). Leave empty when the API key belongs to a single project.": "The Deepgram project ID, from List Projects (list_projects). Leave empty when the API key belongs to a single project.",+ "Only count requests made with this API key ID.": "Only count requests made with this API key ID.",+ "Only count requests with this tag, from deepgram_list_usage_fields.": "Only count requests with this tag, from deepgram_list_usage_fields.",+ "Only count requests to this model build, using a model_id from deepgram_list_usage_fields.": "Only count requests to this model build, using a model_id from deepgram_list_usage_fields.",+ "The balance ID from deepgram_list_balances.": "The balance ID from deepgram_list_balances.",+ "How many recent purchases to return, from 1 to 1000. Defaults to 10.": "How many recent purchases to return, from 1 to 1000. Defaults to 10.","Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.","Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.","Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.","On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.","Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).","Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",+ "Payment card data (PCI)": "Payment card data (PCI)",+ "Personal information (PII)": "Personal information (PII)",+ "Health information (PHI)": "Health information (PHI)",+ "Numbers": "Numbers",+ "Extended": "Extended",+ "Strict": "Strict","bg": "bg","ca": "ca","zh": "zh",@@ -50,6 +227,7 @@"da-DK": "da-DK","nl": "nl","nl-BE": "nl-BE",+ "en": "en","en-US": "en-US","en-AU": "en-AU","en-GB": "en-GB",@@ -92,6 +270,8 @@"tr": "tr","uk": "uk","vi": "vi",+ "POST": "POST",+ "PUT": "PUT","linear16": "linear16","flac": "flac","mulaw": "mulaw",@@ -99,10 +279,37 @@"mp3": "mp3","opus": "opus","aac": "aac",+ "WAV": "WAV",+ "None (raw audio)": "None (raw audio)",+ "MP3": "MP3",+ "Linear PCM 16-bit (WAV)": "Linear PCM 16-bit (WAV)",+ "FLAC": "FLAC",+ "μ-law (WAV)": "μ-law (WAV)",+ "A-law (WAV)": "A-law (WAV)",+ "Opus (OGG)": "Opus (OGG)",+ "AAC": "AAC",+ "Speech to text and voices": "Speech to text and voices",+ "Speech to text models": "Speech to text models",+ "Text to speech voices": "Text to speech voices",+ "Active": "Active",+ "Expired": "Expired",+ "Speech to text (listen)": "Speech to text (listen)",+ "Text intelligence (read)": "Text intelligence (read)",+ "Text to speech (speak)": "Text to speech (speak)",+ "Voice agent (agent)": "Voice agent (agent)",+ "Synchronous": "Synchronous",+ "Callback (async)": "Callback (async)",+ "Streaming": "Streaming",+ "Succeeded": "Succeeded",+ "Failed": "Failed",+ "API key (accessor)": "API key (accessor)",+ "Feature set": "Feature set",+ "Line item": "Line item",+ "Hosted": "Hosted",+ "Beta": "Beta",+ "Self-hosted": "Self-hosted","GET": "GET",- "POST": "POST","PATCH": "PATCH",- "PUT": "PUT","DELETE": "DELETE","HEAD": "HEAD"}\ No newline at end of filediff --git a/packages/pieces/community/deepgram/src/index.ts b/packages/pieces/community/deepgram/src/index.tsindex 0a40f66aa0f..40b4c9965b9 100644--- a/packages/pieces/community/deepgram/src/index.ts+++ b/packages/pieces/community/deepgram/src/index.ts@@ -4,9 +4,38 @@ import { createSummaryAction } from './actions/create-summary';import { createTranscriptionCallbackAction } from './actions/create-transcription';import { listProjectsAction } from './actions/list-projects';import { textToSpeechAction } from './actions/text-to-speech';+import { transcribeAudioAction } from './actions/transcribe-audio';+import { analyzeTextAction } from './actions/analyze-text';+import { listModelsAction } from './actions/list-models';+import { getProjectAction } from './actions/get-project';+import { updateProjectAction } from './actions/update-project';+import { listProjectMembersAction } from './actions/list-project-members';+import { listProjectKeysAction } from './actions/list-project-keys';+import { listRequestsAction } from './actions/list-requests';+import { getRequestAction } from './actions/get-request';+import { getUsageAction } from './actions/get-usage';+import { getBalancesAction } from './actions/get-balances';+import { getBillingBreakdownAction } from './actions/get-billing-breakdown';+import { generateSpeechAction } from './actions/ai/generate-speech';+import { transcribeAudioAiAction } from './actions/ai/transcribe-audio';+import { listModelsAiAction } from './actions/ai/list-models';+import { getModelAction } from './actions/ai/get-model';+import { listRequestsAiAction } from './actions/ai/list-requests';+import { getRequestAiAction } from './actions/ai/get-request';+import { listProjectMembersAiAction } from './actions/ai/list-project-members';+import { getUsageBreakdownAiAction } from './actions/ai/get-usage-breakdown';+import { getUsageSummaryAction } from './actions/ai/get-usage-summary';+import { listUsageFieldsAction } from './actions/ai/list-usage-fields';+import { listBalancesAiAction } from './actions/ai/list-balances';+import { getBalanceAction } from './actions/ai/get-balance';+import { getBillingBreakdownAiAction } from './actions/ai/get-billing-breakdown';+import { listBillingFieldsAction } from './actions/ai/list-billing-fields';+import { listPurchasesAction } from './actions/ai/list-purchases';+import { listThinkModelsAction } from './actions/ai/list-think-models';import { PieceCategory } from '@activepieces/pieces-framework';import { createCustomApiCallAction } from '@activepieces/pieces-common';import { BASE_URL } from './common/constants';+import { deepgramClient } from './common/client';export const deepgramPiece = createPiece({displayName: 'Deepgram',@@ -14,22 +43,46 @@ export const deepgramPiece = createPiece({description:'Deepgram is an AI-powered speech recognition platform that provides real-time transcription, text-to-speech, and audio analysis capabilities.',categories: [PieceCategory.ARTIFICIAL_INTELLIGENCE],- minimumSupportedRelease: '0.30.0',+ minimumSupportedRelease: '0.88.2',authors: ['Ani-4x', 'kishanprmr'],auth: deepgramAuth,actions: [+ transcribeAudioAction,+ analyzeTextAction,createSummaryAction,createTranscriptionCallbackAction,- listProjectsAction,textToSpeechAction,+ generateSpeechAction,+ listModelsAction,+ listProjectsAction,+ getProjectAction,+ updateProjectAction,+ listProjectMembersAction,+ listProjectKeysAction,+ listRequestsAction,+ getRequestAction,+ getUsageAction,+ getBalancesAction,+ getBillingBreakdownAction,+ transcribeAudioAiAction,+ listModelsAiAction,+ getModelAction,+ listRequestsAiAction,+ getRequestAiAction,+ listProjectMembersAiAction,+ getUsageBreakdownAiAction,+ getUsageSummaryAction,+ listUsageFieldsAction,+ listBalancesAiAction,+ getBalanceAction,+ getBillingBreakdownAiAction,+ listBillingFieldsAction,+ listPurchasesAction,+ listThinkModelsAction,createCustomApiCallAction({auth: deepgramAuth,baseUrl: () => BASE_URL,- authMapping: async (auth) => {- return {- Authorization: `Token ${auth.secret_text}`,- };- },+ authMapping: async (auth) => deepgramClient.authHeader(auth.secret_text),}),],triggers: [],diff --git a/packages/pieces/community/deepgram/src/output-schemas.ts b/packages/pieces/community/deepgram/src/output-schemas.tsnew file mode 100644index 00000000000..ca3b53db427--- /dev/null+++ b/packages/pieces/community/deepgram/src/output-schemas.ts@@ -0,0 +1,529 @@+import { OutputSchema } from '@activepieces/pieces-framework';++const topicFields: OutputSchema['fields'] = [+ { key: 'topic', label: 'Topic' },+ { key: 'confidence', label: 'Confidence', format: 'number' },+ { key: 'text', label: 'Text' },+];++const intentFields: OutputSchema['fields'] = [+ { key: 'intent', label: 'Intent' },+ { key: 'confidence', label: 'Confidence', format: 'number' },+ { key: 'text', label: 'Text' },+];++const requestRowFields: OutputSchema['fields'] = [+ { key: 'request_id', label: 'Request ID' },+ { key: 'created', label: 'Created', format: 'datetime' },+ { key: 'completed', label: 'Completed', format: 'datetime' },+ { key: 'endpoint', label: 'Endpoint' },+ { key: 'path', label: 'Path' },+ { key: 'api_key_id', label: 'API Key ID' },+ { key: 'status_code', label: 'Status Code', format: 'number' },+ { key: 'method', label: 'Method' },+ { key: 'deployment', label: 'Deployment' },+ { key: 'duration_seconds', label: 'Duration (seconds)', format: 'number' },+ {+ key: 'total_audio_seconds',+ label: 'Total Audio (seconds)',+ format: 'number',+ },+ { key: 'channels', label: 'Channels', format: 'number' },+ { key: 'usd', label: 'Cost', format: 'currency', currency: 'USD' },+ { key: 'models', label: 'Models' },+ { key: 'features', label: 'Features' },+ { key: 'tags', label: 'Tags' },+ { key: 'tier', label: 'Tier' },+ {+ key: 'callback_status_code',+ label: 'Callback Response Code',+ format: 'number',+ },+ { key: 'callback_attempts', label: 'Callback Attempts', format: 'number' },+];++const projectFields: OutputSchema['fields'] = [+ { key: 'project_id', label: 'Project ID' },+ { key: 'name', label: 'Name' },+ { key: 'mip_opt_out', label: 'Model Improvement Opt-Out', format: 'boolean' },+];++const speechFields: OutputSchema['fields'] = [+ { key: 'file', label: 'Audio File', format: 'url' },+ { key: 'file_name', label: 'File Name' },+ { key: 'content_type', label: 'Content Type' },+ { key: 'size_bytes', label: 'Size', format: 'filesize' },+ { key: 'characters', label: 'Characters Billed', format: 'number' },+ { key: 'request_id', label: 'Request ID' },+ { key: 'model', label: 'Voice' },+ { key: 'encoding', label: 'Encoding' },+];++export const listProjectsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'projects',+ label: 'Projects',+ labelKey: 'name',+ listItems: [+ { key: 'project_id', label: 'Project ID' },+ { key: 'name', label: 'Name' },+ {+ key: 'mip_opt_out',+ label: 'Model Improvement Opt-Out',+ format: 'boolean',+ },+ { key: 'allowed_providers', label: 'Allowed Providers' },+ ],+ },+ ],+};++export const projectOutputSchema: OutputSchema = {+ fields: projectFields,+};++export const updateProjectOutputSchema: OutputSchema = {+ fields: [...projectFields, { key: 'message', label: 'Message' }],+};++export const listMembersOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'members',+ label: 'Members',+ labelKey: 'email',+ listItems: [+ { key: 'member_id', label: 'Member ID' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'first_name', label: 'First Name' },+ { key: 'last_name', label: 'Last Name' },+ { key: 'scopes', label: 'Scopes' },+ ],+ },+ ],+};++export const listKeysOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'keys',+ label: 'API Keys',+ labelKey: 'comment',+ listItems: [+ { key: 'api_key_id', label: 'API Key ID' },+ { key: 'comment', label: 'Comment' },+ { key: 'scopes', label: 'Scopes' },+ { key: 'created', label: 'Created', format: 'datetime' },+ { key: 'expiration_date', label: 'Expires', format: 'datetime' },+ { key: 'member_id', label: 'Member ID' },+ { key: 'member_email', label: 'Member Email', format: 'email' },+ ],+ },+ ],+};++export const listRequestsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'requests',+ label: 'Requests',+ labelKey: 'request_id',+ listItems: requestRowFields,+ },+ { key: 'page', label: 'Page', format: 'number' },+ { key: 'limit', label: 'Limit', format: 'number' },+ { key: 'has_more', label: 'Has More', format: 'boolean' },+ ],+};++export const requestOutputSchema: OutputSchema = {+ fields: requestRowFields,+};++export const usageOutputSchema: OutputSchema = {+ fields: [+ { key: 'start', label: 'Start', format: 'date' },+ { key: 'end', label: 'End', format: 'date' },+ { key: 'resolution', label: 'Resolution' },+ { key: 'total_hours', label: 'Total Hours', format: 'number' },+ { key: 'total_requests', label: 'Total Requests', format: 'number' },+ {+ key: 'total_tts_characters',+ label: 'Total TTS Characters',+ format: 'number',+ },+ { key: 'total_tokens_in', label: 'Total Tokens In', format: 'number' },+ { key: 'total_tokens_out', label: 'Total Tokens Out', format: 'number' },+ {+ key: 'results',+ label: 'Rows',+ labelKey: 'start',+ listItems: [+ { key: 'start', label: 'Start', format: 'date' },+ { key: 'end', label: 'End', format: 'date' },+ { key: 'hours', label: 'Hours', format: 'number' },+ { key: 'total_hours', label: 'Total Hours', format: 'number' },+ { key: 'agent_hours', label: 'Agent Hours', format: 'number' },+ { key: 'requests', label: 'Requests', format: 'number' },+ { key: 'tts_characters', label: 'TTS Characters', format: 'number' },+ { key: 'tokens_in', label: 'Tokens In', format: 'number' },+ { key: 'tokens_out', label: 'Tokens Out', format: 'number' },+ { key: 'endpoint', label: 'Endpoint' },+ { key: 'method', label: 'Method' },+ { key: 'models', label: 'Models' },+ { key: 'tags', label: 'Tags' },+ { key: 'accessor', label: 'API Key (Accessor)' },+ { key: 'feature_set', label: 'Feature Set' },+ { key: 'deployment', label: 'Deployment' },+ ],+ },+ ],+};++export const balancesOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'balances',+ label: 'Balances',+ labelKey: 'balance_id',+ listItems: [+ { key: 'balance_id', label: 'Balance ID' },+ { key: 'amount', label: 'Amount', format: 'number' },+ { key: 'units', label: 'Units' },+ { key: 'purchase_order_id', label: 'Purchase Order ID' },+ ],+ },+ ],+};++export const billingOutputSchema: OutputSchema = {+ fields: [+ { key: 'start', label: 'Start', format: 'date' },+ { key: 'end', label: 'End', format: 'date' },+ {+ key: 'total_dollars',+ label: 'Total',+ format: 'currency',+ currency: 'USD',+ },+ {+ key: 'results',+ label: 'Rows',+ labelKey: 'line_item',+ listItems: [+ {+ key: 'dollars',+ label: 'Amount',+ format: 'currency',+ currency: 'USD',+ },+ { key: 'start', label: 'Start', format: 'date' },+ { key: 'end', label: 'End', format: 'date' },+ { key: 'line_item', label: 'Line Item' },+ { key: 'accessor', label: 'API Key (Accessor)' },+ { key: 'deployment', label: 'Deployment' },+ { key: 'tags', label: 'Tags' },+ ],+ },+ ],+};++const modelRowFields: OutputSchema['fields'] = [+ { key: 'canonical_name', label: 'Model ID' },+ { key: 'type', label: 'Type' },+ { key: 'name', label: 'Name' },+ { key: 'architecture', label: 'Architecture' },+ { key: 'languages', label: 'Languages' },+ { key: 'version', label: 'Version' },+ { key: 'batch', label: 'Pre-recorded', format: 'boolean' },+ { key: 'streaming', label: 'Streaming', format: 'boolean' },+ { key: 'accent', label: 'Accent' },+ { key: 'age', label: 'Age' },+ { key: 'gender', label: 'Gender' },+ { key: 'voice_tags', label: 'Voice Traits' },+ { key: 'sample_url', label: 'Sample', format: 'url' },+];++export const listModelsOutputSchema: OutputSchema = {+ fields: [+ { key: 'count', label: 'Count', format: 'number' },+ {+ key: 'models',+ label: 'Models',+ labelKey: 'canonical_name',+ listItems: modelRowFields,+ },+ ],+};++export const listModelBuildsOutputSchema: OutputSchema = {+ fields: [+ { key: 'count', label: 'Count', format: 'number' },+ {+ key: 'models',+ label: 'Models',+ labelKey: 'canonical_name',+ listItems: [{ key: 'uuid', label: 'Build UUID' }, ...modelRowFields],+ },+ ],+};++export const transcribeAudioOutputSchema: OutputSchema = {+ fields: [+ { key: 'request_id', label: 'Request ID' },+ { key: 'transcript', label: 'Transcript' },+ { key: 'confidence', label: 'Confidence', format: 'number' },+ { key: 'duration_seconds', label: 'Duration (seconds)', format: 'number' },+ { key: 'detected_language', label: 'Detected Language' },+ {+ key: 'language_confidence',+ label: 'Language Confidence',+ format: 'number',+ },+ { key: 'model_name', label: 'Model' },+ { key: 'model_version', label: 'Model Version' },+ { key: 'channel_count', label: 'Channels', format: 'number' },+ { key: 'paragraphs_text', label: 'Transcript with Paragraphs' },+ { key: 'speaker_count', label: 'Speakers', format: 'number' },+ { key: 'speaker_transcript', label: 'Transcript by Speaker' },+ { key: 'summary', label: 'Summary' },+ {+ key: 'topics',+ label: 'Topics',+ labelKey: 'topic',+ listItems: topicFields,+ },+ {+ key: 'intents',+ label: 'Intents',+ labelKey: 'intent',+ listItems: intentFields,+ },+ { key: 'sentiment', label: 'Overall Sentiment' },+ { key: 'sentiment_score', label: 'Sentiment Score', format: 'number' },+ {+ key: 'utterances',+ label: 'Utterances',+ labelKey: 'transcript',+ listItems: [+ { key: 'speaker', label: 'Speaker', format: 'number' },+ { key: 'channel', label: 'Channel', format: 'number' },+ { key: 'start', label: 'Start (seconds)', format: 'number' },+ { key: 'end', label: 'End (seconds)', format: 'number' },+ { key: 'confidence', label: 'Confidence', format: 'number' },+ { key: 'transcript', label: 'Transcript' },+ ],+ },+ {+ key: 'channels',+ label: 'Channel Transcripts',+ labelKey: 'channel',+ listItems: [+ { key: 'channel', label: 'Channel', format: 'number' },+ { key: 'transcript', label: 'Transcript' },+ { key: 'confidence', label: 'Confidence', format: 'number' },+ { key: 'detected_language', label: 'Detected Language' },+ ],+ },+ {+ key: 'entities',+ label: 'Entities',+ labelKey: 'value',+ listItems: [+ { key: 'label', label: 'Type' },+ { key: 'value', label: 'Value' },+ { key: 'confidence', label: 'Confidence', format: 'number' },+ { key: 'channel', label: 'Channel', format: 'number' },+ ],+ },+ {+ key: 'words',+ label: 'Words',+ labelKey: 'punctuated_word',+ listItems: [+ { key: 'word', label: 'Word' },+ { key: 'punctuated_word', label: 'Punctuated Word' },+ { key: 'start', label: 'Start (seconds)', format: 'number' },+ { key: 'end', label: 'End (seconds)', format: 'number' },+ { key: 'confidence', label: 'Confidence', format: 'number' },+ { key: 'speaker', label: 'Speaker', format: 'number' },+ { key: 'channel', label: 'Channel', format: 'number' },+ ],+ },+ { key: 'warnings', label: 'Warnings' },+ ],+};++export const analyzeTextOutputSchema: OutputSchema = {+ fields: [+ { key: 'request_id', label: 'Request ID' },+ { key: 'language', label: 'Language' },+ { key: 'summary', label: 'Summary' },+ {+ key: 'topics',+ label: 'Topics',+ labelKey: 'topic',+ listItems: topicFields,+ },+ {+ key: 'intents',+ label: 'Intents',+ labelKey: 'intent',+ listItems: intentFields,+ },+ { key: 'sentiment', label: 'Overall Sentiment' },+ { key: 'sentiment_score', label: 'Sentiment Score', format: 'number' },+ {+ key: 'sentiment_segments',+ label: 'Sentiment by Segment',+ labelKey: 'sentiment',+ listItems: [+ { key: 'text', label: 'Text' },+ { key: 'sentiment', label: 'Sentiment' },+ { key: 'sentiment_score', label: 'Score', format: 'number' },+ ],+ },+ { key: 'input_tokens', label: 'Input Tokens', format: 'number' },+ { key: 'output_tokens', label: 'Output Tokens', format: 'number' },+ ],+};++export const createTranscriptionCallbackOutputSchema: OutputSchema = {+ fields: [+ { key: 'requestId', label: 'Request ID' },+ { key: 'callbackUrl', label: 'Callback URL' },+ { key: 'status', label: 'Status' },+ ],+};++export const textToSpeechOutputSchema: OutputSchema = {+ fields: speechFields,+};++export const generateSpeechOutputSchema: OutputSchema = {+ fields: speechFields,+};++export const modelOutputSchema: OutputSchema = {+ fields: [{ key: 'uuid', label: 'Build UUID' }, ...modelRowFields],+};++export const balanceOutputSchema: OutputSchema = {+ fields: [+ { key: 'balance_id', label: 'Balance ID' },+ { key: 'amount', label: 'Amount', format: 'number' },+ { key: 'units', label: 'Units' },+ { key: 'purchase_order_id', label: 'Purchase Order ID' },+ ],+};++export const usageSummaryOutputSchema: OutputSchema = {+ fields: [+ { key: 'start', label: 'Start', format: 'date' },+ { key: 'end', label: 'End', format: 'date' },+ { key: 'resolution', label: 'Resolution' },+ { key: 'total_hours', label: 'Total Hours', format: 'number' },+ { key: 'total_requests', label: 'Total Requests', format: 'number' },+ {+ key: 'total_tts_characters',+ label: 'Total TTS Characters',+ format: 'number',+ },+ {+ key: 'total_tts_requests',+ label: 'Total TTS Requests',+ format: 'number',+ },+ { key: 'total_tokens_in', label: 'Total Tokens In', format: 'number' },+ { key: 'total_tokens_out', label: 'Total Tokens Out', format: 'number' },+ {+ key: 'results',+ label: 'Days',+ labelKey: 'start',+ listItems: [+ { key: 'start', label: 'Start', format: 'date' },+ { key: 'end', label: 'End', format: 'date' },+ { key: 'hours', label: 'Hours', format: 'number' },+ { key: 'total_hours', label: 'Total Hours', format: 'number' },+ { key: 'requests', label: 'Requests', format: 'number' },+ { key: 'tts_characters', label: 'TTS Characters', format: 'number' },+ { key: 'tts_requests', label: 'TTS Requests', format: 'number' },+ { key: 'tokens_in', label: 'Tokens In', format: 'number' },+ { key: 'tokens_out', label: 'Tokens Out', format: 'number' },+ ],+ },+ ],+};++export const usageFieldsOutputSchema: OutputSchema = {+ fields: [+ { key: 'accessors', label: 'API Key IDs' },+ { key: 'tags', label: 'Tags' },+ {+ key: 'models',+ label: 'Model Builds',+ labelKey: 'name',+ listItems: [+ { key: 'model_id', label: 'Model UUID' },+ { key: 'name', label: 'Name' },+ { key: 'language', label: 'Language' },+ { key: 'version', label: 'Version' },+ ],+ },+ { key: 'processing_methods', label: 'Processing Methods' },+ { key: 'features', label: 'Features' },+ ],+};++export const billingFieldsOutputSchema: OutputSchema = {+ fields: [+ { key: 'accessors', label: 'API Key IDs' },+ { key: 'deployments', label: 'Deployments' },+ { key: 'tags', label: 'Tags' },+ {+ key: 'line_items',+ label: 'Line Items',+ labelKey: 'line_item',+ listItems: [+ { key: 'line_item', label: 'Line Item' },+ { key: 'description', label: 'Description' },+ ],+ },+ ],+};++export const purchasesOutputSchema: OutputSchema = {+ fields: [+ { key: 'count', label: 'Count', format: 'number' },+ {+ key: 'orders',+ label: 'Purchases',+ labelKey: 'order_id',+ listItems: [+ { key: 'order_id', label: 'Order ID' },+ { key: 'created', label: 'Created', format: 'datetime' },+ { key: 'expiration', label: 'Expires', format: 'datetime' },+ { key: 'amount', label: 'Amount', format: 'number' },+ { key: 'units', label: 'Units' },+ { key: 'order_type', label: 'Order Type' },+ ],+ },+ ],+};++export const thinkModelsOutputSchema: OutputSchema = {+ fields: [+ { key: 'count', label: 'Count', format: 'number' },+ {+ key: 'models',+ label: 'Models',+ labelKey: 'name',+ listItems: [+ { key: 'id', label: 'Model ID' },+ { key: 'name', label: 'Name' },+ { key: 'provider', label: 'Provider' },+ ],+ },+ ],+};diff --git a/packages/pieces/community/deepgram/test/atomics.test.ts b/packages/pieces/community/deepgram/test/atomics.test.tsnew file mode 100644index 00000000000..7245895df0d--- /dev/null+++ b/packages/pieces/community/deepgram/test/atomics.test.ts@@ -0,0 +1,538 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { transcribeAudioAction } from '../src/actions/transcribe-audio';+import { listModelsAction } from '../src/actions/list-models';+import { listRequestsAction } from '../src/actions/list-requests';+import { getRequestAction } from '../src/actions/get-request';+import { getUsageAction } from '../src/actions/get-usage';+import { getBalancesAction } from '../src/actions/get-balances';+import { getBillingBreakdownAction } from '../src/actions/get-billing-breakdown';+import { listProjectMembersAction } from '../src/actions/list-project-members';+import { transcribeAudioAiAction } from '../src/actions/ai/transcribe-audio';+import { listModelsAiAction } from '../src/actions/ai/list-models';+import { getModelAction } from '../src/actions/ai/get-model';+import { listRequestsAiAction } from '../src/actions/ai/list-requests';+import { getRequestAiAction } from '../src/actions/ai/get-request';+import { listProjectMembersAiAction } from '../src/actions/ai/list-project-members';+import { getUsageBreakdownAiAction } from '../src/actions/ai/get-usage-breakdown';+import { getUsageSummaryAction } from '../src/actions/ai/get-usage-summary';+import { listUsageFieldsAction } from '../src/actions/ai/list-usage-fields';+import { listBalancesAiAction } from '../src/actions/ai/list-balances';+import { getBalanceAction } from '../src/actions/ai/get-balance';+import { getBillingBreakdownAiAction } from '../src/actions/ai/get-billing-breakdown';+import { listBillingFieldsAction } from '../src/actions/ai/list-billing-fields';+import { listPurchasesAction } from '../src/actions/ai/list-purchases';+import { listThinkModelsAction } from '../src/actions/ai/list-think-models';+import { API_KEY, runAction, stubFetch } from './helpers';++afterEach(() => {+ vi.unstubAllGlobals();+});++const API = 'https://api.deepgram.com/v1';+const ONE_PROJECT = { projects: [{ project_id: 'p-1', name: 'Main' }] };++const twinPairs = [+ [transcribeAudioAction, transcribeAudioAiAction, ['model']],+ [listModelsAction, listModelsAiAction, ['project']],+ [listRequestsAction, listRequestsAiAction, ['project']],+ [getRequestAction, getRequestAiAction, ['project']],+ [getUsageAction, getUsageBreakdownAiAction, ['project']],+ [getBalancesAction, listBalancesAiAction, ['project']],+ [getBillingBreakdownAction, getBillingBreakdownAiAction, ['project']],+ [listProjectMembersAction, listProjectMembersAiAction, ['project']],+] as const;++describe('twins', () => {+ test.each(twinPairs)(+ 'keep every other prop of the original unchanged',+ (original, twin, swapped) => {+ for (const [key, prop] of Object.entries(original.props)) {+ if (swapped.some((name) => name === key)) {+ continue;+ }+ expect(Reflect.get(twin.props, key), `${twin.name}.${key}`).toBe(prop);+ }+ expect(twin.outputSchema).toBeDefined();+ expect(twin.audience).toBe('ai');+ expect(original.audience).toBe('human');+ }+ );++ test.each(twinPairs.filter(([, , swapped]) => swapped[0] === 'project'))(+ 'swap the project dropdown for a ShortText project_id',+ (_original, twin) => {+ expect(Reflect.get(twin.props, 'project')).toBeUndefined();+ expect(Reflect.get(twin.props, 'project_id')?.type).toBe('SHORT_TEXT');+ }+ );++ test('transcribe twin takes model as text and defaults to nova-3', async () => {+ expect(transcribeAudioAiAction.props.model.type).toBe('SHORT_TEXT');+ const seen = stubFetch(() => ({+ body: { metadata: { request_id: 'r-1' }, results: { channels: [] } },+ }));+ await runAction({+ action: transcribeAudioAiAction,+ propsValue: {+ audioUrl: 'https://cdn.test/a.wav',+ model: 'nova-3-general',+ },+ });+ expect(seen[0].url).toBe(+ `${API}/listen?model=nova-3-general&smart_format=true`+ );+ expect(seen[0].json).toEqual({ url: 'https://cdn.test/a.wav' });+ await runAction({+ action: transcribeAudioAiAction,+ propsValue: { audioUrl: 'https://cdn.test/a.wav' },+ });+ expect(seen[1].url).toContain('model=nova-3&');+ });++ test.each([+ [listRequestsAiAction, '/requests?limit=50&page=0', {}],+ [getRequestAiAction, '/requests/req-1', { requestId: 'req-1' }],+ [getUsageBreakdownAiAction, '/usage/breakdown', {}],+ [listBalancesAiAction, '/balances', {}],+ [getBillingBreakdownAiAction, '/billing/breakdown', {}],+ [listProjectMembersAiAction, '/members', {}],+ ] as const)(+ '%s uses the given project ID without listing projects',+ async (action, path, extra) => {+ const seen = stubFetch(() => ({ body: { request_id: 'req-1' } }));+ await runAction({ action, propsValue: { project_id: 'p 9', ...extra } });+ expect(seen.map((request) => request.url)).toEqual([+ `${API}/projects/p%209${path}`,+ ]);+ }+ );++ test('auto-resolves an empty project_id on a single-project key', async () => {+ const seen = stubFetch((request) =>+ request.url.endsWith('/projects')+ ? { body: ONE_PROJECT }+ : { body: { members: [{ member_id: 'm-1', scopes: ['owner'] }] } }+ );+ const result = await runAction({+ action: listProjectMembersAiAction,+ propsValue: { project_id: '' },+ });+ expect(seen.map((request) => request.url)).toEqual([+ `${API}/projects`,+ `${API}/projects/p-1/members`,+ ]);+ expect(result).toEqual({+ members: [+ {+ member_id: 'm-1',+ email: null,+ first_name: null,+ last_name: null,+ scopes: 'owner',+ },+ ],+ });+ });+});++const catalog = {+ stt: [+ {+ name: 'general',+ canonical_name: 'nova-3-general',+ architecture: 'nova-3',+ languages: ['en'],+ version: '2025-01-01.0',+ uuid: 'u-en',+ batch: true,+ streaming: true,+ },+ {+ name: 'general',+ canonical_name: 'nova-3-general',+ architecture: 'nova-3',+ languages: ['gl'],+ version: '2026-10-06.5364',+ uuid: 'u-gl',+ batch: true,+ streaming: true,+ },+ ],+ tts: [+ {+ name: 'thalia',+ canonical_name: 'aura-2-thalia-en',+ architecture: 'aura-2',+ languages: ['en'],+ version: '2025-01-01.0',+ uuid: 'u-thalia',+ metadata: { display_name: 'Thalia', tags: ['feminine'] },+ },+ ],+};++describe('deepgram_list_models', () => {+ test('empty project ID reads the public catalog and never lists projects', async () => {+ const seen = stubFetch(() => ({ body: catalog }));+ const result = await runAction({+ action: listModelsAiAction,+ propsValue: { type: 'stt' },+ });+ expect(seen.map((request) => request.url)).toEqual([`${API}/models`]);+ expect(result).toMatchObject({ count: 1 });+ expect(JSON.stringify(result)).not.toContain('uuid');+ });++ test('perBuild returns one row per build with its UUID', async () => {+ stubFetch(() => ({ body: catalog }));+ const result = await runAction({+ action: listModelsAiAction,+ propsValue: { type: 'all', perBuild: true, language: 'gl' },+ });+ expect(result).toMatchObject({+ count: 1,+ models: [{ uuid: 'u-gl', languages: 'gl' }],+ });+ const all = await runAction({+ action: listModelsAiAction,+ propsValue: { type: 'all', perBuild: true },+ });+ expect(JSON.stringify(all).match(/u-[a-z]+/g)).toEqual([+ 'u-en',+ 'u-gl',+ 'u-thalia',+ ]);+ });++ test('a project ID switches to the project catalog', async () => {+ const seen = stubFetch(() => ({ body: catalog }));+ await runAction({+ action: listModelsAiAction,+ propsValue: { type: 'tts', project_id: 'p-1', includeOutdated: true },+ });+ expect(seen[0].url).toBe(+ `${API}/projects/p-1/models?include_outdated=true`+ );+ });+});++describe('deepgram_get_model', () => {+ test('reads the public build by UUID', async () => {+ const seen = stubFetch(() => ({ body: catalog.stt[1] }));+ const result = await runAction({+ action: getModelAction,+ propsValue: { model_id: ' u-gl ' },+ });+ expect(seen[0].url).toBe(`${API}/models/u-gl`);+ expect(result).toMatchObject({+ uuid: 'u-gl',+ canonical_name: 'nova-3-general',+ type: 'stt',+ languages: 'gl',+ version: '2026-10-06.5364',+ batch: true,+ });+ });++ test('reads a project build and recognises voices', async () => {+ const seen = stubFetch(() => ({ body: catalog.tts[0] }));+ const result = await runAction({+ action: getModelAction,+ propsValue: { model_id: 'u-thalia', project_id: 'p-1' },+ });+ expect(seen[0].url).toBe(`${API}/projects/p-1/models/u-thalia`);+ expect(result).toMatchObject({ type: 'tts', name: 'Thalia', batch: null });+ });++ test('refuses an empty ID before calling Deepgram', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(+ runAction({ action: getModelAction, propsValue: { model_id: ' ' } })+ ).rejects.toThrow('Enter a model UUID.');+ expect(seen).toEqual([]);+ });+});++describe('usage atomics', () => {+ test('usage summary sends every filter and strips a tag= prefix', async () => {+ const seen = stubFetch(() => ({+ body: {+ start: '2026-10-01',+ end: '2026-10-11',+ resolution: { units: 'day', amount: 1 },+ results: [+ {+ start: '2026-10-11',+ end: '2026-10-11',+ hours: 0.0072,+ total_hours: 0.0072,+ requests: 2,+ tokens: { in: 3, out: 4 },+ tts: { characters: 9, requests: 1 },+ },+ ],+ },+ }));+ const result = await runAction({+ action: getUsageSummaryAction,+ propsValue: {+ project_id: 'p-1',+ start: '2026-10-01T10:00:00Z',+ end: '2026-10-11',+ accessor: 'key-1',+ tag: 'tag=aptest',+ model: 'u-en',+ endpoint: 'listen',+ method: 'sync',+ deployment: 'hosted',+ },+ });+ expect(seen[0].url).toBe(+ `${API}/projects/p-1/usage?start=2026-10-01&end=2026-10-11&accessor=key-1&tag=aptest&model=u-en&endpoint=listen&method=sync&deployment=hosted`+ );+ expect(result).toMatchObject({+ start: '2026-10-01',+ end: '2026-10-11',+ resolution: '1 day',+ total_hours: 0.0072,+ total_requests: 2,+ total_tts_characters: 9,+ total_tts_requests: 1,+ total_tokens_in: 3,+ total_tokens_out: 4,+ results: [+ {+ start: '2026-10-11',+ end: '2026-10-11',+ hours: 0.0072,+ total_hours: 0.0072,+ requests: 2,+ tts_characters: 9,+ tts_requests: 1,+ tokens_in: 3,+ tokens_out: 4,+ },+ ],+ });+ });++ test('usage summary rejects a reversed range', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(+ runAction({+ action: getUsageSummaryAction,+ propsValue: {+ project_id: 'p-1',+ start: '2026-10-11',+ end: '2026-10-01',+ },+ })+ ).rejects.toThrow('start date');+ expect(seen).toEqual([]);+ });++ test('usage fields flattens models and strips tag= prefixes', async () => {+ const seen = stubFetch(() => ({+ body: {+ accessors: ['key-1'],+ tags: ['tag=dev', 'dev', 'prod'],+ models: [+ { name: 'general', language: 'en', version: 'v1', model_id: 'u-en' },+ ],+ processing_methods: ['sync'],+ features: ['smart_format'],+ },+ }));+ const result = await runAction({+ action: listUsageFieldsAction,+ propsValue: { project_id: 'p-1', start: '2026-10-01' },+ });+ expect(seen[0].url).toBe(+ `${API}/projects/p-1/usage/fields?start=2026-10-01`+ );+ expect(result).toEqual({+ accessors: ['key-1'],+ tags: ['dev', 'prod'],+ models: [+ { model_id: 'u-en', name: 'general', language: 'en', version: 'v1' },+ ],+ processing_methods: ['sync'],+ features: ['smart_format'],+ });+ });+});++describe('billing atomics', () => {+ test('billing fields flattens the line_items map to rows', async () => {+ const seen = stubFetch((request) => ({+ body: request.url.endsWith('/projects')+ ? ONE_PROJECT+ : {+ accessors: ['key-1'],+ deployments: ['hosted'],+ tags: ['dev'],+ line_items: { 'sync::aura': 'Aura TTS', 'async::nova': 'Nova' },+ },+ }));+ const result = await runAction({+ action: listBillingFieldsAction,+ propsValue: {},+ });+ expect(seen[0].url).toBe(`${API}/projects`);+ expect(seen[1].url).toBe(`${API}/projects/p-1/billing/fields`);+ expect(result).toEqual({+ accessors: ['key-1'],+ deployments: ['hosted'],+ tags: ['dev'],+ line_items: [+ { line_item: 'sync::aura', description: 'Aura TTS' },+ { line_item: 'async::nova', description: 'Nova' },+ ],+ });+ });++ test('billing fields tolerates a missing map', async () => {+ stubFetch(() => ({ body: {} }));+ const result = await runAction({+ action: listBillingFieldsAction,+ propsValue: { project_id: 'p-1' },+ });+ expect(result).toEqual({+ accessors: [],+ deployments: [],+ tags: [],+ line_items: [],+ });+ });++ test('purchases sends the limit and flattens orders', async () => {+ const seen = stubFetch(() => ({+ body: {+ orders: [+ {+ order_id: 'o-1',+ expiration: '2027-01-01T00:00:00Z',+ created: '2026-01-01T00:00:00Z',+ amount: 200,+ units: 'usd',+ order_type: 'promotional',+ },+ ],+ },+ }));+ const result = await runAction({+ action: listPurchasesAction,+ propsValue: { project_id: 'p-1', limit: '5' },+ });+ expect(seen[0].url).toBe(`${API}/projects/p-1/purchases?limit=5`);+ expect(result).toEqual({+ orders: [+ {+ order_id: 'o-1',+ created: '2026-01-01T00:00:00Z',+ expiration: '2027-01-01T00:00:00Z',+ amount: 200,+ units: 'usd',+ order_type: 'promotional',+ },+ ],+ count: 1,+ });+ });++ test.each([0, 1001, 2.5, 'abc'])(+ 'purchases rejects limit %s before calling Deepgram',+ async (limit) => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(+ runAction({+ action: listPurchasesAction,+ propsValue: { project_id: 'p-1', limit },+ })+ ).rejects.toThrow('Limit must be a whole number from 1 to 1000.');+ expect(seen).toEqual([]);+ }+ );++ test('purchases defaults to 10', async () => {+ const seen = stubFetch(() => ({ body: { orders: [] } }));+ const result = await runAction({+ action: listPurchasesAction,+ propsValue: { project_id: 'p-1' },+ });+ expect(seen[0].url).toBe(`${API}/projects/p-1/purchases?limit=10`);+ expect(result).toEqual({ orders: [], count: 0 });+ });++ test('get balance reads one balance by ID', async () => {+ const seen = stubFetch(() => ({+ body: { balance_id: 'b-1', amount: 199.5, units: 'usd' },+ }));+ const result = await runAction({+ action: getBalanceAction,+ propsValue: { project_id: 'p-1', balance_id: ' b-1 ' },+ });+ expect(seen[0].url).toBe(`${API}/projects/p-1/balances/b-1`);+ expect(result).toEqual({+ balance_id: 'b-1',+ amount: 199.5,+ units: 'usd',+ purchase_order_id: null,+ });+ });++ test('get balance refuses an empty ID', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(+ runAction({+ action: getBalanceAction,+ propsValue: { project_id: 'p-1', balance_id: '' },+ })+ ).rejects.toThrow('Enter a balance ID.');+ expect(seen).toEqual([]);+ });++ test('get balance relays a 403 with the role hint', async () => {+ stubFetch(() => ({+ status: 403,+ body: {+ err_code: 'INSUFFICIENT_PERMISSIONS',+ err_msg: 'no billing:read',+ },+ }));+ await expect(+ runAction({+ action: getBalanceAction,+ propsValue: { project_id: 'p-1', balance_id: 'b-1' },+ })+ ).rejects.toThrow(/HTTP 403 INSUFFICIENT_PERMISSIONS.*Admin or Owner/);+ });+});++describe('deepgram_list_think_models', () => {+ test('calls the agent host with the key and flattens models', async () => {+ const seen = stubFetch(() => ({+ body: {+ models: [+ { id: 'gpt-4o-mini', name: 'GPT-4o mini', provider: 'open_ai' },+ { id: 'claude-x', name: 'Claude', provider: 'anthropic' },+ ],+ },+ }));+ const result = await runAction({+ action: listThinkModelsAction,+ propsValue: {},+ });+ expect(seen[0].url).toBe(+ 'https://agent.deepgram.com/v1/agent/settings/think/models'+ );+ expect(seen[0].headers.get('authorization')).toBe(`Token ${API_KEY}`);+ expect(result).toEqual({+ models: [+ { id: 'gpt-4o-mini', name: 'GPT-4o mini', provider: 'open_ai' },+ { id: 'claude-x', name: 'Claude', provider: 'anthropic' },+ ],+ count: 2,+ });+ });+});diff --git a/packages/pieces/community/deepgram/test/client.test.ts b/packages/pieces/community/deepgram/test/client.test.tsnew file mode 100644index 00000000000..93b1677f586--- /dev/null+++ b/packages/pieces/community/deepgram/test/client.test.ts@@ -0,0 +1,299 @@+import { format } from 'node:util';+import { HttpMethod } from '@activepieces/pieces-common';+import { afterEach, describe, expect, test, vi } from 'vitest';+import {+ DeepgramApiError,+ deepgramClient,+ LONG_AUDIO_HINT,+} from '../src/common/client';+import { deepgramAuth } from '../src/common/auth';+import { API_KEY, stubFetch } from './helpers';++afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++describe('deepgramClient.request', () => {+ test('sends a trimmed Token header to api.deepgram.com through a certificate-checking agent', async () => {+ const seen = stubFetch(() => ({ body: { projects: [] } }));+ await deepgramClient.request({+ apiKey: ` ${API_KEY}\n`,+ method: HttpMethod.GET,+ path: '/projects',+ timeoutMs: 1000,+ operation: 'list projects',+ });+ expect(seen[0].url).toBe('https://api.deepgram.com/v1/projects');+ expect(seen[0].headers.get('authorization')).toBe(`Token ${API_KEY}`);+ expect(seen[0].headers.get('accept')).toBe('application/json');+ expect(Reflect.get(Object(seen[0].dispatcher), 'constructor')?.name).toBe(+ 'Agent'+ );+ });++ test('repeats array query parameters and skips empty ones', () => {+ const url = deepgramClient.buildUrl({+ path: '/listen',+ query: {+ model: 'nova-3',+ keyterm: ['Acme', 'Zed Co'],+ tag: [],+ language: undefined,+ redact: ['pci', 'pii'],+ smart_format: 'true',+ },+ });+ expect(url).toBe(+ 'https://api.deepgram.com/v1/listen?model=nova-3&keyterm=Acme&keyterm=Zed+Co&redact=pci&redact=pii&smart_format=true'+ );+ });++ test('maps the legacy error shape', async () => {+ stubFetch(() => ({+ status: 400,+ body: {+ err_code: 'Bad Request',+ err_msg: 'No such model/version/tier combination found.',+ request_id: 'r-1',+ },+ }));+ const error = await deepgramClient+ .request({+ apiKey: API_KEY,+ method: HttpMethod.GET,+ path: '/x',+ timeoutMs: 1000,+ operation: 'do x',+ })+ .catch((e: unknown) => e);+ expect(error).toBeInstanceOf(DeepgramApiError);+ const message = String(Reflect.get(Object(error), 'message'));+ expect(message).toBe(+ 'Deepgram could not do x (HTTP 400 Bad Request): No such model/version/tier combination found. Deepgram request ID: r-1.'+ );+ expect(Reflect.get(Object(error), 'requestId')).toBe('r-1');+ expect(Reflect.get(Object(error), 'body')).toBeUndefined();+ expect(Reflect.get(Object(error), 'responseBody')).toBeDefined();+ });++ test('maps the modern error shape with a role hint on 403', async () => {+ stubFetch(() => ({+ status: 403,+ body: {+ category: 'INSUFFICIENT_PERMISSIONS',+ message: 'Your account does not have the required scope.',+ details: "Check the 'billing:read' scope.",+ request_id: 'r-2',+ },+ }));+ await expect(+ deepgramClient.request({+ apiKey: API_KEY,+ method: HttpMethod.GET,+ path: '/x',+ timeoutMs: 1000,+ operation: 'get balances',+ })+ ).rejects.toThrow(+ /HTTP 403 INSUFFICIENT_PERMISSIONS\): Your account does not have the required scope\. - Check the 'billing:read' scope\. .*Admin or Owner/+ );+ });++ test('maps a plain-text 401 and a 402 out-of-credit error', async () => {+ stubFetch((_, index) =>+ index === 0+ ? {+ status: 401,+ text: 'Invalid credentials.',+ headers: { 'content-type': 'text/plain' },+ }+ : {+ status: 402,+ body: {+ err_code: 'ASR_PAYMENT_REQUIRED',+ err_msg: 'Project does not have enough credits.',+ },+ }+ );+ await expect(+ deepgramClient.request({+ apiKey: API_KEY,+ method: HttpMethod.GET,+ path: '/x',+ timeoutMs: 1000,+ operation: 'x',+ })+ ).rejects.toThrow(+ 'Deepgram could not x (HTTP 401): Invalid credentials. Check that the API key is correct'+ );+ await expect(+ deepgramClient.request({+ apiKey: API_KEY,+ method: HttpMethod.GET,+ path: '/x',+ timeoutMs: 1000,+ operation: 'x',+ })+ ).rejects.toThrow('out of credit');+ });++ test('uses the long-audio hint on a 504', async () => {+ stubFetch(() => ({ status: 504, text: '' }));+ await expect(+ deepgramClient.request({+ apiKey: API_KEY,+ method: HttpMethod.POST,+ path: '/listen',+ body: { url: 'https://a.io/a.mp3' },+ timeoutMs: 1000,+ operation: 'transcribe',+ timeoutHint: LONG_AUDIO_HINT,+ })+ ).rejects.toThrow(LONG_AUDIO_HINT);+ });++ test('reports a timeout in seconds', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => {+ throw Object.assign(new Error('aborted'), { name: 'AbortError' });+ })+ );+ await expect(+ deepgramClient.request({+ apiKey: API_KEY,+ method: HttpMethod.GET,+ path: '/x',+ timeoutMs: 480_000,+ operation: 'transcribe the audio',+ timeoutHint: LONG_AUDIO_HINT,+ })+ ).rejects.toThrow(+ `Deepgram did not answer within 480 seconds while trying to transcribe the audio. ${LONG_AUDIO_HINT}`+ );+ });++ test('keeps a failed 5 MB upload out of the error message and the log', async () => {+ stubFetch(() => ({+ status: 400,+ body: { err_code: 'Bad Request', err_msg: 'corrupt or unsupported data' },+ }));+ const logged: string[] = [];+ vi.spyOn(console, 'error').mockImplementation((...args: unknown[]) => {+ logged.push(format(...args));+ });+ const data = Buffer.alloc(5 * 1024 * 1024, 7);+ const error = await deepgramClient+ .request({+ apiKey: API_KEY,+ method: HttpMethod.POST,+ path: '/listen',+ body: deepgramClient.audioUploadBody(data),+ headers: { 'Content-Type': 'audio/wav' },+ timeoutMs: 1000,+ operation: 'transcribe',+ })+ .catch((e: unknown) => e);+ expect(String(Reflect.get(Object(error), 'message')).length).toBeLessThan(+ 1024+ );+ expect(logged.join('\n').length).toBeLessThan(8192);+ expect(logged.join('\n')).toContain('[audio upload, 5242880 bytes]');+ });++ test('streams the upload unchanged', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ const data = Buffer.from(+ Array.from({ length: 200_000 }, (_, index) => index % 251)+ );+ await deepgramClient.request({+ apiKey: API_KEY,+ method: HttpMethod.POST,+ path: '/listen',+ body: deepgramClient.audioUploadBody(data),+ headers: { 'Content-Type': 'audio/wav' },+ timeoutMs: 1000,+ operation: 'x',+ });+ expect(seen[0].streamed).toBe(true);+ expect(seen[0].bytes?.equals(data)).toBe(true);+ expect(seen[0].headers.get('content-type')).toBe('audio/wav');+ });+});++describe('deepgramClient.maskUrlCredentials', () => {+ test('hides user and password in plain and percent-encoded URLs', () => {+ expect(deepgramClient.maskUrlCredentials('https://u:[email protected]/cb')).toBe(+ 'https://***@x.io/cb'+ );+ expect(+ deepgramClient.maskUrlCredentials(+ '/v1/listen?callback=https%3A%2F%2Fu%3Asecret%40x.io%2Fcb&model=nova'+ )+ ).toBe('/v1/listen?callback=https%3A%2F%2F***%40x.io%2Fcb&model=nova');+ expect(deepgramClient.maskUrlCredentials('https://x.io/path@v2')).toBe(+ 'https://x.io/path@v2'+ );+ expect(deepgramClient.maskOptional(null)).toBeNull();+ });+});++describe('deepgramAuth.validate', () => {+ const validate = (auth: string) =>+ Reflect.get(Object(deepgramAuth), 'validate')({ auth });++ test('accepts a working key', async () => {+ stubFetch(() => ({ body: { projects: [] } }));+ await expect(validate('k')).resolves.toEqual({ valid: true });+ });++ test('rejects only on 401 or 403', async () => {+ stubFetch(() => ({ status: 401, text: 'Invalid credentials.' }));+ await expect(validate('k')).resolves.toEqual({+ valid: false,+ error: 'Invalid API key.',+ });+ });++ test('reports other failures as a reachability problem', async () => {+ stubFetch(() => ({ status: 503, text: 'unavailable' }));+ const result = await validate('k');+ expect(result.valid).toBe(false);+ expect(result.error).toContain('Could not reach Deepgram');+ expect(result.error).toContain('HTTP 503');+ });+});++describe('deepgramClient.maskUrlCredentials edge cases', () => {+ const mask = deepgramClient.maskUrlCredentials;+ test('masks credentials with percent-encoded characters', () => {+ expect(mask('https://alice:p%[email protected]/cb')).toBe(+ 'https://***@hooks.example.com/cb'+ );+ expect(mask('https://alice:p%[email protected]/cb')).toBe(+ 'https://***@hooks.example.com/cb'+ );+ });+ test('masks a password containing ":" and a user without a password', () => {+ expect(mask('https://alice:pa:[email protected]/cb')).toBe('https://***@x.io/cb');+ expect(mask('https://[email protected]/cb')).toBe('https://***@x.io/cb');+ });+ test('masks URLs inside free text and percent-encoded query values', () => {+ expect(+ mask('Callback https://alice:p%[email protected]/cb failed')+ ).toBe('Callback https://***@hooks.example.com/cb failed');+ expect(+ mask(+ '/v1/listen?callback=https%3A%2F%2Falice%3Ap%252Fs%40hooks.example.com%2Fcb'+ )+ ).toBe('/v1/listen?callback=https%3A%2F%2F***%40hooks.example.com%2Fcb');+ });+ test('leaves text without credentials untouched', () => {+ expect(mask('not a url at all')).toBe('not a url at all');+ expect(mask('email me at [email protected]')).toBe(+ 'email me at [email protected]'+ );+ expect(mask('https://x.io/cb?a=1')).toBe('https://x.io/cb?a=1');+ });+});diff --git a/packages/pieces/community/deepgram/test/helpers.ts b/packages/pieces/community/deepgram/test/helpers.tsnew file mode 100644index 00000000000..f6680ed6954--- /dev/null+++ b/packages/pieces/community/deepgram/test/helpers.ts@@ -0,0 +1,98 @@+import { Readable } from 'node:stream';+import { vi } from 'vitest';++export const API_KEY = 'dg-test-key';++export function stubFetch(+ respond: (request: SeenRequest, index: number) => FakeReply+): SeenRequest[] {+ const seen: SeenRequest[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const raw = init?.body;+ const isStream = raw instanceof Readable;+ const bytes = isStream ? await readAll(raw) : null;+ const text = typeof raw === 'string' ? raw : null;+ const request: SeenRequest = {+ url,+ method: (init?.method ?? 'GET').toUpperCase(),+ headers: new Headers(init?.headers),+ json: text ? JSON.parse(text) : null,+ streamed: isStream,+ bytes,+ dispatcher: Reflect.get(Object(init), 'dispatcher'),+ };+ seen.push(request);+ const reply = respond(request, seen.length - 1);+ const body =+ reply.binary !== undefined+ ? reply.binary+ : reply.text !== undefined+ ? reply.text+ : reply.body === undefined+ ? null+ : JSON.stringify(reply.body);+ return new Response(body, {+ status: reply.status ?? 200,+ headers: reply.headers ?? { 'content-type': 'application/json' },+ });+ })+ );+ return seen;+}++async function readAll(stream: Readable): Promise<Buffer> {+ const chunks: Buffer[] = [];+ for await (const chunk of stream) {+ chunks.push(Buffer.from(chunk));+ }+ return Buffer.concat(chunks);+}++export function context(propsValue: Record<string, unknown>) {+ return {+ auth: { secret_text: API_KEY, type: 'SECRET_TEXT' },+ propsValue,+ store: {},+ files: {+ write: vi.fn(+ async ({ fileName }: { fileName: string }) =>+ `https://files.test/${fileName}`+ ),+ },+ server: { apiUrl: '', publicUrl: '', token: '' },+ run: { id: 'run-1' },+ step: { name: 'step_1' },+ };+}++export async function runAction({+ action,+ propsValue,+}: {+ action: unknown;+ propsValue: Record<string, unknown>;+}): Promise<unknown> {+ const run = Reflect.get(Object(action), 'run');+ return run(context(propsValue));+}++export type SeenRequest = {+ url: string;+ method: string;+ headers: Headers;+ json: unknown;+ streamed: boolean;+ bytes: Buffer | null;+ dispatcher: unknown;+};++export type FakeReply = {+ status?: number;+ body?: unknown;+ text?: string;+ binary?: Uint8Array;+ headers?: Record<string, string>;+};diff --git a/packages/pieces/community/deepgram/test/manage.test.ts b/packages/pieces/community/deepgram/test/manage.test.tsnew file mode 100644index 00000000000..c9c7f73dbbb--- /dev/null+++ b/packages/pieces/community/deepgram/test/manage.test.ts@@ -0,0 +1,443 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { getProjectAction } from '../src/actions/get-project';+import { updateProjectAction } from '../src/actions/update-project';+import { listRequestsAction } from '../src/actions/list-requests';+import { getRequestAction } from '../src/actions/get-request';+import { getUsageAction } from '../src/actions/get-usage';+import { getBillingBreakdownAction } from '../src/actions/get-billing-breakdown';+import { getBalancesAction } from '../src/actions/get-balances';+import { listProjectKeysAction } from '../src/actions/list-project-keys';+import { listProjectMembersAction } from '../src/actions/list-project-members';+import { listProjectsAction } from '../src/actions/list-projects';+import { runAction, stubFetch } from './helpers';++afterEach(() => {+ vi.unstubAllGlobals();+});++const ONE_PROJECT = {+ projects: [{ project_id: 'p-1', name: 'Main', mip_opt_out: false }],+};++const requestRow = {+ request_id: 'req-9',+ project_uuid: 'p-1',+ created: '2026-10-11T14:46:00.000Z',+ path: '/v1/listen?callback=https%3A%2F%2Fu%3Asecret%40hooks.io%2Fcb&model=nova',+ api_key_id: 'key-1',+ response: {+ code: 200,+ completed: '2026-10-11T14:46:02.000Z',+ deployment: 'hosted:us',+ details: {+ channels: 1,+ duration: 25.9,+ total_audio: 25.9,+ method: 'async',+ models: ['m-1'],+ features: ['callback'],+ tags: ['ap'],+ usd: 0.0019,+ tier: 'nova',+ },+ },+ callback: { attempts: 10, code: 405 },+};++describe('project resolution', () => {+ test('uses the only project when none is chosen', async () => {+ const seen = stubFetch((request) =>+ request.url.endsWith('/projects')+ ? { body: ONE_PROJECT }+ : { body: { project_id: 'p-1', name: 'Main', mip_opt_out: true } }+ );+ const result = await runAction({+ action: getProjectAction,+ propsValue: {},+ });+ expect(seen.map((request) => request.url)).toEqual([+ 'https://api.deepgram.com/v1/projects',+ 'https://api.deepgram.com/v1/projects/p-1',+ ]);+ expect(result).toEqual({+ project_id: 'p-1',+ name: 'Main',+ mip_opt_out: true,+ });+ });++ test('asks to choose when the key has several projects', async () => {+ stubFetch(() => ({+ body: {+ projects: [+ { project_id: 'a', name: 'A' },+ { project_id: 'b', name: 'B' },+ ],+ },+ }));+ await expect(+ runAction({ action: getProjectAction, propsValue: {} })+ ).rejects.toThrow(+ 'This API key can access 2 Deepgram projects. Choose one in the Project field: A (a), B (b).'+ );+ });++ test('uses a chosen project without listing', async () => {+ const seen = stubFetch(() => ({+ body: { balances: [{ balance_id: 'b-1', amount: 199.5, units: 'usd' }] },+ }));+ const result = await runAction({+ action: getBalancesAction,+ propsValue: { project: 'p/2' },+ });+ expect(seen.map((request) => request.url)).toEqual([+ 'https://api.deepgram.com/v1/projects/p%2F2/balances',+ ]);+ expect(result).toEqual({+ balances: [+ {+ balance_id: 'b-1',+ amount: 199.5,+ units: 'usd',+ purchase_order_id: null,+ },+ ],+ });+ });+});++describe('update_project', () => {+ test('PATCHes only the trimmed name and returns the stored project', async () => {+ const seen = stubFetch((request) =>+ request.method === 'PATCH'+ ? { body: { message: 'Successfully updated project info.' } }+ : { body: { project_id: 'p-1', name: 'Renamed', mip_opt_out: false } }+ );+ const result = await runAction({+ action: updateProjectAction,+ propsValue: { project: 'p-1', name: ' Renamed ' },+ });+ expect(seen[0].method).toBe('PATCH');+ expect(seen[0].url).toBe('https://api.deepgram.com/v1/projects/p-1');+ expect(seen[0].json).toEqual({ name: 'Renamed' });+ expect(result).toEqual({+ project_id: 'p-1',+ name: 'Renamed',+ mip_opt_out: false,+ message: 'Successfully updated project info.',+ });+ });++ test('refuses an empty name', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(+ runAction({+ action: updateProjectAction,+ propsValue: { project: 'p-1', name: ' ' },+ })+ ).rejects.toThrow('Enter a new name');+ expect(seen).toHaveLength(0);+ });+});++describe('requests', () => {+ test('list_requests sends filters, masks callback credentials and reports has_more', async () => {+ const seen = stubFetch(() => ({+ body: { page: 0, limit: 1, requests: [requestRow] },+ }));+ const result = await runAction({+ action: listRequestsAction,+ propsValue: {+ project: 'p-1',+ start: '2026-10-01T00:00:00.000Z',+ end: '2026-10-11T23:59:59.000Z',+ endpoint: 'listen',+ method: 'async',+ status: 'succeeded',+ limit: 1,+ },+ });+ expect(seen[0].url).toBe(+ 'https://api.deepgram.com/v1/projects/p-1/requests?start=2026-10-01T00%3A00%3A00Z&end=2026-10-11T23%3A59%3A59Z&endpoint=listen&method=async&status=succeeded&limit=1&page=0'+ );+ expect(JSON.stringify(result)).not.toContain('secret');+ expect(result).toEqual({+ requests: [+ {+ request_id: 'req-9',+ created: '2026-10-11T14:46:00.000Z',+ completed: '2026-10-11T14:46:02.000Z',+ endpoint: 'listen',+ path: '/v1/listen?callback=https%3A%2F%2F***%40hooks.io%2Fcb&model=nova',+ api_key_id: 'key-1',+ status_code: 200,+ method: 'async',+ deployment: 'hosted:us',+ duration_seconds: 25.9,+ total_audio_seconds: 25.9,+ channels: 1,+ usd: 0.0019,+ models: 'm-1',+ features: 'callback',+ tags: 'ap',+ tier: 'nova',+ callback_status_code: 405,+ callback_attempts: 10,+ },+ ],+ page: 0,+ limit: 1,+ has_more: true,+ });+ });++ test.each([+ [{ limit: 0 }, 'Limit must be a whole number from 1 to 1000'],+ [{ limit: 1001 }, 'Limit must be a whole number from 1 to 1000'],+ [{ page: -1 }, 'Page must be a whole number from 0 up'],+ [+ { start: '2026-10-11', end: '2026-10-01' },+ 'start date must be on or before',+ ],+ [{ start: 'yesterday' }, 'is not a valid date'],+ ])('list_requests rejects %j', async (props, message) => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(+ runAction({+ action: listRequestsAction,+ propsValue: { project: 'p-1', ...props },+ })+ ).rejects.toThrow(message);+ expect(seen).toHaveLength(0);+ });++ test('get_request flattens the top-level row Deepgram returns', async () => {+ const seen = stubFetch(() => ({ body: requestRow }));+ const result = await runAction({+ action: getRequestAction,+ propsValue: { project: 'p-1', requestId: ' req-9 ' },+ });+ expect(seen[0].url).toBe(+ 'https://api.deepgram.com/v1/projects/p-1/requests/req-9'+ );+ expect(result).toEqual(+ expect.objectContaining({+ request_id: 'req-9',+ status_code: 200,+ usd: 0.0019,+ tier: 'nova',+ callback_status_code: 405,+ callback_attempts: 10,+ endpoint: 'listen',+ })+ );+ expect(JSON.stringify(result)).not.toContain('secret');+ });++ test.each([null, {}])(+ 'get_request fails clearly when Deepgram returns %j for an unknown ID',+ async (body) => {+ stubFetch(() => ({ body }));+ await expect(+ runAction({+ action: getRequestAction,+ propsValue: { project: 'p-1', requestId: 'missing-1' },+ })+ ).rejects.toThrow('Deepgram has no request with ID missing-1');+ }+ );++ test('get_request also reads the documented wrapped row', async () => {+ stubFetch(() => ({ body: { request: requestRow } }));+ const result = await runAction({+ action: getRequestAction,+ propsValue: { project: 'p-1', requestId: 'req-9' },+ });+ expect(Reflect.get(Object(result), 'usd')).toBe(0.0019);+ });+});++describe('usage and billing', () => {+ test('get_usage sends day dates and grouping and totals the rows', async () => {+ const seen = stubFetch(() => ({+ body: {+ start: '2026-10-01',+ end: '2026-10-11',+ resolution: { units: 'day', amount: 1 },+ results: [+ {+ hours: 0.1,+ total_hours: 0.1,+ agent_hours: 0,+ tokens_in: 10,+ tokens_out: 5,+ tts_characters: 100,+ requests: 3,+ grouping: {+ start: '2026-10-01',+ end: '2026-10-01',+ endpoint: 'listen',+ models: ['Nova-3'],+ },+ },+ {+ hours: 0.2,+ total_hours: 0.2,+ agent_hours: 0,+ tokens_in: 0,+ tokens_out: 0,+ tts_characters: 0,+ requests: 1,+ grouping: {+ start: '2026-10-02',+ end: '2026-10-02',+ endpoint: 'speak',+ },+ },+ ],+ },+ }));+ const result = await runAction({+ action: getUsageAction,+ propsValue: {+ project: 'p-1',+ start: '2026-10-01T10:00:00.000Z',+ end: '2026-10-11',+ groupBy: 'endpoint',+ tag: ' ap ',+ },+ });+ expect(seen[0].url).toBe(+ 'https://api.deepgram.com/v1/projects/p-1/usage/breakdown?start=2026-10-01&end=2026-10-11&grouping=endpoint&tag=ap'+ );+ expect(result).toEqual(+ expect.objectContaining({+ resolution: '1 day',+ total_hours: 0.3,+ total_requests: 4,+ total_tts_characters: 100,+ total_tokens_in: 10,+ total_tokens_out: 5,+ })+ );+ expect(Reflect.get(Object(result), 'results')[0]).toEqual(+ expect.objectContaining({+ endpoint: 'listen',+ models: 'Nova-3',+ tags: '',+ })+ );+ });++ test('get_billing_breakdown repeats grouping and rounds the total', async () => {+ const seen = stubFetch(() => ({+ body: {+ start: '2026-10-01',+ end: '2026-10-11',+ results: [+ {+ dollars: 0.1,+ grouping: { line_item: 'batch::nova-3', tags: ['a', 'b'] },+ },+ { dollars: 0.2, grouping: { line_item: 'speak::aura-2' } },+ ],+ },+ }));+ const result = await runAction({+ action: getBillingBreakdownAction,+ propsValue: { project: 'p-1', groupBy: ['line_item', 'tags'] },+ });+ expect(seen[0].url).toBe(+ 'https://api.deepgram.com/v1/projects/p-1/billing/breakdown?grouping=line_item&grouping=tags'+ );+ expect(Reflect.get(Object(result), 'total_dollars')).toBe(0.3);+ expect(Reflect.get(Object(result), 'results')[0]).toEqual({+ dollars: 0.1,+ start: null,+ end: null,+ line_item: 'batch::nova-3',+ accessor: null,+ deployment: null,+ tags: 'a, b',+ });+ });+});++describe('members, keys and projects', () => {+ test('list_project_keys never returns a secret and flattens member data', async () => {+ const seen = stubFetch(() => ({+ body: {+ api_keys: [+ {+ member: { member_id: 'm-1', email: '[email protected]' },+ api_key: {+ api_key_id: 'k-1',+ comment: 'CI',+ scopes: ['member'],+ created: '2026-01-01T00:00:00Z',+ },+ },+ ],+ },+ }));+ const result = await runAction({+ action: listProjectKeysAction,+ propsValue: { project: 'p-1', status: 'active' },+ });+ expect(seen[0].url).toBe(+ 'https://api.deepgram.com/v1/projects/p-1/keys?status=active'+ );+ expect(result).toEqual({+ keys: [+ {+ api_key_id: 'k-1',+ comment: 'CI',+ scopes: 'member',+ created: '2026-01-01T00:00:00Z',+ expiration_date: null,+ member_id: 'm-1',+ member_email: '[email protected]',+ },+ ],+ });+ });++ test('list_project_members joins scopes', async () => {+ stubFetch(() => ({+ body: {+ members: [+ {+ member_id: 'm-1',+ email: '[email protected]',+ first_name: 'A',+ last_name: 'B',+ scopes: ['owner', 'admin'],+ },+ ],+ },+ }));+ await expect(+ runAction({+ action: listProjectMembersAction,+ propsValue: { project: 'p-1' },+ })+ ).resolves.toEqual({+ members: [+ {+ member_id: 'm-1',+ email: '[email protected]',+ first_name: 'A',+ last_name: 'B',+ scopes: 'owner, admin',+ },+ ],+ });+ });++ test('list_projects keeps the vendor fields', async () => {+ stubFetch(() => ({ body: ONE_PROJECT }));+ await expect(+ runAction({ action: listProjectsAction, propsValue: {} })+ ).resolves.toEqual(ONE_PROJECT);+ });+});diff --git a/packages/pieces/community/deepgram/test/metadata.test.ts b/packages/pieces/community/deepgram/test/metadata.test.tsnew file mode 100644index 00000000000..5ba225732a0--- /dev/null+++ b/packages/pieces/community/deepgram/test/metadata.test.ts@@ -0,0 +1,100 @@+import { describe, expect, test } from 'vitest';+import { deepgramPiece } from '../src/index';++const actions = Object.values(deepgramPiece.actions());+const handWritten = actions.filter(+ (action) => action.name !== 'custom_api_call'+);++describe('piece metadata', () => {+ test('every hand-written action declares audience, aiMetadata and classification', () => {+ for (const action of handWritten) {+ expect(['human', 'ai', 'both'], action.name).toContain(action.audience);+ expect(+ action.aiMetadata?.description?.length ?? 0,+ action.name+ ).toBeGreaterThan(40);+ expect(typeof action.aiMetadata?.idempotent, action.name).toBe('boolean');+ expect(['READ', 'SEARCH', 'WRITE', 'DESTRUCTIVE'], action.name).toContain(+ action.classification+ );+ }+ });++ test('every action except the polymorphic Create Summary has an output schema', () => {+ const missing = handWritten+ .filter((action) => !action.outputSchema)+ .map((action) => action.name);+ expect(missing).toEqual(['create_summary']);+ });++ test('replaced actions are human-only and their agent twins exist', () => {+ const byName = new Map(handWritten.map((action) => [action.name, action]));+ expect(byName.get('create_summary')?.audience).toBe('human');+ expect(byName.get('create_transcription_callback')?.audience).toBe('human');+ expect(byName.get('text_to_speech')?.audience).toBe('human');+ for (const name of [+ 'transcribe_audio',+ 'list_models',+ 'list_requests',+ 'get_request',+ 'get_usage',+ 'get_balances',+ 'get_billing_breakdown',+ 'list_project_members',+ ]) {+ expect(byName.get(name)?.audience, name).toBe('human');+ }+ for (const name of [+ 'list_projects',+ 'analyze_text',+ 'get_project',+ 'update_project',+ 'list_project_keys',+ ]) {+ expect(byName.get(name)?.audience, name).toBe('both');+ }+ expect(byName.get('deepgram_generate_speech')?.audience).toBe('ai');+ expect(byName.get('create_transcription_callback')?.classification).toBe(+ 'WRITE'+ );+ });++ test('audience counts match the coverage map', () => {+ const count = (audience: string) =>+ handWritten.filter((action) => action.audience === audience).length;+ expect([count('both'), count('human'), count('ai')]).toEqual([5, 11, 16]);+ });++ test('display names are unique across audiences', () => {+ const names = handWritten.map((action) => action.displayName);+ expect(new Set(names).size).toBe(names.length);+ });++ test('ai and both actions never point agents at human-only actions', () => {+ const humanNames = handWritten+ .filter((action) => action.audience === 'human')+ .map((action) => action.displayName);+ for (const action of handWritten.filter(+ (item) => item.audience !== 'human'+ )) {+ for (const name of humanNames) {+ const mention = new RegExp(`\\b${name}\\b(?! \\(Agent\\)| by ID)`);+ expect(action.aiMetadata?.description ?? '', action.name).not.toMatch(+ mention+ );+ }+ }+ });++ test('schema child paths are relative', () => {+ const paths = handWritten.flatMap((action) =>+ (action.outputSchema?.fields ?? []).flatMap((field) =>+ [...(field.listItems ?? []), ...(field.children ?? [])].map(+ (child) => child.value ?? child.key+ )+ )+ );+ expect(paths.filter((path) => path.includes('.'))).toEqual([]);+ });+});diff --git a/packages/pieces/community/deepgram/test/models.test.ts b/packages/pieces/community/deepgram/test/models.test.tsnew file mode 100644index 00000000000..6d69099b672--- /dev/null+++ b/packages/pieces/community/deepgram/test/models.test.ts@@ -0,0 +1,189 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { deepgramModels } from '../src/common/models';+import { listModelsAction } from '../src/actions/list-models';+import { runAction, stubFetch } from './helpers';++afterEach(() => {+ vi.unstubAllGlobals();+});++const stt = [+ {+ name: 'general',+ canonical_name: 'nova-2-general',+ architecture: 'nova-2',+ languages: ['en'],+ version: '2024-01-09.1',+ batch: true,+ streaming: false,+ },+ {+ name: 'general',+ canonical_name: 'nova-2-general',+ architecture: 'nova-2',+ languages: ['es'],+ version: '2024-02-01.1',+ batch: false,+ streaming: true,+ },+ {+ name: 'general',+ canonical_name: 'nova-3-general',+ architecture: 'nova-3',+ languages: ['en', 'multi'],+ version: '2025-07-31.0',+ batch: true,+ streaming: true,+ },+ {+ name: 'phoneme',+ canonical_name: 'phoneme',+ architecture: 'base',+ languages: ['en'],+ version: '1',+ batch: true,+ streaming: false,+ },+ {+ name: 'general',+ canonical_name: 'general-dQw4w9WgXcQ',+ architecture: 'base',+ languages: ['en'],+ version: '1',+ batch: true,+ streaming: false,+ },+ {+ name: 'streamonly',+ canonical_name: 'flux-general-en',+ architecture: 'flux',+ languages: ['en'],+ version: '1',+ batch: false,+ streaming: true,+ },+ {+ name: 'general',+ canonical_name: 'base-general',+ architecture: 'base',+ languages: ['en'],+ version: '1',+ batch: true,+ streaming: true,+ },+];++const tts = [+ {+ name: 'asteria',+ canonical_name: 'aura-asteria-en',+ architecture: 'aura',+ languages: ['en', 'en-US'],+ version: '1',+ metadata: { accent: 'American', display_name: null, tags: ['feminine'] },+ },+ {+ name: 'thalia',+ canonical_name: 'aura-2-thalia-en',+ architecture: 'aura-2',+ languages: ['en', 'en-US'],+ version: '1',+ metadata: {+ accent: 'American',+ display_name: 'Thalia',+ tags: ['feminine', 'clear'],+ sample: 'https://s.test/t.wav',+ age: 'Adult',+ },+ },+ {+ name: 'celeste',+ canonical_name: 'aura-2-celeste-es',+ architecture: 'aura-2',+ languages: ['es', 'es-CO'],+ version: '1',+ metadata: {+ accent: 'Colombian',+ display_name: 'Celeste',+ tags: ['feminine'],+ },+ },+];++describe('model dropdowns', () => {+ test('dedupe speech models, drop junk and streaming-only entries, nova-3 first', () => {+ const options = deepgramModels.toSttOptions({ models: stt });+ expect(options).toEqual([+ { label: 'nova-3-general (nova-3)', value: 'nova-3-general' },+ { label: 'nova-2-general (nova-2)', value: 'nova-2-general' },+ { label: 'base-general (base)', value: 'base-general' },+ ]);+ });++ test('labels voices with name, family, language and gender, Aura-2 first', () => {+ const options = deepgramModels.toTtsOptions({ models: tts });+ expect(options.map((option) => option.value)).toEqual([+ 'aura-2-celeste-es',+ 'aura-2-thalia-en',+ 'aura-asteria-en',+ ]);+ expect(options[1].label).toBe(+ 'Thalia - Aura-2, en (American), feminine [aura-2-thalia-en]'+ );+ expect(options[2].label).toBe(+ 'Asteria - Aura, en (American), feminine [aura-asteria-en]'+ );+ });+});++describe('list_models', () => {+ test('returns one flat row per model with merged languages and a language filter', async () => {+ const seen = stubFetch(() => ({ body: { stt, tts } }));+ const result = await runAction({+ action: listModelsAction,+ propsValue: { type: 'all', language: 'es', includeOutdated: true },+ });+ expect(seen[0].url).toBe(+ 'https://api.deepgram.com/v1/models?include_outdated=true'+ );+ expect(result).toEqual({+ count: 2,+ models: [+ expect.objectContaining({+ canonical_name: 'nova-2-general',+ type: 'stt',+ languages: 'en, es',+ batch: true,+ streaming: true,+ version: '2024-02-01.1',+ }),+ expect.objectContaining({+ canonical_name: 'aura-2-celeste-es',+ type: 'tts',+ name: 'Celeste',+ gender: 'feminine',+ batch: null,+ }),+ ],+ });+ });++ test('uses the project catalog when a project is chosen', async () => {+ const seen = stubFetch(() => ({ body: { stt: [], tts } }));+ const result = await runAction({+ action: listModelsAction,+ propsValue: { type: 'tts', project: 'p 1' },+ });+ expect(seen[0].url).toBe(+ 'https://api.deepgram.com/v1/projects/p%201/models'+ );+ expect(Reflect.get(Object(result), 'count')).toBe(3);+ });++ test('rejects an unknown type', async () => {+ stubFetch(() => ({ body: {} }));+ await expect(+ runAction({ action: listModelsAction, propsValue: { type: 'video' } })+ ).rejects.toThrow('Type must be all, stt or tts.');+ });+});diff --git a/packages/pieces/community/deepgram/test/read.test.ts b/packages/pieces/community/deepgram/test/read.test.tsnew file mode 100644index 00000000000..171893bb938--- /dev/null+++ b/packages/pieces/community/deepgram/test/read.test.ts@@ -0,0 +1,144 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { analyzeTextAction } from '../src/actions/analyze-text';+import { runAction, stubFetch } from './helpers';++afterEach(() => {+ vi.unstubAllGlobals();+});++const nestedShape = {+ metadata: {+ metadata: {+ request_id: 'read-1',+ language: 'en',+ summary_info: { input_tokens: 350, output_tokens: 75 },+ topics_info: { input_tokens: 350, output_tokens: 20 },+ },+ },+ results: {+ summary: { results: { summary: { text: 'Nested summary.' } } },+ topics: {+ results: {+ topics: {+ segments: [+ {+ text: 'Seg',+ topics: [{ topic: 'Space', confidence_score: 0.9 }],+ },+ ],+ },+ },+ },+ intents: {+ results: {+ intents: {+ segments: [+ {+ text: 'Seg',+ intents: [{ intent: 'Subscribe', confidence_score: 0.1 }],+ },+ ],+ },+ },+ },+ sentiments: {+ segments: [{ text: 'Seg', sentiment: 'positive', sentiment_score: 0.58 }],+ average: { sentiment: 'positive', sentiment_score: 0.5 },+ },+ },+};++const flatShape = {+ metadata: {+ request_id: 'read-2',+ language: 'en',+ summary_info: { input_tokens: 10, output_tokens: 5 },+ },+ results: {+ summary: { text: 'Flat summary.' },+ topics: {+ segments: [+ { text: 'Seg', topics: [{ topic: 'Space', confidence_score: 0.9 }] },+ ],+ },+ },+};++describe('analyze_text', () => {+ test('sends text with the chosen features and repeated custom topics', async () => {+ const seen = stubFetch(() => ({ body: nestedShape }));+ await runAction({+ action: analyzeTextAction,+ propsValue: {+ text: 'Some English text.',+ summarize: true,+ sentiment: true,+ customTopics: ['Billing', 'Refunds'],+ customTopicMode: 'strict',+ },+ });+ expect(seen[0].url).toBe(+ 'https://api.deepgram.com/v1/read?language=en&summarize=true&topics=true&sentiment=true&custom_topic=Billing&custom_topic=Refunds&custom_topic_mode=strict'+ );+ expect(seen[0].json).toEqual({ text: 'Some English text.' });+ });++ test('flattens the nested response shape', async () => {+ stubFetch(() => ({ body: nestedShape }));+ const result = await runAction({+ action: analyzeTextAction,+ propsValue: {+ textUrl: 'https://static.deepgram.com/examples/aura.txt',+ summarize: true,+ topics: true,+ },+ });+ expect(result).toEqual({+ request_id: 'read-1',+ language: 'en',+ summary: 'Nested summary.',+ topics: [{ topic: 'Space', confidence: 0.9, text: 'Seg' }],+ intents: [{ intent: 'Subscribe', confidence: 0.1, text: 'Seg' }],+ sentiment: 'positive',+ sentiment_score: 0.5,+ sentiment_segments: [+ { text: 'Seg', sentiment: 'positive', sentiment_score: 0.58 },+ ],+ input_tokens: 350,+ output_tokens: 95,+ });+ });++ test('flattens the flat response shape', async () => {+ stubFetch(() => ({ body: flatShape }));+ const result = await runAction({+ action: analyzeTextAction,+ propsValue: { text: 'x', summarize: true },+ });+ expect(result).toEqual(+ expect.objectContaining({+ request_id: 'read-2',+ summary: 'Flat summary.',+ topics: [{ topic: 'Space', confidence: 0.9, text: 'Seg' }],+ intents: [],+ sentiment: null,+ })+ );+ });++ test.each([+ [{ summarize: true }, 'Provide the text to analyze'],+ [{ text: 'x', textUrl: 'https://a.io/t.txt', summarize: true }, 'not both'],+ [{ text: 'x', summarize: false }, 'Turn on at least one'],+ [+ { textUrl: 'file:///etc/passwd', summarize: true },+ 'must start with https://',+ ],+ ])('rejects %j before any request', async (props, message) => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(+ runAction({ action: analyzeTextAction, propsValue: props })+ ).rejects.toThrow(message);+ expect(seen).toHaveLength(0);+ });+});diff --git a/packages/pieces/community/deepgram/test/speech.test.ts b/packages/pieces/community/deepgram/test/speech.test.tsnew file mode 100644index 00000000000..171b4b24f39--- /dev/null+++ b/packages/pieces/community/deepgram/test/speech.test.ts@@ -0,0 +1,174 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { textToSpeechAction } from '../src/actions/text-to-speech';+import { generateSpeechAction } from '../src/actions/ai/generate-speech';+import { deepgramSpeech } from '../src/common/speech';+import { runAction, stubFetch } from './helpers';++afterEach(() => {+ vi.unstubAllGlobals();+});++const audio = new Uint8Array([1, 2, 3, 4]);++function audioReply(contentType: string) {+ return {+ binary: audio,+ headers: {+ 'content-type': contentType,+ 'dg-char-count': '11',+ 'dg-request-id': 'tts-1',+ },+ };+}++describe('text_to_speech', () => {+ test('keeps aura-asteria-en and mp3 as defaults, accepts any audio type and returns the file', async () => {+ const seen = stubFetch(() => audioReply('audio/mpeg'));+ const result = await runAction({+ action: textToSpeechAction,+ propsValue: { text: 'Hello world' },+ });+ expect(seen[0].url).toBe(+ 'https://api.deepgram.com/v1/speak?model=aura-asteria-en&encoding=mp3'+ );+ expect(seen[0].json).toEqual({ text: 'Hello world' });+ expect(seen[0].headers.get('accept')).toBe('*/*');+ expect(result).toEqual({+ file: 'https://files.test/audio.mp3',+ file_name: 'audio.mp3',+ content_type: 'audio/mpeg',+ size_bytes: 4,+ characters: 11,+ request_id: 'tts-1',+ model: 'aura-asteria-en',+ encoding: 'mp3',+ });+ });++ test('sends container, sample rate, bit rate and speed', async () => {+ const seen = stubFetch(() => audioReply('audio/l16;rate=8000'));+ const result = await runAction({+ action: textToSpeechAction,+ propsValue: {+ text: 'Hi',+ model: 'aura-2-thalia-en',+ encoding: 'linear16',+ container: 'none',+ sampleRate: 8000,+ speed: 1.1,+ },+ });+ expect(seen[0].url).toBe(+ 'https://api.deepgram.com/v1/speak?model=aura-2-thalia-en&encoding=linear16&container=none&sample_rate=8000&speed=1.1'+ );+ expect(Reflect.get(Object(result), 'file_name')).toBe('audio.raw');+ });++ test('accepts exactly 2,000 characters and rejects 2,001 before calling Deepgram', async () => {+ const seen = stubFetch(() => audioReply('audio/mpeg'));+ await runAction({+ action: textToSpeechAction,+ propsValue: { text: 'a'.repeat(2000) },+ });+ await expect(+ runAction({+ action: textToSpeechAction,+ propsValue: { text: 'a'.repeat(2001) },+ })+ ).rejects.toThrow('at most 2000 characters');+ await expect(+ runAction({ action: textToSpeechAction, propsValue: { text: ' ' } })+ ).rejects.toThrow('Enter the text');+ await expect(+ runAction({+ action: textToSpeechAction,+ propsValue: { text: 'hi', speed: 3 },+ })+ ).rejects.toThrow('0.5 to 1.5');+ expect(seen).toHaveLength(1);+ });++ test.each([+ ['mp3', undefined, 'mp3'],+ ['linear16', undefined, 'wav'],+ ['mulaw', 'wav', 'wav'],+ ['alaw', 'none', 'raw'],+ ['opus', undefined, 'ogg'],+ ['flac', undefined, 'flac'],+ ['aac', undefined, 'aac'],+ ])(+ '%s with container %s is saved as .%s',+ (encoding, container, extension) => {+ expect(deepgramSpeech.fileExtension({ encoding, container })).toBe(+ extension+ );+ }+ );+});++describe('deepgram_generate_speech', () => {+ test('defaults to aura-2-thalia-en', async () => {+ const seen = stubFetch(() => audioReply('audio/mpeg'));+ await runAction({+ action: generateSpeechAction,+ propsValue: { text: 'Hello' },+ });+ expect(seen[0].url).toBe(+ 'https://api.deepgram.com/v1/speak?model=aura-2-thalia-en&encoding=mp3'+ );+ });++ test('normalizes and validates the voice ID and format', async () => {+ const seen = stubFetch(() => audioReply('audio/ogg;codecs=opus'));+ await runAction({+ action: generateSpeechAction,+ propsValue: {+ text: 'Hola',+ voice: ' AURA-2-celeste-es ',+ encoding: 'opus',+ },+ });+ expect(seen[0].url).toBe(+ 'https://api.deepgram.com/v1/speak?model=aura-2-celeste-es&encoding=opus'+ );+ await expect(+ runAction({+ action: generateSpeechAction,+ propsValue: { text: 'x', voice: 'thalia' },+ })+ ).rejects.toThrow('is not a Deepgram voice ID');+ await expect(+ runAction({+ action: generateSpeechAction,+ propsValue: { text: 'x', encoding: 'wav' },+ })+ ).rejects.toThrow('Unknown audio format "wav"');+ expect(seen).toHaveLength(1);+ });+});++describe('speech errors', () => {+ test('decodes the binary error body so code and request id survive', async () => {+ stubFetch(() => ({+ status: 400,+ text: JSON.stringify({+ err_code: 'INVALID_QUERY_PARAMETER',+ err_msg: 'Unsupported encoding.',+ request_id: 'req-42',+ }),+ }));+ const error = await runAction({+ action: textToSpeechAction,+ propsValue: { text: 'Hello world' },+ }).catch((e: unknown) => e);+ expect(error).toMatchObject({+ name: 'DeepgramApiError',+ status: 400,+ code: 'INVALID_QUERY_PARAMETER',+ requestId: 'req-42',+ });+ const message = String(Reflect.get(Object(error), 'message'));+ expect(message).toContain('Unsupported encoding.');+ expect(message).toContain('Deepgram request ID: req-42.');+ });+});diff --git a/packages/pieces/community/deepgram/test/transcribe.test.ts b/packages/pieces/community/deepgram/test/transcribe.test.tsnew file mode 100644index 00000000000..dca6fe1c9a4--- /dev/null+++ b/packages/pieces/community/deepgram/test/transcribe.test.ts@@ -0,0 +1,387 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { transcribeAudioAction } from '../src/actions/transcribe-audio';+import { createSummaryAction } from '../src/actions/create-summary';+import { createTranscriptionCallbackAction } from '../src/actions/create-transcription';+import { deepgramTranscript } from '../src/common/transcript';+import { runAction, stubFetch } from './helpers';++afterEach(() => {+ vi.unstubAllGlobals();+});++const AUDIO_URL =+ 'https://static.deepgram.com/examples/nasa-spacewalk-interview.wav';++function listenReply({+ channels = 1,+ summary,+}: { channels?: number; summary?: unknown } = {}) {+ return {+ metadata: {+ request_id: 'req-1',+ duration: 25.9,+ channels,+ models: ['m-1'],+ model_info: {+ 'm-1': {+ name: 'general-nova-3',+ version: '2025-07-31.0',+ arch: 'nova-3',+ },+ },+ warnings: [+ { parameter: 'keyterm', type: 'unsupported', message: 'ignored' },+ ],+ },+ results: {+ channels: Array.from({ length: channels }, (_, index) => ({+ detected_language: 'en',+ language_confidence: 0.99,+ alternatives: [+ {+ transcript: `hello from channel ${index}`,+ confidence: 0.9,+ paragraphs: {+ transcript: `\nSpeaker 0: hello from channel ${index}`,+ },+ entities: [{ label: 'NAME', value: ' Jane', confidence: 0.98 }],+ words: [+ {+ word: 'hello',+ punctuated_word: 'Hello',+ start: 0,+ end: 0.5,+ confidence: 0.9,+ speaker: 0,+ },+ {+ word: 'there',+ punctuated_word: 'there.',+ start: 0.5,+ end: 1,+ confidence: 0.9,+ speaker: 1,+ },+ ],+ },+ ],+ })),+ utterances: [+ {+ speaker: 0,+ channel: 0,+ start: 0,+ end: 0.5,+ confidence: 0.9,+ transcript: 'Hello',+ id: 'u1',+ },+ ],+ ...(summary === undefined ? {} : { summary }),+ topics: {+ segments: [+ {+ text: 'Hello there.',+ start_word: 0,+ end_word: 1,+ topics: [{ topic: 'Greeting', confidence_score: 0.8 }],+ },+ ],+ },+ intents: {+ segments: [+ {+ text: 'Hello there.',+ intents: [{ intent: 'Say hello', confidence_score: 0.7 }],+ },+ ],+ },+ sentiments: {+ segments: [+ { text: 'Hello there.', sentiment: 'positive', sentiment_score: 0.5 },+ ],+ average: { sentiment: 'positive', sentiment_score: 0.4 },+ },+ },+ };+}++describe('transcribe_audio', () => {+ test('sends a JSON url body with nova-3 and smart format by default', async () => {+ const seen = stubFetch(() => ({ body: listenReply() }));+ await runAction({+ action: transcribeAudioAction,+ propsValue: { audioUrl: AUDIO_URL },+ });+ expect(seen[0].method).toBe('POST');+ expect(seen[0].url).toBe(+ 'https://api.deepgram.com/v1/listen?model=nova-3&smart_format=true'+ );+ expect(seen[0].json).toEqual({ url: AUDIO_URL });+ expect(seen[0].headers.get('content-type')).toBe('application/json');+ });++ test('builds every feature parameter, repeating keyterm, redact and tag', async () => {+ const seen = stubFetch(() => ({ body: listenReply() }));+ await runAction({+ action: transcribeAudioAction,+ propsValue: {+ audioUrl: AUDIO_URL,+ model: 'nova-3-general',+ language: 'en-US',+ smartFormat: false,+ diarize: true,+ paragraphs: true,+ utterances: true,+ multichannel: true,+ keyterms: ['Activepieces', ' Deepgram '],+ redact: ['pci', 'pii'],+ detectEntities: true,+ summarize: true,+ topics: true,+ intents: true,+ sentiment: true,+ tags: ['flow-1'],+ },+ });+ expect(seen[0].url).toBe(+ 'https://api.deepgram.com/v1/listen?model=nova-3-general&language=en-US&diarize_model=latest¶graphs=true&utterances=true&multichannel=true&detect_entities=true&summarize=v2&topics=true&intents=true&sentiment=true&keyterm=Activepieces&keyterm=Deepgram&redact=pci&redact=pii&tag=flow-1'+ );+ });++ test('streams an uploaded file with its MIME type, or octet-stream when unknown', async () => {+ const seen = stubFetch(() => ({ body: listenReply() }));+ const data = Buffer.from('RIFF....WAVEfmt fake audio');+ await runAction({+ action: transcribeAudioAction,+ propsValue: {+ audioFile: { filename: 'call.wav', extension: 'wav', data },+ },+ });+ await runAction({+ action: transcribeAudioAction,+ propsValue: { audioFile: { filename: 'blob', data } },+ });+ expect(seen[0].streamed).toBe(true);+ expect(seen[0].bytes?.equals(data)).toBe(true);+ expect(seen[0].headers.get('content-type')).toBe('audio/wave');+ expect(seen[1].headers.get('content-type')).toBe(+ 'application/octet-stream'+ );+ });++ test('detect language drops the language parameter', async () => {+ const seen = stubFetch(() => ({ body: listenReply() }));+ await runAction({+ action: transcribeAudioAction,+ propsValue: {+ audioUrl: AUDIO_URL,+ language: 'de',+ detectLanguage: true,+ summarize: true,+ },+ });+ expect(seen[0].url).toContain('detect_language=true');+ expect(seen[0].url).not.toContain('language=de');+ });++ test.each([+ [{}, 'Provide an audio URL or an audio file'],+ [+ {+ audioUrl: AUDIO_URL,+ audioFile: { filename: 'a.wav', data: Buffer.from('x') },+ },+ 'not both',+ ],+ [{ audioUrl: 'ftp://x.io/a.wav' }, 'must start with https:// or http://'],+ [+ { audioUrl: AUDIO_URL, language: 'es', summarize: true },+ 'only work on English audio',+ ],+ [+ { audioUrl: AUDIO_URL, model: 'nova-2-general', keyterms: ['x'] },+ 'only work with nova-3',+ ],+ [{ audioUrl: AUDIO_URL, redact: ['ssn'] }, 'Unknown redaction type: ssn'],+ [{ audioFile: { filename: 'a.wav', data: Buffer.alloc(0) } }, 'empty'],+ ])('rejects %j before any request', async (props, message) => {+ const seen = stubFetch(() => ({ body: listenReply() }));+ await expect(+ runAction({ action: transcribeAudioAction, propsValue: props })+ ).rejects.toThrow(message);+ expect(seen).toHaveLength(0);+ });++ test('flattens transcript, speakers, channels, intelligence and warnings', async () => {+ stubFetch(() => ({+ body: listenReply({+ channels: 2,+ summary: { result: 'success', short: 'A greeting.' },+ }),+ }));+ const result = await runAction({+ action: transcribeAudioAction,+ propsValue: { audioUrl: AUDIO_URL, includeWords: true },+ });+ expect(result).toEqual(+ expect.objectContaining({+ request_id: 'req-1',+ transcript: 'hello from channel 0\n\nhello from channel 1',+ duration_seconds: 25.9,+ detected_language: 'en',+ model_name: 'general-nova-3',+ channel_count: 2,+ paragraphs_text:+ 'Speaker 0: hello from channel 0\n\nSpeaker 0: hello from channel 1',+ speaker_count: 2,+ summary: 'A greeting.',+ topics: [{ topic: 'Greeting', confidence: 0.8, text: 'Hello there.' }],+ intents: [+ { intent: 'Say hello', confidence: 0.7, text: 'Hello there.' },+ ],+ sentiment: 'positive',+ sentiment_score: 0.4,+ warnings: ['keyterm: ignored'],+ })+ );+ const flat = Reflect.get(Object(result), 'speaker_transcript');+ expect(flat).toBe(+ 'Speaker 0: Hello\nSpeaker 1: there.\nSpeaker 0: Hello\nSpeaker 1: there.'+ );+ expect(Reflect.get(Object(result), 'channels')).toHaveLength(2);+ expect(Reflect.get(Object(result), 'entities')).toEqual([+ { label: 'NAME', value: 'Jane', confidence: 0.98, channel: 0 },+ { label: 'NAME', value: 'Jane', confidence: 0.98, channel: 1 },+ ]);+ expect(Reflect.get(Object(result), 'words')).toHaveLength(4);+ });++ test('leaves words out unless asked and turns a failed summary into a warning', () => {+ const flat = deepgramTranscript.flattenListen({+ body: listenReply({+ summary: {+ result: 'failure',+ short:+ 'The summarization feature is currently only available in English.',+ },+ }),+ includeWords: false,+ });+ expect(flat.words).toEqual([]);+ expect(flat.summary).toBeNull();+ expect(flat.warnings).toContain(+ 'Summary not available: The summarization feature is currently only available in English.'+ );+ });+});++describe('create_summary', () => {+ const audioFile = {+ filename: 'a.mp3',+ extension: 'mp3',+ data: Buffer.from('ID3 fake'),+ };++ test('keeps the nova default and returns the summary object on success', async () => {+ const seen = stubFetch(() => ({+ body: listenReply({ summary: { result: 'success', short: 'Short.' } }),+ }));+ const result = await runAction({+ action: createSummaryAction,+ propsValue: { audioFile, fallbackToTranscript: true },+ });+ expect(seen[0].url).toBe(+ 'https://api.deepgram.com/v1/listen?model=nova&summarize=v2&language=en'+ );+ expect(seen[0].headers.get('content-type')).toBe('audio/mpeg');+ expect(seen[0].streamed).toBe(true);+ expect(result).toEqual({ result: 'success', short: 'Short.' });+ });++ test('a failed summary falls back to the transcript', async () => {+ stubFetch(() => ({+ body: listenReply({ summary: { result: 'failure', short: 'nope' } }),+ }));+ await expect(+ runAction({+ action: createSummaryAction,+ propsValue: { audioFile, fallbackToTranscript: true },+ })+ ).resolves.toBe('hello from channel 0');+ });++ test('a failed summary without fallback throws with the reason', async () => {+ stubFetch(() => ({+ body: listenReply({ summary: { result: 'failure', short: 'nope' } }),+ }));+ await expect(+ runAction({+ action: createSummaryAction,+ propsValue: { audioFile, fallbackToTranscript: false },+ })+ ).rejects.toThrow('Deepgram could not summarize this audio (nope)');+ });++ test('refuses a non-English language before uploading', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(+ runAction({+ action: createSummaryAction,+ propsValue: { audioFile, language: 'fr' },+ })+ ).rejects.toThrow('only available for English');+ expect(seen).toHaveLength(0);+ });+});++describe('create_transcription_callback', () => {+ test('sends the callback and masks its credentials in the output', async () => {+ const seen = stubFetch(() => ({ body: { request_id: 'cb-1' } }));+ const result = await runAction({+ action: createTranscriptionCallbackAction,+ propsValue: {+ audioUrl: AUDIO_URL,+ callbackUrl: 'https://u:[email protected]/cb',+ callbackMethod: 'PUT',+ },+ });+ expect(seen[0].url).toBe(+ 'https://api.deepgram.com/v1/listen?model=nova&callback=https%3A%2F%2Fu%3Asecret%40hooks.example.com%2Fcb&callback_method=put&language=en'+ );+ expect(result).toEqual({+ requestId: 'cb-1',+ callbackUrl: 'https://***@hooks.example.com/cb',+ status: 'submitted',+ });+ expect(JSON.stringify(result)).not.toContain('secret');+ });++ test.each([+ ['https://hooks.example.com:9000/cb', 'ports 80, 443, 8080 or 8443'],+ ['ftp://hooks.example.com/cb', 'must start with https:// or http://'],+ ['not a url', 'full URL'],+ ])('rejects callback %s', async (callbackUrl, message) => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(+ runAction({+ action: createTranscriptionCallbackAction,+ propsValue: { audioUrl: AUDIO_URL, callbackUrl },+ })+ ).rejects.toThrow(message);+ expect(seen).toHaveLength(0);+ });++ test('accepts port 8443', async () => {+ stubFetch(() => ({ body: { request_id: 'cb-2' } }));+ await expect(+ runAction({+ action: createTranscriptionCallbackAction,+ propsValue: {+ audioUrl: AUDIO_URL,+ callbackUrl: 'https://hooks.example.com:8443/cb',+ },+ })+ ).resolves.toEqual(expect.objectContaining({ requestId: 'cb-2' }));+ });+});diff --git a/packages/pieces/community/deepgram/vitest.config.ts b/packages/pieces/community/deepgram/vitest.config.tsnew file mode 100644index 00000000000..79c97261904--- /dev/null+++ b/packages/pieces/community/deepgram/vitest.config.ts@@ -0,0 +1,19 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ root: __dirname,+ test: {+ globals: true,+ environment: 'node',+ include: ['test/**/*.test.ts'],+ },+ resolve: {+ alias: {+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})