feat: cal ai templates (#15391)
* chore: save progress * feat: add schema and fieds * chore: update code * chore: save * refactor: code and type error * feat: use facade + command design pattern * chore: missing param * feat: add custom template feature * refactor: code * chore: move the default prompt * fix: type err * fix: code and ux improvements * chore: change default template * fix: ui and typo * fix: add validation check for my phone number --------- Co-authored-by: Joe Au-Yeung <[email protected]>
This commit is contained in:
1 parent
c6febad364
commit
199d95b35f
17 files changed
+759
-340
No files matched your search
@@ -1,5 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { templateTypeEnum } from "@calcom/features/ee/cal-ai-phone/zod-utils";
|
||||
import { _DestinationCalendarModel, _EventTypeModel } from "@calcom/prisma/zod";
|
||||
import { customInputSchema, EventTypeMetaDataSchema, stringOrNumber } from "@calcom/prisma/zod-utils";
|
||||
import { eventTypeBookingFields } from "@calcom/prisma/zod-utils";
|
||||
@@ -16,9 +17,14 @@ export const EventTypeUpdateInput = _EventTypeModel
|
||||
beginMessage: z.string().nullable(),
|
||||
yourPhoneNumber: z.string().default(""),
|
||||
numberToCall: z.string().default(""),
|
||||
guestName: z.string().default(""),
|
||||
guestName: z
|
||||
.string()
|
||||
.nullable()
|
||||
.optional()
|
||||
.transform((val) => (!!val ? val : undefined)),
|
||||
guestEmail: z.string().nullable().default(null),
|
||||
guestCompany: z.string().nullable().default(null),
|
||||
templateType: templateTypeEnum,
|
||||
})
|
||||
.optional(),
|
||||
calAiPhoneScript: z.string().optional(),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createPhoneCallSchema } from "@calcom/features/ee/cal-ai-phone/zod-utils";
|
||||
import { ZVerifyCodeInputSchema } from "@calcom/prisma/zod-utils";
|
||||
import { AIPhoneSettingSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import authedProcedure, {
|
||||
authedAdminProcedure,
|
||||
@@ -161,7 +161,7 @@ export const viewerOrganizationsRouter = router({
|
||||
const handler = await importHandler(namespaced("adminDelete"), () => import("./adminDelete.handler"));
|
||||
return handler(opts);
|
||||
}),
|
||||
createPhoneCall: authedProcedure.input(AIPhoneSettingSchema).mutation(async (opts) => {
|
||||
createPhoneCall: authedProcedure.input(createPhoneCallSchema).mutation(async (opts) => {
|
||||
const handler = await importHandler(
|
||||
namespaced("createPhoneCall"),
|
||||
() => import("./createPhoneCall.handler")
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { z } from "zod";
|
||||
import type { z } from "zod";
|
||||
|
||||
import { PROMPT_TEMPLATES } from "@calcom/features/ee/cal-ai-phone/promptTemplates";
|
||||
import { RetellAIService, validatePhoneNumber } from "@calcom/features/ee/cal-ai-phone/retellAIService";
|
||||
import type { createPhoneCallSchema } from "@calcom/features/ee/cal-ai-phone/zod-utils";
|
||||
import { templateTypeEnum } from "@calcom/features/ee/cal-ai-phone/zod-utils";
|
||||
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { fetcher } from "@calcom/lib/retellAIFetcher";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import { getRetellLLMSchema } from "@calcom/prisma/zod-utils";
|
||||
import type { AIPhoneSettingSchema } from "@calcom/prisma/zod-utils";
|
||||
import { TRPCError } from "@calcom/trpc/server";
|
||||
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
|
||||
|
||||
type CreatePhoneCallProps = {
|
||||
@@ -14,35 +15,21 @@ type CreatePhoneCallProps = {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
prisma: PrismaClient;
|
||||
};
|
||||
input: z.infer<typeof AIPhoneSettingSchema>;
|
||||
input: z.infer<typeof createPhoneCallSchema>;
|
||||
};
|
||||
|
||||
const createRetellLLMSchema = z
|
||||
.object({
|
||||
llm_id: z.string(),
|
||||
llm_websocket_url: z.string(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const createPhoneSchema = z
|
||||
.object({
|
||||
call_id: z.string(),
|
||||
agent_id: z.string(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const getPhoneNumberSchema = z
|
||||
.object({
|
||||
agent_id: z.string(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const createPhoneCallHandler = async ({ input, ctx }: CreatePhoneCallProps) => {
|
||||
if (!!!ctx.user.profile.organization) {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
|
||||
await checkRateLimitAndThrowError({
|
||||
rateLimitingType: "core",
|
||||
identifier: `createPhoneCall:${ctx.user.id}`,
|
||||
});
|
||||
|
||||
await validatePhoneNumber(input.yourPhoneNumber);
|
||||
|
||||
const {
|
||||
yourPhoneNumber,
|
||||
numberToCall,
|
||||
@@ -51,69 +38,66 @@ const createPhoneCallHandler = async ({ input, ctx }: CreatePhoneCallProps) => {
|
||||
guestCompany,
|
||||
eventTypeId,
|
||||
beginMessage,
|
||||
generalPrompt,
|
||||
calApiKey,
|
||||
templateType,
|
||||
schedulerName,
|
||||
generalPrompt: userCustomPrompt,
|
||||
} = input;
|
||||
|
||||
const generalPrompt =
|
||||
templateType === templateTypeEnum.enum.CUSTOM_TEMPLATE
|
||||
? userCustomPrompt
|
||||
: PROMPT_TEMPLATES[templateType]?.generalPrompt;
|
||||
|
||||
const retellAI = new RetellAIService({
|
||||
templateType,
|
||||
generalPrompt: generalPrompt ?? "",
|
||||
yourPhoneNumber,
|
||||
loggedInUserTimeZone: ctx.user.timeZone,
|
||||
eventTypeId,
|
||||
calApiKey,
|
||||
dynamicVariables: {
|
||||
guestName,
|
||||
guestEmail,
|
||||
guestCompany,
|
||||
schedulerName,
|
||||
},
|
||||
});
|
||||
|
||||
const aiPhoneCallConfig = await ctx.prisma.aIPhoneCallConfiguration.upsert({
|
||||
where: {
|
||||
eventTypeId,
|
||||
},
|
||||
update: {
|
||||
beginMessage,
|
||||
generalPrompt,
|
||||
enabled: true,
|
||||
guestName,
|
||||
guestEmail,
|
||||
guestCompany,
|
||||
numberToCall,
|
||||
yourPhoneNumber,
|
||||
schedulerName,
|
||||
templateType,
|
||||
generalPrompt,
|
||||
},
|
||||
create: {
|
||||
eventTypeId,
|
||||
beginMessage,
|
||||
generalPrompt,
|
||||
enabled: true,
|
||||
guestName,
|
||||
guestEmail,
|
||||
guestCompany,
|
||||
numberToCall,
|
||||
yourPhoneNumber,
|
||||
schedulerName,
|
||||
templateType,
|
||||
generalPrompt,
|
||||
},
|
||||
});
|
||||
|
||||
let llmWebSocketUrlToBeUpdated = null;
|
||||
|
||||
// If no retell LLM is associated with the event type, create one
|
||||
if (!aiPhoneCallConfig.llmId) {
|
||||
const createdRetellLLM = await fetcher("/create-retell-llm", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
general_prompt: generalPrompt,
|
||||
begin_message: beginMessage,
|
||||
inbound_dynamic_variables_webhook_url: `${WEBAPP_URL}/api/get-inbound-dynamic-variables`,
|
||||
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);
|
||||
const createdRetellLLM = await retellAI.createRetellLLMAndUpdateWebsocketUrl();
|
||||
|
||||
await ctx.prisma.aIPhoneCallConfiguration.update({
|
||||
where: {
|
||||
@@ -123,54 +107,18 @@ const createPhoneCallHandler = async ({ input, ctx }: CreatePhoneCallProps) => {
|
||||
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,
|
||||
begin_message: beginMessage,
|
||||
inbound_dynamic_variables_webhook_url: `${WEBAPP_URL}/api/get-inbound-dynamic-variables`,
|
||||
}),
|
||||
}).then(getRetellLLMSchema.parse);
|
||||
const retellLLM = await retellAI.getRetellLLM(aiPhoneCallConfig.llmId);
|
||||
|
||||
const doWeNeedToUpdateLLM =
|
||||
retellLLM.general_prompt !== generalPrompt || retellLLM.begin_message !== beginMessage;
|
||||
if (doWeNeedToUpdateLLM) {
|
||||
const updatedRetellLLM = await retellAI.updatedRetellLLMAndUpdateWebsocketUrl(aiPhoneCallConfig.llmId);
|
||||
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, company: guestCompany, email: guestEmail },
|
||||
}),
|
||||
}).then(createPhoneSchema.parse);
|
||||
|
||||
const createPhoneCallRes = await retellAI.createRetellPhoneCall(numberToCall);
|
||||
logger.debug("Create Call Response", createPhoneCallRes);
|
||||
|
||||
return createPhoneCallRes;
|
||||
|
||||
Reference in new issue
Block a user