-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathconversationTopics.ts
More file actions
169 lines (149 loc) · 5.49 KB
/
Copy pathconversationTopics.ts
File metadata and controls
169 lines (149 loc) · 5.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import type {
AnalyticsApi,
Models,
SpeechTextAnalyticsApi,
} from "purecloud-platform-client-v2";
import { z } from "zod";
import { createTool, type ToolFactory } from "../utils/createTool.js";
import { errorResult } from "../utils/errorResult.js";
import { isUnauthorisedError } from "../utils/genesys/isUnauthorisedError.js";
import { chunks } from "./chunks.js";
export interface ToolDependencies {
readonly speechTextAnalyticsApi: Pick<
SpeechTextAnalyticsApi,
"getSpeechandtextanalyticsTopics"
>;
readonly analyticsApi: Pick<
AnalyticsApi,
| "getAnalyticsConversationDetails"
| "postAnalyticsTranscriptsAggregatesQuery"
>;
}
const MAX_IDS_ALLOWED_BY_API = 50;
const paramsSchema = z.object({
conversationId: z
.string()
.uuid()
.describe(
"A UUID for a conversation. (e.g., 00000000-0000-0000-0000-000000000000)",
),
});
export const conversationTopics: ToolFactory<
ToolDependencies,
typeof paramsSchema
> = ({ speechTextAnalyticsApi, analyticsApi }) =>
createTool({
schema: {
name: "conversation_topics",
annotations: { title: "Conversation Topics" },
description:
"Retrieves Speech and Text Analytics topics detected for a specific conversation. Topics represent business-level intents (e.g. cancellation, billing enquiry) inferred from recognised phrases in the customer-agent interaction.",
paramsSchema,
},
call: async ({ conversationId }) => {
let conversationDetails: Models.AnalyticsConversationWithoutAttributes;
try {
conversationDetails =
await analyticsApi.getAnalyticsConversationDetails(conversationId);
} catch (error: unknown) {
const errorMessage = isUnauthorisedError(error)
? "Failed to retrieve conversation topics: Unauthorised access. Please check API credentials or permissions"
: `Failed to retrieve conversation topics: ${error instanceof Error ? error.message : JSON.stringify(error)}`;
return errorResult(errorMessage);
}
if (
!conversationDetails.conversationStart ||
!conversationDetails.conversationEnd
) {
return errorResult(
"Unable to find conversation Start and End date needed for retrieving topics",
);
}
// Widen the time range either side to ensure the conversation timeframe is enclosed.
// Conversation not returned if either only partially covered by interval, or matched exactly.
const startDate = new Date(conversationDetails.conversationStart);
startDate.setMinutes(startDate.getMinutes() - 10);
const endDate = new Date(conversationDetails.conversationEnd);
endDate.setMinutes(endDate.getMinutes() + 10);
let jobDetails: Models.TranscriptAggregateQueryResponse;
try {
jobDetails = await analyticsApi.postAnalyticsTranscriptsAggregatesQuery(
{
interval: `${startDate.toISOString()}/${endDate.toISOString()}`,
filter: {
type: "and",
predicates: [
{
dimension: "conversationId",
value: conversationId,
},
{
dimension: "resultsBy",
value: "communication",
},
],
},
groupBy: ["topicId"],
metrics: ["nTopicCommunications"],
},
);
} catch (error: unknown) {
const errorMessage = isUnauthorisedError(error)
? "Failed to retrieve conversation topics: Unauthorised access. Please check API credentials or permissions"
: `Failed to retrieve conversation topics: ${error instanceof Error ? error.message : JSON.stringify(error)}`;
return errorResult(errorMessage);
}
const topicIds = new Set<string>();
for (const result of jobDetails.results ?? []) {
if (result.group?.topicId) {
topicIds.add(result.group.topicId);
}
}
if (topicIds.size === 0) {
return {
content: [
{
type: "text",
text: `Conversation ID: ${conversationId}\nNo detected topics for this conversation.`,
},
],
};
}
const topics: Models.ListedTopic[] = [];
try {
for (const topicIdChunk of chunks(
Array.from(topicIds.values()),
MAX_IDS_ALLOWED_BY_API,
)) {
const topicsListings =
await speechTextAnalyticsApi.getSpeechandtextanalyticsTopics({
ids: topicIdChunk,
pageSize: MAX_IDS_ALLOWED_BY_API,
});
topics.push(...(topicsListings.entities ?? []));
}
} catch (error: unknown) {
const errorMessage = isUnauthorisedError(error)
? "Failed to retrieve conversation topics: Unauthorised access. Please check API credentials or permissions"
: `Failed to retrieve conversation topics: ${error instanceof Error ? error.message : JSON.stringify(error)}`;
return errorResult(errorMessage);
}
const topicNames = topics
.filter((topic) => topic.name && topic.description)
.map(({ name, description }) => ({
name: name ?? "",
description: description ?? "",
}));
return {
content: [
{
type: "text",
text: JSON.stringify({
conversationId: conversationId,
detectedTopics: topicNames,
}),
},
],
};
},
});