feat: cal.ai enterprise phone calls (#14100)

* added empty layout

* init

* yarn lock due to package changes

* added retell ai to .env

* removed ton of glue code

* nit

* Discard changes to package.json

* Upgrades lucide-react

* minor UI fixes

* nit

* nit

* feat: save progress

* feat: v1

* fix: type error

* feat: change schema

* fix: type error and testr

* chore: update agent

* chore: change default prompt

* feat: feedback and improvements

* fix: type error

* fix: type error

* hidden for now while in trial

* added i18n and removed some comments

* feat: add cal api key

* fix: type error

---------

Co-authored-by: Omar López <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Joe Au-Yeung <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-03-28 13:59:01 +00:00
1 parent eec76ecfe2
commit 1025238eee
42 files changed
+724 -59

No files matched your search

@@ -8,6 +8,17 @@ export const EventTypeUpdateInput = _EventTypeModel
/** Optional fields */
.extend({
isInstantEvent: z.boolean().optional(),
aiPhoneCallConfig: z
.object({
generalPrompt: z.string(),
enabled: z.boolean(),
beginMessage: z.string().nullable(),
yourPhoneNumber: z.string().default(""),
numberToCall: z.string().default(""),
guestName: z.string().default(""),
})
.optional(),
calAiPhoneScript: z.string().optional(),
customInputs: z.array(customInputSchema).optional(),
destinationCalendar: _DestinationCalendarModel
.pick({
@@ -49,12 +49,21 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
bookingFields,
offsetStart,
secondaryEmailId,
aiPhoneCallConfig,
...rest
} = input;
const eventType = await ctx.prisma.eventType.findUniqueOrThrow({
where: { id },
select: {
aiPhoneCallConfig: {
select: {
generalPrompt: true,
beginMessage: true,
enabled: true,
llmId: true,
},
},
children: {
select: {
userId: true,
@@ -345,6 +354,27 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
}
}
if (aiPhoneCallConfig) {
if (aiPhoneCallConfig.enabled) {
await ctx.prisma.aIPhoneCallConfiguration.upsert({
where: {
eventTypeId: id,
},
update: aiPhoneCallConfig,
create: {
...aiPhoneCallConfig,
eventTypeId: id,
},
});
} else if (!aiPhoneCallConfig.enabled && eventType.aiPhoneCallConfig) {
await ctx.prisma.aIPhoneCallConfiguration.delete({
where: {
eventTypeId: id,
},
});
}
}
const updatedEventTypeSelect = Prisma.validator<Prisma.EventTypeSelect>()({
slug: true,
schedulingType: true,
@@ -1,4 +1,5 @@
import { ZVerifyCodeInputSchema } from "@calcom/prisma/zod-utils";
import { AIPhoneSettingSchema } from "@calcom/prisma/zod-utils";
import authedProcedure, {
authedAdminProcedure,
@@ -141,4 +142,11 @@ export const viewerOrganizationsRouter = router({
const handler = await importHandler(namespaced("adminDelete"), () => import("./adminDelete.handler"));
return handler(opts);
}),
createPhoneCall: authedProcedure.input(AIPhoneSettingSchema).mutation(async (opts) => {
const handler = await importHandler(
namespaced("createPhoneCall"),
() => import("./createPhoneCall.handler")
);
return handler(opts);
}),
});
@@ -0,0 +1,180 @@
import { z } from "zod";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import { handleErrorsJson } from "@calcom/lib/errors";
import logger from "@calcom/lib/logger";
import type { PrismaClient } from "@calcom/prisma";
import type { AIPhoneSettingSchema } from "@calcom/prisma/zod-utils";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
type CreatePhoneCallProps = {
ctx: {
user: NonNullable<TrpcSessionUser>;
prisma: PrismaClient;
};
input: z.infer<typeof AIPhoneSettingSchema>;
};
const createRetellLLMSchema = z
.object({
llm_id: z.string(),
llm_websocket_url: z.string(),
})
.passthrough();
const getRetellLLMSchema = z
.object({
general_prompt: z.string(),
begin_message: z.string().nullable(),
})
.passthrough();
const createPhoneSchema = z
.object({
call_id: z.string(),
agent_id: z.string(),
})
.passthrough();
const getPhoneNumberSchema = z
.object({
agent_id: z.string(),
})
.passthrough();
export const fetcher = async (endpoint: string, init?: RequestInit | undefined) => {
return fetch(`https://api.retellai.com${endpoint}`, {
method: "GET",
headers: {
Authorization: `Bearer ${process.env.RETELL_AI_KEY}`,
"Content-Type": "application/json",
...init?.headers,
},
...init,
}).then(handleErrorsJson);
};
const createPhoneCallHandler = async ({ input, ctx }: CreatePhoneCallProps) => {
await checkRateLimitAndThrowError({
rateLimitingType: "core",
identifier: `createPhoneCall:${ctx.user.id}`,
});
const { yourPhoneNumber, numberToCall, guestName, eventTypeId, beginMessage, generalPrompt, calApiKey } =
input;
const aiPhoneCallConfig = await ctx.prisma.aIPhoneCallConfiguration.upsert({
where: {
eventTypeId,
},
update: {
beginMessage,
generalPrompt,
enabled: true,
guestName,
numberToCall,
yourPhoneNumber,
},
create: {
eventTypeId,
beginMessage,
generalPrompt,
enabled: true,
guestName,
numberToCall,
yourPhoneNumber,
},
});
let llmWebSocketUrlToBeUpdated = null;
if (!aiPhoneCallConfig.llmId) {
const createdRetellLLM = await fetcher("/create-retell-llm", {
method: "POST",
body: JSON.stringify({
general_prompt: generalPrompt,
begin_message: beginMessage,
general_tools: [
{
type: "end_call",
name: "end_call",
description: "Hang up the call, triggered only after appointment successfully scheduled.",
},
{
type: "check_availability_cal",
name: "check_availability",
cal_api_key: calApiKey,
event_type_id: eventTypeId,
timezone: ctx.user.timeZone,
},
{
type: "book_appointment_cal",
name: "book_appointment",
cal_api_key: calApiKey,
event_type_id: eventTypeId,
timezone: ctx.user.timeZone,
},
],
}),
}).then(createRetellLLMSchema.parse);
await ctx.prisma.aIPhoneCallConfiguration.update({
where: {
eventTypeId,
},
data: {
llmId: createdRetellLLM.llm_id,
},
});
llmWebSocketUrlToBeUpdated = createdRetellLLM.llm_websocket_url;
} else {
const retellLLM = await fetcher(`/get-retell-llm/${aiPhoneCallConfig.llmId}`).then(
getRetellLLMSchema.parse
);
if (retellLLM.general_prompt !== generalPrompt || retellLLM.begin_message !== beginMessage) {
const updatedRetellLLM = await fetcher(`/update-retell-llm/${aiPhoneCallConfig.llmId}`, {
method: "PATCH",
body: JSON.stringify({
general_prompt: generalPrompt,
}),
}).then(getRetellLLMSchema.parse);
logger.debug("updated Retell LLM", updatedRetellLLM);
llmWebSocketUrlToBeUpdated = updatedRetellLLM.llm_websocket_url;
}
}
if (llmWebSocketUrlToBeUpdated) {
const getPhoneNumberDetails = await fetcher(`/get-phone-number/${yourPhoneNumber}`).then(
getPhoneNumberSchema.parse
);
const updated = await fetcher(`/update-agent/${getPhoneNumberDetails.agent_id}`, {
method: "PATCH",
body: JSON.stringify({
llm_websocket_url: llmWebSocketUrlToBeUpdated,
}),
});
logger.debug("updated Retell Agent", updated);
}
// Create Phone Call
const createPhoneCallRes = await fetcher("/create-phone-call", {
method: "POST",
body: JSON.stringify({
from_number: yourPhoneNumber,
to_number: numberToCall,
retell_llm_dynamic_variables: { name: guestName },
}),
}).then(createPhoneSchema.parse);
logger.debug("Create Call Response", createPhoneCallRes);
return createPhoneCallRes;
};
export default createPhoneCallHandler;