* chore: Upgrade prisma to 6.7.0 * Build fixes * type fixes Signed-off-by: Omar López <zomars@me.com> * Update schema.prisma * Patching * Revert "Update schema.prisma" This reverts commit 47d8618bf89ef4d007b30084df766f17281e21a1. * Revert "Patching" This reverts commit a1d2e3040e71690a44d4324db95d73b4d68c6adb. * Revert schema changes Signed-off-by: Omar López <zomars@me.com> * WIP Signed-off-by: Omar López <zomars@me.com> * Update getPublicEvent.ts * Update imports Signed-off-by: Omar López <zomars@me.com> * Update gitignore Signed-off-by: Omar López <zomars@me.com> * update remaining imports Signed-off-by: Omar López <zomars@me.com> * Delete .cursor/config.json * Discard changes to packages/features/eventtypes/lib/getPublicEvent.ts * Update _get.ts * Update user.ts * Update .gitignore * update * Update WorkflowStepContainer.tsx * Update next-auth-custom-adapter.ts * Update getPublicEvent.ts * Update workflow.ts * Update next-auth-custom-adapter.ts * Update next-auth-options.ts * Update bookingScenario.ts * fix missing imports * upgrades prismock Signed-off-by: Omar López <zomars@me.com> * patches prismock Signed-off-by: Omar López <zomars@me.com> * Update reschedule.test.ts * Update prisma.ts * patch prismock Signed-off-by: Omar López <zomars@me.com> * fix enums imports Signed-off-by: Omar López <zomars@me.com> * Revert "Update prisma.ts" This reverts commit 64edcf8db54171ff4456c209d563b5d431d99619. * Revert "patch prismock" This reverts commit e95819113dc9d88e7130947aa120cd42710977c8. * fix patch * Fix test that overrun the boundary, it shouldn't test too much * Move prisma import to changeSMSLockState * Bring back broken test without illegal imports * Merge with main and fix filter hosts by same round robin host * Fixed buildDryRunBooking fn tests * Fix and move ooo create or update handler test * Fix packages/features/eventtypes/lib/isCurrentlyAvailable.test.ts * Fix packages/trpc/server/routers/viewer/organizations/listMembers.handler.test.ts * Mock @calcom/prisma * Fix: verify-email.test.ts * fix: Moved WebhookService test and fixed default import mock * Fix: Added missing prisma mock, handleNewBooking uses that of course * We're not testing createContext here * fix: Prisma mock fix for listMembers.test.ts * More fixes to broken testcases * Forgot to remove borked test * Prevent the need to mock a lot of dependencies by moving out buildBaseWhereCondition to its own file * Temporarily skip getCalendarEvents, needs a rewrite * Fix: turns out you can access protected in testcases * fix further mocks * Added packages/features/insights/server/buildBaseWhereCondition.ts, types * Always great to have a mock and then not use it * And one less again. * fix: confirm.handler.test, didn't mock prisma * fix: Address minor nit by @eunjae & fix ImpersonationProvider test * Updated isPrismaAvailableCheck that doesn't crash on import * fix: Get Prisma directly from the client, it usually involves the Validator and does not need 'local' inclusion * Add zod-prisma-types without the generator enabled (commented out) * Uncomment and see what happens * Change method of import as imports did not work in Input Schemas * Remove custom 'zod' booking model, it does not belong with Prisma * Fix all other global Model imports * Rewrite most schema includes AND remove barrel file * Add bookingCreateBodySchema to features/bookings * Flurry of type fixes for compatibility with new zod gen * Refactor out the custom prisma type createEventTypeInput * Work around nullable eventTypeLocations * HandlePayment type fix * More fixes, final fix remaining is CompleteEventType * Should fix a bunch more booking related type errors * Missed one * Some props missing from BookingCreateBodySchema * Fix location type in handleChildrenEventTypes * Little bit hacky imo but it works * Final type error \o/ * Forgot to include Prisma * Do not include zod-utils in booker/types * Oops, was already including Booker/types * Fix membership type, also disallow updating createdAt/updatedAt, make part of patch/post * Fix api v1 type errors * Fix EventTypeDescription typings * Remove getParserWithGeneric, use userBodySchema with UserSchema * use centralized timeZoneSchema * Implement feedback by @zomars * Couple of WIP pushes * Fix tests * Type fixes in `handleChildrenEventTypes` test * Try and parse metadata before use * Change zod-prisma-types configuration for optimal performance * Fix prisma validator error in `prisma/selects/credential` * Disable seperate relations model, hits a bug * Import absolute - this makes rollup work in @platform/libraries * Attempt at removing resolutions override * Refactor using `Prisma.validator` to `satisfies` * Build atoms using @calcom/prisma/client * Build atoms using @calcom/prisma/client * fixes * Update eventTypeSelect.ts * Adjust `eventTypeMetaDataSchemaWithUntypedApps` from `unknown` to `record(any)` * `EventTypeDescription` rely on `descriptionAsSafeHTML` instead of `description` * Add `seatsPerTimeSlot` to event type public select * Fix typing in `users-public-view` getServerSide props * Add missing `schedulingType` to prop * chore: bump platform libraries * Function return type is illegal, not sure how this passed eslint (#21567) * Merged with main * Update updateTokenObject.ts * Update handleResponse.ts * Update index.ts * Update handleChildrenEventTypes.ts * Update booking-idempotency-key.ts * Update WebhookService.test.ts * Update events.test.ts * Update queued-response.test.ts * Update events.test.ts * Update getRoutedUrl.test.ts * fix: type checks Signed-off-by: Omar López <zomars@me.com> * fixes Signed-off-by: Omar López <zomars@me.com> * chore: bump platform libraries * Update yarn.lock * more fixes Signed-off-by: Omar López <zomars@me.com> * fixes Signed-off-by: Omar López <zomars@me.com> * biuld fixes * chore: bump platform libraries * Update conferencing.repository.ts * Update conferencing.repository.ts * Update getCalendarsEvents.test.ts * Update vite.config.js * chore: bump platform libraries * Update users.ts * Discard changes to docs/api-reference/v2/openapi.json * Update vite.config.ts * updated platform libraries * Update get.handler.test.ts * Update get.handler.test.ts * Update schema.prisma * Discard changes to docs/api-reference/v2/openapi.json * Update next-auth-custom-adapter.ts * Update team.ts * Flurry of type fixes * Fix majority of insight related type errors * Type fixes for unlink of account * Make user nullable again * Fixed a bunch of unit tests and one type error * Attempted mock fix * Attempted fix for Attribute type * Ensure default import becomes prisma, but not direct usage * Import default as prisma in prisma.module * Add attributeOption to attribute type * Fix calcom/prisma mock * Refactor Prisma client imports to @calcom/prisma/client Updated all imports from '@prisma/client' to '@calcom/prisma/client' across tests and repository files for consistency and to use the correct Prisma client package. This change improves maintainability and ensures the correct client is referenced throughout the codebase. * Undo removal of max-warnings=0 to get main to merge * Remove unit tests for e2e fixtures, provide new prisma mock * Mock @calcom/prisma in event manager * Mock @calcom/prisma in event manager * Add correct format even with --no-verify * Mock prisma in CalendarManager * Add mock for permission-check.service * Better injection in PrismaApiKeyRepository imports * More mock fixes :) * Fix listMembers.handler.test * Fix User import * Appropriately adjust all types to be imported as types, there were a lot of types imported as normal deps * Why was this a thing? * Strictly speaking; Not using prismock anymore * Ditched patch file for prismock * Fix output.service.ts platform type imports, need concrete for plainToClass * Better typing and tests for unlinkConnectedAccount.handler * Small type fix * Disable calendar cache tests as they are dependent on prismock * chore: bump platform lib * getRoutedUrl test remove of unused import * Extract select to external const on getEventTypesFromDB * Direct select of userSelect from selects/user * fix type error from merging 23653 * Fixed integration tests by removing hardcoded values that were possible due to mocking, but as its now directly hitting the db no longer * fix: vite config atoms prisma client type location * revert: example app prisma client * revert: example app prisma client * bump platform libs * fix: use class instead of type for DI of PlatformBookingsService * update platform libs * remove unused variable * chore: generate prisma client for api v2 * fix: api v2 e2e * fix: atoms e2e * fix: atoms e2e * fix: atoms e2e * fix: api v2 e2e * fix: tsconfig apiv2 enums * publish libraries * Simplify check for existence teamId --------- Signed-off-by: Omar López <zomars@me.com> Co-authored-by: Alex van Andel <me@alexvanandel.com> Co-authored-by: Joe Au-Yeung <j.auyeung419@gmail.com> Co-authored-by: supalarry <laurisskraucis@gmail.com> Co-authored-by: cal.com <morgan@cal.com> Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com> Co-authored-by: Benny Joo <sldisek783@gmail.com>
641 lines
18 KiB
TypeScript
641 lines
18 KiB
TypeScript
import { v4 as uuidv4 } from "uuid";
|
|
|
|
import { RETELL_AI_TEST_MODE, RETELL_AI_TEST_EVENT_TYPE_MAP } from "@calcom/lib/constants";
|
|
import { timeZoneSchema } from "@calcom/lib/dayjs/timeZone.schema";
|
|
import { HttpError } from "@calcom/lib/http-error";
|
|
import logger from "@calcom/lib/logger";
|
|
import { PrismaApiKeyRepository } from "@calcom/lib/server/repository/PrismaApiKeyRepository";
|
|
|
|
import type {
|
|
AIPhoneServiceUpdateModelParams,
|
|
AIPhoneServiceProviderType,
|
|
AIPhoneServiceAgent,
|
|
AIPhoneServiceModel,
|
|
AIPhoneServiceTools,
|
|
} from "../../../interfaces/AIPhoneService.interface";
|
|
import type { AgentRepositoryInterface } from "../../interfaces/AgentRepositoryInterface";
|
|
import { RetellAIServiceMapper } from "../RetellAIServiceMapper";
|
|
import type { RetellAIRepository, Language } from "../types";
|
|
import { getLlmId } from "../types";
|
|
|
|
export class AgentService {
|
|
private logger = logger.getSubLogger({ prefix: ["AgentService"] });
|
|
|
|
constructor(
|
|
private retellRepository: RetellAIRepository,
|
|
private agentRepository: AgentRepositoryInterface
|
|
) {}
|
|
|
|
private async createApiKey({ userId, teamId }: { userId: number; teamId?: number }) {
|
|
const apiKeyRepository = await PrismaApiKeyRepository.withGlobalPrisma();
|
|
return await apiKeyRepository.createApiKey({
|
|
userId,
|
|
teamId,
|
|
expiresAt: null,
|
|
note: `Cal AI Phone API Key for agent ${userId} ${teamId ? `for team ${teamId}` : ""}`,
|
|
});
|
|
}
|
|
|
|
async getAgent(agentId: string): Promise<AIPhoneServiceAgent<AIPhoneServiceProviderType.RETELL_AI>> {
|
|
if (!agentId?.trim()) {
|
|
throw new HttpError({
|
|
statusCode: 400,
|
|
message: "Agent ID is required and cannot be empty",
|
|
});
|
|
}
|
|
|
|
try {
|
|
return await this.retellRepository.getAgent(agentId);
|
|
} catch (error) {
|
|
this.logger.error("Failed to get agent from external AI service", {
|
|
agentId,
|
|
error,
|
|
});
|
|
throw new HttpError({
|
|
statusCode: 500,
|
|
message: `Failed to get agent ${agentId}`,
|
|
});
|
|
}
|
|
}
|
|
|
|
async updateToolsFromAgentId(
|
|
agentId: string,
|
|
data: { eventTypeId: number | null; timeZone: string; userId: number | null; teamId?: number | null }
|
|
) {
|
|
if (!agentId?.trim()) {
|
|
throw new HttpError({
|
|
statusCode: 400,
|
|
message: "Agent ID is required and cannot be empty",
|
|
});
|
|
}
|
|
|
|
if (!data.eventTypeId || !data.userId) {
|
|
throw new HttpError({
|
|
statusCode: 400,
|
|
message: "Event type ID and user ID are required",
|
|
});
|
|
}
|
|
|
|
if (!timeZoneSchema.safeParse(data.timeZone).success) {
|
|
throw new HttpError({
|
|
statusCode: 400,
|
|
message: "Invalid time zone",
|
|
});
|
|
}
|
|
|
|
let eventTypeId = data.eventTypeId;
|
|
|
|
if (RETELL_AI_TEST_MODE && RETELL_AI_TEST_EVENT_TYPE_MAP) {
|
|
const mappedId = RETELL_AI_TEST_EVENT_TYPE_MAP[String(data.eventTypeId)];
|
|
eventTypeId = mappedId ? Number(mappedId) : data.eventTypeId;
|
|
}
|
|
|
|
try {
|
|
const agent = await this.getAgent(agentId);
|
|
const llmId = getLlmId(agent);
|
|
|
|
if (!llmId) {
|
|
throw new HttpError({
|
|
statusCode: 404,
|
|
message: "Agent does not have an LLM configured.",
|
|
});
|
|
}
|
|
const llmDetails = await this.retellRepository.getLLM(llmId);
|
|
|
|
if (!llmDetails) {
|
|
throw new HttpError({ statusCode: 404, message: "LLM details not found." });
|
|
}
|
|
|
|
const existing = llmDetails?.general_tools ?? [];
|
|
|
|
const hasCheck = existing.some((t) => t.name === `check_availability_${eventTypeId}`);
|
|
const hasBook = existing.some((t) => t.name === `book_appointment_${eventTypeId}`);
|
|
// If both already exist and end_call also exists, nothing to do
|
|
const hasEndCallAlready = existing.some((t) => t.type === "end_call");
|
|
if (hasCheck && hasBook && hasEndCallAlready) {
|
|
return;
|
|
}
|
|
|
|
const reusableKey = existing.find(
|
|
(t): t is Extract<typeof t, { cal_api_key: string }> =>
|
|
"cal_api_key" in t && typeof t.cal_api_key === "string"
|
|
)?.cal_api_key;
|
|
|
|
const apiKey =
|
|
RETELL_AI_TEST_MODE && process.env.RETELL_AI_TEST_CAL_API_KEY
|
|
? process.env.RETELL_AI_TEST_CAL_API_KEY
|
|
: reusableKey ??
|
|
(await this.createApiKey({
|
|
userId: data.userId,
|
|
teamId: data.teamId || undefined,
|
|
}));
|
|
|
|
const newEventTools: NonNullable<AIPhoneServiceTools<AIPhoneServiceProviderType.RETELL_AI>> = [];
|
|
if (!hasCheck) {
|
|
newEventTools.push({
|
|
name: `check_availability_${eventTypeId}`,
|
|
type: "check_availability_cal",
|
|
event_type_id: eventTypeId,
|
|
cal_api_key: apiKey,
|
|
timezone: data.timeZone,
|
|
});
|
|
}
|
|
if (!hasBook) {
|
|
newEventTools.push({
|
|
name: `book_appointment_${eventTypeId}`,
|
|
type: "book_appointment_cal",
|
|
event_type_id: eventTypeId,
|
|
cal_api_key: apiKey,
|
|
timezone: data.timeZone,
|
|
});
|
|
}
|
|
|
|
if (!hasEndCallAlready) {
|
|
newEventTools.unshift({
|
|
type: "end_call",
|
|
name: "end_call",
|
|
description: "Hang up the call, triggered only after appointment successfully scheduled.",
|
|
});
|
|
}
|
|
|
|
const updatedGeneralTools = [...existing, ...newEventTools];
|
|
|
|
await this.retellRepository.updateLLM(llmId, { general_tools: updatedGeneralTools });
|
|
} catch (error) {
|
|
if (error instanceof HttpError) {
|
|
throw error;
|
|
}
|
|
|
|
this.logger.error("Failed to update agent general tools in external AI service", {
|
|
agentId,
|
|
error,
|
|
});
|
|
throw new HttpError({
|
|
statusCode: 500,
|
|
message: `Failed to update agent general tools ${agentId}: ${
|
|
error instanceof Error ? error.message : "Unknown error"
|
|
}`,
|
|
});
|
|
}
|
|
}
|
|
|
|
async removeToolsForEventTypes(agentId: string, eventTypeIds: number[]) {
|
|
if (!agentId?.trim()) {
|
|
throw new HttpError({
|
|
statusCode: 400,
|
|
message: "Agent ID is required and cannot be empty",
|
|
});
|
|
}
|
|
|
|
if (!eventTypeIds.length) {
|
|
return;
|
|
}
|
|
|
|
let mappedEventTypeIds = eventTypeIds;
|
|
|
|
if (RETELL_AI_TEST_MODE && RETELL_AI_TEST_EVENT_TYPE_MAP) {
|
|
mappedEventTypeIds = eventTypeIds.map((id) => {
|
|
const mappedId = RETELL_AI_TEST_EVENT_TYPE_MAP[String(id)];
|
|
return mappedId ? Number(mappedId) : id;
|
|
});
|
|
}
|
|
|
|
try {
|
|
const agent = await this.getAgent(agentId);
|
|
const llmId = getLlmId(agent);
|
|
|
|
if (!llmId) {
|
|
throw new HttpError({
|
|
statusCode: 404,
|
|
message: "Agent does not have an LLM configured.",
|
|
});
|
|
}
|
|
|
|
const llmDetails = await this.retellRepository.getLLM(llmId);
|
|
|
|
if (!llmDetails) {
|
|
throw new HttpError({ statusCode: 404, message: "LLM details not found." });
|
|
}
|
|
|
|
const existing = llmDetails?.general_tools ?? [];
|
|
|
|
const toolNamesToRemove = mappedEventTypeIds.flatMap((eventTypeId) => [
|
|
`check_availability_${eventTypeId}`,
|
|
`book_appointment_${eventTypeId}`,
|
|
]);
|
|
|
|
const filteredTools = existing.filter((tool) => !toolNamesToRemove.includes(tool.name));
|
|
|
|
if (filteredTools.length !== existing.length) {
|
|
await this.retellRepository.updateLLM(llmId, { general_tools: filteredTools });
|
|
this.logger.info("Removed event-specific tools from agent", {
|
|
agentId,
|
|
llmId,
|
|
removedEventTypes: eventTypeIds,
|
|
mappedEventTypes: RETELL_AI_TEST_MODE ? mappedEventTypeIds : undefined,
|
|
toolsRemoved: existing.length - filteredTools.length,
|
|
});
|
|
}
|
|
} catch (error) {
|
|
if (error instanceof HttpError) {
|
|
throw error;
|
|
}
|
|
|
|
this.logger.error("Failed to remove event-specific tools from agent", {
|
|
agentId,
|
|
eventTypeIds,
|
|
error,
|
|
});
|
|
throw new HttpError({
|
|
statusCode: 500,
|
|
message: `Failed to remove tools for agent ${agentId}`,
|
|
});
|
|
}
|
|
}
|
|
|
|
async cleanupUnusedTools(agentId: string, activeEventTypeIds: number[] = []) {
|
|
if (!agentId?.trim()) {
|
|
throw new HttpError({
|
|
statusCode: 400,
|
|
message: "Agent ID is required and cannot be empty",
|
|
});
|
|
}
|
|
|
|
let mappedActiveEventTypeIds = activeEventTypeIds;
|
|
|
|
if (RETELL_AI_TEST_MODE && RETELL_AI_TEST_EVENT_TYPE_MAP) {
|
|
mappedActiveEventTypeIds = activeEventTypeIds.map((id) => {
|
|
const mappedId = RETELL_AI_TEST_EVENT_TYPE_MAP[String(id)];
|
|
return mappedId ? Number(mappedId) : id;
|
|
});
|
|
}
|
|
|
|
try {
|
|
const agent = await this.getAgent(agentId);
|
|
const llmId = getLlmId(agent);
|
|
|
|
if (!llmId) {
|
|
throw new HttpError({
|
|
statusCode: 404,
|
|
message: "Agent does not have an LLM configured.",
|
|
});
|
|
}
|
|
|
|
const llmDetails = await this.retellRepository.getLLM(llmId);
|
|
|
|
if (!llmDetails) {
|
|
throw new HttpError({ statusCode: 404, message: "LLM details not found." });
|
|
}
|
|
|
|
const existing = llmDetails?.general_tools ?? [];
|
|
|
|
const eventSpecificTools = existing.filter(
|
|
(tool) => tool.name.includes("check_availability_") || tool.name.includes("book_appointment_")
|
|
);
|
|
|
|
const toolsToRemove = eventSpecificTools.filter((tool) => {
|
|
// Extract event type ID from tool name
|
|
const eventTypeIdMatch = tool.name.match(/_(\d+)$/);
|
|
if (!eventTypeIdMatch) return false;
|
|
|
|
const eventTypeId = parseInt(eventTypeIdMatch[1]);
|
|
return !mappedActiveEventTypeIds.includes(eventTypeId);
|
|
});
|
|
|
|
if (toolsToRemove.length > 0) {
|
|
const toolNamesToRemove = toolsToRemove.map((tool) => tool.name);
|
|
const filteredTools = existing.filter((tool) => !toolNamesToRemove.includes(tool.name));
|
|
|
|
await this.retellRepository.updateLLM(llmId, { general_tools: filteredTools });
|
|
|
|
this.logger.info("Cleaned up unused event-specific tools", {
|
|
agentId,
|
|
llmId,
|
|
removedTools: toolsToRemove.length,
|
|
toolNames: toolNamesToRemove,
|
|
});
|
|
|
|
return {
|
|
removedCount: toolsToRemove.length,
|
|
removedTools: toolNamesToRemove,
|
|
};
|
|
}
|
|
|
|
return {
|
|
removedCount: 0,
|
|
removedTools: [],
|
|
};
|
|
} catch (error) {
|
|
if (error instanceof HttpError) {
|
|
throw error;
|
|
}
|
|
|
|
this.logger.error("Failed to cleanup unused tools for agent", {
|
|
agentId,
|
|
activeEventTypeIds,
|
|
mappedActiveEventTypeIds: RETELL_AI_TEST_MODE ? mappedActiveEventTypeIds : undefined,
|
|
error,
|
|
});
|
|
throw new HttpError({
|
|
statusCode: 500,
|
|
message: `Failed to cleanup tools for agent ${agentId}`,
|
|
});
|
|
}
|
|
}
|
|
|
|
async updateAgent(
|
|
agentId: string,
|
|
data: {
|
|
agent_name?: string | null;
|
|
voice_id?: string;
|
|
language?: Language;
|
|
responsiveness?: number;
|
|
interruption_sensitivity?: number;
|
|
}
|
|
): Promise<AIPhoneServiceAgent<AIPhoneServiceProviderType.RETELL_AI>> {
|
|
if (!agentId?.trim()) {
|
|
throw new HttpError({ statusCode: 400, message: "Agent ID is required and cannot be empty" });
|
|
}
|
|
|
|
if (!data || Object.keys(data).length === 0) {
|
|
throw new HttpError({ statusCode: 400, message: "Update data is required" });
|
|
}
|
|
|
|
try {
|
|
const updateRequest = RetellAIServiceMapper.mapToUpdateAgentRequest(data);
|
|
return await this.retellRepository.updateAgent(agentId, updateRequest);
|
|
} catch (error) {
|
|
this.logger.error("Failed to update agent in external AI service", {
|
|
agentId,
|
|
data,
|
|
error,
|
|
});
|
|
throw new HttpError({
|
|
statusCode: 500,
|
|
message: `Failed to update agent ${agentId}`,
|
|
});
|
|
}
|
|
}
|
|
|
|
async listAgents({
|
|
userId,
|
|
teamId,
|
|
scope = "all",
|
|
}: {
|
|
userId: number;
|
|
teamId?: number;
|
|
scope?: "personal" | "team" | "all";
|
|
}) {
|
|
const agents = await this.agentRepository.findManyWithUserAccess({
|
|
userId,
|
|
teamId,
|
|
scope,
|
|
});
|
|
|
|
const formattedAgents = agents.map((agent) => RetellAIServiceMapper.formatAgentForList(agent));
|
|
|
|
return {
|
|
totalCount: formattedAgents.length,
|
|
filtered: formattedAgents,
|
|
};
|
|
}
|
|
|
|
async getAgentWithDetails({ id, userId, teamId }: { id: string; userId: number; teamId?: number }) {
|
|
const agent = await this.agentRepository.findByIdWithUserAccessAndDetails({
|
|
id,
|
|
userId,
|
|
teamId,
|
|
});
|
|
|
|
if (!agent) {
|
|
throw new HttpError({
|
|
statusCode: 404,
|
|
message: "Agent not found or you don't have permission to view it.",
|
|
});
|
|
}
|
|
|
|
try {
|
|
const retellAgent = await this.getAgent(agent.providerAgentId);
|
|
const llmId = getLlmId(retellAgent);
|
|
|
|
if (!llmId) {
|
|
throw new HttpError({
|
|
statusCode: 404,
|
|
message: "Agent does not have an LLM configured.",
|
|
});
|
|
}
|
|
|
|
const llmDetails = await this.retellRepository.getLLM(llmId);
|
|
|
|
return RetellAIServiceMapper.formatAgentDetails(agent, retellAgent, llmDetails);
|
|
} catch (error) {
|
|
if (error instanceof HttpError) {
|
|
throw error;
|
|
}
|
|
|
|
this.logger.error("Failed to get agent details from external AI service", {
|
|
agentId: id,
|
|
providerAgentId: agent.providerAgentId,
|
|
userId,
|
|
teamId,
|
|
error,
|
|
});
|
|
throw new HttpError({
|
|
statusCode: 500,
|
|
message: "Unable to fetch agent details. Please try again.",
|
|
});
|
|
}
|
|
}
|
|
|
|
async createAgent({
|
|
name: _name,
|
|
userId,
|
|
teamId,
|
|
workflowStepId,
|
|
setupAIConfiguration,
|
|
}: {
|
|
name?: string;
|
|
userId: number;
|
|
teamId?: number;
|
|
workflowStepId?: number;
|
|
setupAIConfiguration: () => Promise<{ llmId: string; agentId: string }>;
|
|
}) {
|
|
const agentName = _name || `Agent - ${userId} ${uuidv4()}`;
|
|
|
|
if (teamId) {
|
|
const canManage = await this.agentRepository.canManageTeamResources({
|
|
userId,
|
|
teamId,
|
|
});
|
|
if (!canManage) {
|
|
throw new HttpError({
|
|
statusCode: 403,
|
|
message: "You don't have permission to create agents for this team.",
|
|
});
|
|
}
|
|
}
|
|
|
|
const llmConfig = await setupAIConfiguration();
|
|
|
|
const agent = await this.agentRepository.create({
|
|
name: agentName,
|
|
providerAgentId: llmConfig.agentId,
|
|
userId,
|
|
teamId,
|
|
});
|
|
|
|
if (workflowStepId) {
|
|
await this.agentRepository.linkToWorkflowStep({
|
|
workflowStepId,
|
|
agentId: agent.id,
|
|
});
|
|
}
|
|
|
|
return {
|
|
id: agent.id,
|
|
providerAgentId: agent.providerAgentId,
|
|
message: "Agent created successfully",
|
|
};
|
|
}
|
|
|
|
async updateAgentConfiguration({
|
|
id,
|
|
userId,
|
|
teamId,
|
|
name: _name,
|
|
generalPrompt,
|
|
beginMessage,
|
|
generalTools,
|
|
voiceId,
|
|
updateLLMConfiguration,
|
|
}: {
|
|
id: string;
|
|
userId: number;
|
|
teamId?: number;
|
|
name?: string;
|
|
generalPrompt?: string | null;
|
|
beginMessage?: string | null;
|
|
generalTools?: AIPhoneServiceTools<AIPhoneServiceProviderType.RETELL_AI>;
|
|
voiceId?: string;
|
|
updateLLMConfiguration: (
|
|
llmId: string,
|
|
data: AIPhoneServiceUpdateModelParams<AIPhoneServiceProviderType.RETELL_AI>
|
|
) => Promise<AIPhoneServiceModel<AIPhoneServiceProviderType.RETELL_AI>>;
|
|
}) {
|
|
const agent = await this.agentRepository.findByIdWithAdminAccess({
|
|
id,
|
|
userId,
|
|
teamId,
|
|
});
|
|
|
|
if (!agent) {
|
|
throw new HttpError({
|
|
statusCode: 404,
|
|
message: "Agent not found or you don't have permission to update it.",
|
|
});
|
|
}
|
|
|
|
const hasRetellUpdates =
|
|
generalPrompt !== undefined ||
|
|
beginMessage !== undefined ||
|
|
generalTools !== undefined ||
|
|
voiceId !== undefined;
|
|
|
|
if (hasRetellUpdates) {
|
|
try {
|
|
const retellAgent = await this.getAgent(agent.providerAgentId);
|
|
const llmId = getLlmId(retellAgent);
|
|
|
|
if (
|
|
llmId &&
|
|
(generalPrompt !== undefined || beginMessage !== undefined || generalTools !== undefined)
|
|
) {
|
|
const llmUpdateData = RetellAIServiceMapper.extractLLMUpdateData(
|
|
generalPrompt,
|
|
beginMessage,
|
|
generalTools
|
|
);
|
|
await updateLLMConfiguration(llmId, llmUpdateData);
|
|
}
|
|
|
|
if (voiceId) {
|
|
await this.updateAgent(agent.providerAgentId, {
|
|
voice_id: voiceId,
|
|
});
|
|
}
|
|
} catch (error) {
|
|
this.logger.error("Failed to update agent configuration in external AI service", {
|
|
agentId: id,
|
|
providerAgentId: agent.providerAgentId,
|
|
userId,
|
|
updates: {
|
|
generalPrompt: !!generalPrompt,
|
|
beginMessage: !!beginMessage,
|
|
generalTools: !!generalTools,
|
|
voiceId: !!voiceId,
|
|
},
|
|
error,
|
|
});
|
|
|
|
if (error instanceof HttpError) {
|
|
throw error;
|
|
}
|
|
|
|
throw new HttpError({
|
|
statusCode: 500,
|
|
message: "Unable to update agent configuration. Please try again.",
|
|
});
|
|
}
|
|
}
|
|
|
|
return { message: "Agent updated successfully" };
|
|
}
|
|
|
|
async deleteAgent({
|
|
id,
|
|
userId,
|
|
teamId,
|
|
deleteAIConfiguration,
|
|
}: {
|
|
id: string;
|
|
userId: number;
|
|
teamId?: number;
|
|
deleteAIConfiguration: (config: { agentId: string; llmId?: string }) => Promise<void>;
|
|
}) {
|
|
const agent = await this.agentRepository.findByIdWithAdminAccess({
|
|
id,
|
|
userId,
|
|
teamId,
|
|
});
|
|
|
|
if (!agent) {
|
|
throw new HttpError({
|
|
statusCode: 404,
|
|
message: "Agent not found or you don't have permission to delete it.",
|
|
});
|
|
}
|
|
|
|
try {
|
|
const retellAgent = await this.getAgent(agent.providerAgentId);
|
|
const llmId = getLlmId(retellAgent);
|
|
|
|
await deleteAIConfiguration({
|
|
agentId: agent.providerAgentId,
|
|
llmId: llmId || undefined,
|
|
});
|
|
} catch (error) {
|
|
this.logger.error("Failed to delete agent from external AI service", {
|
|
agentId: id,
|
|
providerAgentId: agent.providerAgentId,
|
|
userId,
|
|
teamId,
|
|
error,
|
|
});
|
|
}
|
|
|
|
await this.agentRepository.delete({ id });
|
|
|
|
return { message: "Agent deleted successfully" };
|
|
}
|
|
}
|