UNPKG

phonic

Version:

[![fern shield](https://img.shields.io/badge/%F0%9F%8C%BF-Built%20with%20Fern-brightgreen)](https://buildwithfern.com?utm_source=github&utm_medium=github&utm_campaign=readme&utm_source=https%3A%2F%2Fgithub.com%2FPhonic-Co%2Fphonic-node) [![npm shield](htt

687 lines (668 loc) 19.6 kB
import WebSocket from 'ws'; type PhonicConfig = { baseUrl?: string; headers?: Record<string, string>; __downstreamWebSocketUrl?: string; }; type FetchOptions = { method: "GET"; headers?: Record<string, string>; } | { method: "POST"; headers?: Record<string, string>; body: string; } | { method: "PATCH"; headers?: Record<string, string>; body: string; } | { method: "PUT"; headers?: Record<string, string>; body: string; } | { method: "DELETE"; headers?: Record<string, string>; }; type DataOrError<T> = Promise<{ data: T; error: null; } | { data: null; error: { message: string; code?: string; param_errors?: Record<string, string>; }; }>; type ISODate = `${string}-${string}-${string}`; type ISODateTime = `${string}Z`; type TaskStatus = "pending" | "completed" | "failed"; type TaskResult = { name: string; description: string; status: TaskStatus; commentary: string | null; }; type TaskResults = { results: Array<TaskResult>; }; type ConversationItem = { role: "user"; item_idx: number; text: string; duration_ms: number; started_at: string; } | { role: "assistant"; item_idx: number; text: string; voice_id: string; system_prompt: string; audio_speed: number; duration_ms: number; started_at: string; }; type Conversation = { id: string; external_id: string | null; workspace: string; agent: { id: string; name: string; } | null; model: string; welcome_message: string | null; input_format: "pcm_44100" | "mulaw_8000"; output_format: "pcm_44100" | "mulaw_8000"; live_transcript: string; post_call_transcript: string | null; audio_url: string | null; duration_ms: number; task_results: TaskResults; started_at: ISODateTime; ended_at: ISODateTime | null; items: Array<ConversationItem>; }; type ConversationEndedWebhookPayload = { event_type: "conversation.ended"; created_at: ISODateTime; data: { conversation: Conversation; call_info: { from_phone_number: string; to_phone_number: string; } | null; }; }; type ConversationAnalysisWebhookPayload = { event_type: "conversation.analysis"; created_at: ISODateTime; data: { conversation: { latencies_ms: number[]; interruptions_count: number; }; call_info: { from_phone_number: string; to_phone_number: string; } | null; }; }; type PhonicSTSTool = "keypad_input" | "natural_conversation_ending" | (string & {}); interface PhonicSTSConfigBase { input_format: "pcm_44100" | "mulaw_8000"; output_format?: "pcm_44100" | "mulaw_8000"; voice_id?: string; audio_speed?: number; welcome_message?: string; system_prompt?: string; template_variables?: Record<string, string>; enable_silent_audio_fallback?: boolean; experimental_params?: Record<string, unknown>; tools?: Array<PhonicSTSTool>; vad_prebuffer_duration_ms?: number; vad_min_speech_duration_ms?: number; vad_min_silence_duration_ms?: number; vad_threshold?: number; } interface PhonicSTSConfigWithAgent extends PhonicSTSConfigBase { agent: string; } interface PhonicSTSConfigWithProject extends PhonicSTSConfigBase { project: string; } type PhonicSTSConfig = PhonicSTSConfigWithAgent | PhonicSTSConfigWithProject; type PhonicSTSWebSocketResponseMessage = { type: "conversation_created"; conversation_id: string; } | { type: "ready_to_start_conversation"; } | { type: "input_text"; text: string; } | { type: "audio_chunk"; text: string; audio: string; } | { type: "audio_finished"; } | { type: "is_user_speaking"; is_user_speaking: boolean; } | { type: "user_started_speaking"; } | { type: "user_finished_speaking"; } | { type: "interrupted_response"; text: string; } | { type: "assistant_chose_not_to_respond"; } | { type: "assistant_ended_conversation"; } | { type: "dtmf"; digits: string; } | { type: "tool_call_output_processed"; tool_call_id: string; tool: { id: string; name: string; }; endpoint_url: string | null; endpoint_timeout_ms: number | null; endpoint_called_at: string | null; request_body: { call_info: { from_phone_number: string; to_phone_number: string; } | null; [key: string]: unknown; } | null; parameters: Record<string, unknown> | null; output: unknown | null; response_body: unknown | null; response_status_code: number | null; timed_out: boolean | null; error_message: string | null; } | { type: "tool_call"; tool_call_id: string; tool_name: string; parameters: Record<string, unknown>; } | { type: "error"; error: { message: string; code?: string; }; param_errors?: { input_format?: string; system_prompt?: string; welcome_message?: string; voice_id?: string; output_format?: string; }; }; type OnMessageCallback = (message: PhonicSTSWebSocketResponseMessage) => void; type OnCloseCallback = (event: WebSocket.CloseEvent) => void; type OnErrorCallback = (event: WebSocket.ErrorEvent) => void; type PhonicTool = "send_dtmf_tone" | "end_conversation"; type PhonicConfigurationEndpointRequestPayload = { project: { name: string; }; agent: { name: string; welcome_message: string; system_prompt: string; tools: Array<PhonicTool>; boosted_keywords: string[]; }; from_phone_number?: string; to_phone_number?: string; }; type PhonicConfigurationEndpointResponsePayload = { welcome_message?: string | null; system_prompt?: string; template_variables?: Record<string, string>; tools?: Array<PhonicTool>; boosted_keywords?: string[]; }; type Agent = { id: string; name: string; org_id: string; project: { id: string; name: string; }; phone_number: string | null; voice_id: string; audio_format: "pcm_44100" | "mulaw_8000"; welcome_message: string | null; system_prompt: string; template_variables: Record<string, { default_value: string | null; }>; tools: Array<PhonicSTSTool>; no_input_poke_sec: number | null; no_input_poke_text: string; no_input_end_conversation_sec: number; boosted_keywords: string[]; configuration_endpoint: { url: string; headers: Record<string, string>; timeout_ms: number; } | null; }; type ListAgentsParams = { project?: string; }; type ListAgentsSuccessResponse = { agents: Array<Agent>; }; type GetAgentParams = { project?: string; }; type GetAgentSuccessResponse = { agent: Agent; }; interface AgentOptionalParams { project?: string; timezone?: string; voiceId?: string; audioSpeed?: number; welcomeMessage?: string; systemPrompt?: string; templateVariables?: Record<string, { defaultValue: string | null; }>; tools?: Array<PhonicSTSTool>; noInputPokeSec?: number | null; noInputPokeText?: string; noInputEndConversationSec?: number; boostedKeywords?: string[]; configurationEndpoint?: { url: string; headers?: Record<string, string>; timeoutMs?: number; } | null; } interface CreateAgentBaseParams extends AgentOptionalParams { name: string; } interface AgentPhoneNumberParams { phoneNumber: "assign-automatically"; audioFormat?: "mulaw_8000"; } interface AgentNoPhoneNumberParams { phoneNumber?: null; audioFormat?: "pcm_44100" | "mulaw_8000"; } interface CreateAgentWithPhoneNumberParams extends CreateAgentBaseParams, AgentPhoneNumberParams { } interface CreateAgentWithoutPhoneNumberParams extends CreateAgentBaseParams, AgentNoPhoneNumberParams { } type CreateAgentParams = CreateAgentWithPhoneNumberParams | CreateAgentWithoutPhoneNumberParams; type CreateAgentSuccessResponse = { id: string; name: string; }; interface UpdateAgentBaseParams extends AgentOptionalParams { name?: string; } interface UpdateAgentWithPhoneNumberParams extends UpdateAgentBaseParams, AgentPhoneNumberParams { } interface UpdateAgentWithoutPhoneNumberParams extends UpdateAgentBaseParams, AgentNoPhoneNumberParams { } type UpdateAgentParams = UpdateAgentWithPhoneNumberParams | UpdateAgentWithoutPhoneNumberParams; type UpdateAgentSuccessResponse = { success: true; }; interface UpsertAgentBaseParams extends AgentOptionalParams { name: string; } interface UpsertAgentWithPhoneNumberParams extends UpsertAgentBaseParams, AgentPhoneNumberParams { } interface UpsertAgentWithoutPhoneNumberParams extends UpsertAgentBaseParams, AgentNoPhoneNumberParams { } type UpsertAgentParams = UpsertAgentWithPhoneNumberParams | UpsertAgentWithoutPhoneNumberParams; interface UpsertAgentSuccessResponseBase { agent: Agent; } interface UpsertAgentInsertedSuccessResponse extends UpsertAgentSuccessResponseBase { inserted: true; updated: false; } interface UpsertAgentUpdatedSuccessResponse extends UpsertAgentSuccessResponseBase { inserted: false; updated: true; } type UpsertAgentSuccessResponse = UpsertAgentInsertedSuccessResponse | UpsertAgentUpdatedSuccessResponse; type DeleteAgentParams = { project?: string; }; type DeleteAgentSuccessResponse = { success: true; }; declare class Agents { private readonly phonic; constructor(phonic: Phonic); private getQueryString; private getTemplateVariablesForBody; private getConfigurationEndpointForBody; list(params?: ListAgentsParams): DataOrError<ListAgentsSuccessResponse>; get(nameOrId: string, params?: GetAgentParams): DataOrError<GetAgentSuccessResponse>; create(params: CreateAgentParams): DataOrError<CreateAgentSuccessResponse>; update(nameOrId: string, params: UpdateAgentParams): DataOrError<UpdateAgentSuccessResponse>; upsert(params: UpsertAgentParams): DataOrError<UpsertAgentSuccessResponse>; delete(nameOrId: string, params?: DeleteAgentParams): DataOrError<DeleteAgentSuccessResponse>; } type ConversationSuccessResponse = { conversation: Conversation; }; type ConversationsSuccessResponse = { conversations: Array<Conversation>; }; type OutboundCallConfig = Omit<PhonicSTSConfigWithAgent, "input_format" | "output_format"> | Omit<PhonicSTSConfigWithProject, "input_format" | "output_format">; type OutboundCallSuccessResponse = { conversation_id: string; }; type TwilioOutboundCallParams = { account_sid: string; api_key_sid: string; api_key_secret: string; from_phone_number: string; to_phone_number: string; }; type TwilioOutboundCallConfig = OutboundCallConfig; type TwilioOutboundCallSuccessResponse = { callSid: string; }; declare class Twilio { private readonly phonic; constructor(phonic: Phonic); outboundCall(params: TwilioOutboundCallParams, config: TwilioOutboundCallConfig): DataOrError<TwilioOutboundCallSuccessResponse>; } declare class Conversations { private readonly phonic; readonly twilio: Twilio; constructor(phonic: Phonic); list({ project, durationMin, durationMax, startedAtMin, startedAtMax, }: { project?: string; durationMin?: number; durationMax?: number; startedAtMin?: ISODate | ISODateTime; startedAtMax?: ISODate | ISODateTime; }): DataOrError<ConversationsSuccessResponse>; get(id: string): DataOrError<ConversationSuccessResponse>; getByExternalId({ project, externalId, }: { project?: string; externalId: string; }): DataOrError<ConversationSuccessResponse>; outboundCall(toPhoneNumber: string, config: OutboundCallConfig): DataOrError<OutboundCallSuccessResponse>; } type Project = { id: string; name: string; default_agent: { id: string; name: string; } | null; }; type ListProjectsSuccessResponse = { projects: Array<Project>; }; type GetProjectSuccessResponse = { project: Project; }; type CreateProjectParams = { name: string; }; type CreateProjectSuccessResponse = { id: string; name: string; }; type UpdateProjectParams = { name?: string; defaultAgent?: string; }; type UpdateProjectSuccessResponse = { success: true; }; type DeleteProjectSuccessResponse = { success: true; }; declare class Projects { private readonly phonic; constructor(phonic: Phonic); list(): DataOrError<ListProjectsSuccessResponse>; get(nameOrId: string): DataOrError<GetProjectSuccessResponse>; create(params: CreateProjectParams): DataOrError<CreateProjectSuccessResponse>; update(nameOrId: string, params: UpdateProjectParams): DataOrError<UpdateProjectSuccessResponse>; delete(nameOrId: string): DataOrError<DeleteProjectSuccessResponse>; } declare class PhonicSTSWebSocket { private readonly ws; private readonly config; private onMessageCallback; private onCloseCallback; private onErrorCallback; private buffer; private isOpen; constructor(ws: WebSocket, config: PhonicSTSConfig); private processUserMessage; onMessage(callback: OnMessageCallback): void; onClose(callback: OnCloseCallback): void; onError(callback: OnErrorCallback): void; audioChunk({ audio }: { audio: string; }): void; sendToolCallOutput({ toolCallId, output, }: { toolCallId: string; output: unknown; }): void; updateSystemPrompt({ systemPrompt }: { systemPrompt: string; }): void; setExternalId({ externalId }: { externalId: string; }): void; close(code?: number): void; } declare class SpeechToSpeech { private readonly phonic; constructor(phonic: Phonic); websocket(config: PhonicSTSConfig): PhonicSTSWebSocket; } interface ParameterBase { name: string; description: string; isRequired: boolean; } interface PrimitiveParameter extends ParameterBase { type: "string" | "integer" | "number" | "boolean"; } interface ArrayParameter extends ParameterBase { type: "array"; itemType: "string" | "integer" | "number" | "boolean"; } type ToolParameters = Array<PrimitiveParameter | ArrayParameter>; type ExecutionMode = "sync" | "async"; interface ToolBase { id: string; name: string; description: string; execution_mode: ExecutionMode; parameters: ToolParameters; } interface WebhookTool extends ToolBase { type: "custom_webhook"; endpoint_method: "POST"; endpoint_url: string; endpoint_headers: Record<string, string>; endpoint_timeout_ms: number; } interface WebSocketTool extends ToolBase { type: "custom_websocket"; tool_call_output_timeout_ms: number; } type Tool = WebhookTool | WebSocketTool; type ListToolsParams = { project?: string; }; type ListToolsSuccessResponse = DataOrError<{ tools: Array<Tool>; }>; type GetToolParams = { project?: string; }; type GetToolSuccessResponse = DataOrError<{ tool: Tool; }>; interface CreateToolParamsBase { project?: string; name: string; description: string; executionMode: ExecutionMode; parameters?: ToolParameters; } interface CreateWebhookToolParams extends CreateToolParamsBase { type: "custom_webhook"; endpointMethod: "POST"; endpointUrl: string; endpointHeaders?: Record<string, string>; endpointTimeoutMs?: number; } interface CreateWebSocketToolParams extends CreateToolParamsBase { type: "custom_websocket"; toolCallOutputTimeoutMs?: number; } type CreateToolParams = CreateWebhookToolParams | CreateWebSocketToolParams; type CreateToolSuccessResponse = { id: string; name: string; }; type UpdateToolParams = { project?: string; name?: string; description?: string; type?: "custom_webhook" | "custom_websocket"; executionMode?: ExecutionMode; endpointMethod?: "POST"; endpointUrl?: string; endpointHeaders?: Record<string, string>; endpointTimeoutMs?: number; toolCallOutputTimeoutMs?: number; parameters?: ToolParameters; }; type UpdateToolSuccessResponse = { success: true; }; type DeleteToolParams = { project?: string; }; type DeleteToolSuccessResponse = { success: true; }; declare class Tools { private readonly phonic; constructor(phonic: Phonic); private getQueryString; private getParametersForBody; list(params?: ListToolsParams): DataOrError<ListToolsSuccessResponse>; get(nameOrId: string, params?: GetToolParams): DataOrError<GetToolSuccessResponse>; create(params: CreateToolParams): DataOrError<CreateToolSuccessResponse>; update(nameOrId: string, params: UpdateToolParams): DataOrError<UpdateToolSuccessResponse>; delete(nameOrId: string, params?: DeleteToolParams): DataOrError<DeleteToolSuccessResponse>; } type Voice = { id: string; name: string; }; type VoicesSuccessResponse = { voices: Array<Voice>; }; type VoiceSuccessResponse = { voice: Voice; }; declare class Voices { private readonly phonic; constructor(phonic: Phonic); list({ model }: { model: string; }): DataOrError<VoicesSuccessResponse>; get(id: string): DataOrError<VoiceSuccessResponse>; } declare class Phonic { readonly apiKey: string; readonly baseUrl: string; readonly __downstreamWebSocketUrl: string | null; readonly headers: Record<string, string>; readonly agents: Agents; readonly conversations: Conversations; readonly projects: Projects; readonly tools: Tools; readonly voices: Voices; readonly sts: SpeechToSpeech; constructor(apiKey: string, config?: PhonicConfig); fetchRequest<T>(path: string, options: FetchOptions): DataOrError<T>; get<T>(path: string): Promise<{ data: null; error: { message: string; code?: string; param_errors?: Record<string, string>; }; } | { data: T; error: null; }>; post<T>(path: string, body: Record<string, unknown>, headers?: Record<string, string>): Promise<{ data: null; error: { message: string; code?: string; param_errors?: Record<string, string>; }; } | { data: T; error: null; }>; patch<T>(path: string, body: Record<string, unknown>, headers?: Record<string, string>): Promise<{ data: null; error: { message: string; code?: string; param_errors?: Record<string, string>; }; } | { data: T; error: null; }>; put<T>(path: string, body: Record<string, unknown>, headers?: Record<string, string>): Promise<{ data: null; error: { message: string; code?: string; param_errors?: Record<string, string>; }; } | { data: T; error: null; }>; delete<T>(path: string, headers?: Record<string, string>): Promise<{ data: null; error: { message: string; code?: string; param_errors?: Record<string, string>; }; } | { data: T; error: null; }>; } export { type ConversationAnalysisWebhookPayload, type ConversationEndedWebhookPayload, Phonic, type PhonicConfigurationEndpointRequestPayload, type PhonicConfigurationEndpointResponsePayload, type PhonicSTSConfig, PhonicSTSWebSocket, type PhonicSTSWebSocketResponseMessage };