|
| 1 | +import { config } from 'dotenv'; |
| 2 | +import express, { Application } from 'express'; |
| 3 | +import { AzureCommunicationTokenCredential } from '@azure/communication-common'; |
| 4 | +import { ChatClient } from '@azure/communication-chat'; |
| 5 | +import { AzureKeyCredential, OpenAIClient } from '@azure/openai'; |
| 6 | +config(); |
| 7 | + |
| 8 | +const PORT = process.env.PORT; |
| 9 | +const ACS_URL_ENDPOINT = process.env.ACS_URL_ENDPOINT; |
| 10 | +const app: Application = express(); |
| 11 | +app.use(express.json()); |
| 12 | +const TRANSLATION_LANGUAGE = 'spanish'; // Change this to the target language you want to translate to |
| 13 | + |
| 14 | +let openAiClient : OpenAIClient; |
| 15 | + |
| 16 | +const numMessagesToSummarize = 10; |
| 17 | +const summarizationSystemPrompt = 'Act like you are a agent specialized in generating summary of a chat conversation, you will be provided with a JSON list of messages of a conversation, generate a summary for the conversation based on the content message.'; |
| 18 | +const sentimentSystemPrompt = 'Act like you are a agent specialized in generating sentiment of a chat message, please provide the sentiment of the given message as POSITIVE, NEGATIVE or NEUTRAL.'; |
| 19 | +const translationSystemPrompt = 'Act like you are a agent specialized in generating translation of a chat message, please translate the given message to the TARGET_LANGUAGE. If you do not understand language or recognized words, just echo back the original message'; |
| 20 | + |
| 21 | +/* Azure Open AI Service */ |
| 22 | +async function createOpenAiClient() { |
| 23 | + const openAiServiceEndpoint = process.env.AZURE_OPENAI_SERVICE_ENDPOINT || ""; |
| 24 | + const openAiKey = process.env.AZURE_OPENAI_SERVICE_KEY || ""; |
| 25 | + openAiClient = new OpenAIClient( |
| 26 | + openAiServiceEndpoint, |
| 27 | + new AzureKeyCredential(openAiKey) |
| 28 | + ); |
| 29 | + console.log("Initialized Open AI Client."); |
| 30 | +} |
| 31 | + |
| 32 | +async function getChatCompletions(systemPrompt: string, userPrompt: string){ |
| 33 | + const deploymentName = process.env.AZURE_OPENAI_DEPLOYMENT_MODEL_NAME; |
| 34 | + const messages = [ |
| 35 | + { role: "system", content: systemPrompt }, |
| 36 | + { role: "user", content: userPrompt }, |
| 37 | + ]; |
| 38 | + |
| 39 | + const response = await openAiClient.getChatCompletions(deploymentName, messages); |
| 40 | + const responseContent = response.choices[0].message.content; |
| 41 | + console.log(responseContent); |
| 42 | + return responseContent; |
| 43 | +} |
| 44 | + |
| 45 | +/* Azure Communication Service */ |
| 46 | +async function getRecentMessages(token: string, threadId: string) { |
| 47 | + const chatClient = new ChatClient(ACS_URL_ENDPOINT, new AzureCommunicationTokenCredential(token)); |
| 48 | + const threadClient = chatClient.getChatThreadClient(threadId); |
| 49 | + const messagesIterator = threadClient.listMessages({ maxPageSize: numMessagesToSummarize }); |
| 50 | + const messages = []; |
| 51 | + for await (const message of messagesIterator) { |
| 52 | + messages.push(message); |
| 53 | + } |
| 54 | + return messages; |
| 55 | +} |
| 56 | + |
| 57 | +async function getMessage(token: string, threadId: string, messageId: string) { |
| 58 | + const chatClient = new ChatClient(ACS_URL_ENDPOINT, new AzureCommunicationTokenCredential(token)); |
| 59 | + const threadClient = chatClient.getChatThreadClient(threadId); |
| 60 | + const message = await threadClient.getMessage(messageId); |
| 61 | + return message; |
| 62 | +} |
| 63 | + |
| 64 | +/* API routes */ |
| 65 | +app.get('/api/chat/:threadId/summary', async (req: any, res: any)=>{ |
| 66 | + // Authnorization header format: "Bearer <ACS_TOKEN>" |
| 67 | + const token = req.headers['authorization'].split(' ')[1]; |
| 68 | + const { threadId } = req.params; |
| 69 | + try{ |
| 70 | + const messages = await getRecentMessages(token, threadId); |
| 71 | + const result = await getChatCompletions(summarizationSystemPrompt, JSON.stringify(messages)) |
| 72 | + res.json(result); |
| 73 | + } |
| 74 | + catch(error){ |
| 75 | + console.error("Error during get summary.", error); |
| 76 | + } |
| 77 | +}); |
| 78 | + |
| 79 | +app.get('/api/chat/:threadId/message/:messageId/sentiment', async (req: any, res: any)=>{ |
| 80 | + // Authnorization header format: "Bearer <ACS_TOKEN>" |
| 81 | + const token = req.headers['authorization'].split(' ')[1]; |
| 82 | + const { threadId, messageId } = req.params; |
| 83 | + try{ |
| 84 | + const message = await getMessage(token, threadId, messageId); |
| 85 | + const result = await getChatCompletions(sentimentSystemPrompt, message.content.message); |
| 86 | + res.json(result); |
| 87 | + } |
| 88 | + catch(error){ |
| 89 | + console.error("Error during get sentiment.", error); |
| 90 | + } |
| 91 | +}); |
| 92 | + |
| 93 | +app.get('/api/chat/:threadId/message/:messageId/translation/:language', async (req: any, res: any)=>{ |
| 94 | + // Authnorization header format: "Bearer <ACS_TOKEN>" |
| 95 | + const token = req.headers['authorization'].split(' ')[1]; |
| 96 | + const { threadId, messageId, language } = req.params; |
| 97 | + try{ |
| 98 | + const message = await getMessage(token, threadId, messageId); |
| 99 | + const systemPrompt = translationSystemPrompt.replace('TARGET_LANGUAGE', language); |
| 100 | + const result = await getChatCompletions(systemPrompt, message.content.message); |
| 101 | + res.json(result); |
| 102 | + } |
| 103 | + catch(error){ |
| 104 | + console.error("Error during get translation.", error); |
| 105 | + } |
| 106 | +}); |
| 107 | + |
| 108 | +// EventGrid |
| 109 | +app.post("/api/chatMessageReceived", async (req: any, res:any)=>{ |
| 110 | + console.log(`Received chatMessageReceived event - data --> ${JSON.stringify(req.body)} `); |
| 111 | + const event = req.body[0]; |
| 112 | + |
| 113 | + try{ |
| 114 | + const eventData = event.data; |
| 115 | + if (event.eventType === "Microsoft.EventGrid.SubscriptionValidationEvent") { |
| 116 | + console.log("Received SubscriptionValidation event"); |
| 117 | + res.status(200).json({ |
| 118 | + validationResponse: eventData.validationCode |
| 119 | + }); |
| 120 | + return; |
| 121 | + } |
| 122 | + |
| 123 | + const messageId = event.data.messageId; |
| 124 | + |
| 125 | + // Sentiment Analysis |
| 126 | + const sentimentResult = await getChatCompletions(sentimentSystemPrompt, event.data.messageBody); |
| 127 | + console.log(`Sentiment ${messageId}: ${sentimentResult}`); |
| 128 | + |
| 129 | + // Translation |
| 130 | + const translaitonPrompt = translationSystemPrompt.replace('TARGET_LANGUAGE', TRANSLATION_LANGUAGE); |
| 131 | + const translationResult = await getChatCompletions(translaitonPrompt, event.data.messageBody); |
| 132 | + console.log(`Translating ${messageId}: ${translationResult}`); |
| 133 | + } |
| 134 | + catch(error){ |
| 135 | + console.error("Error during the message recieved event.", error); |
| 136 | + } |
| 137 | +}); |
| 138 | + |
| 139 | +app.get('/', (req, res) => { |
| 140 | + res.send('Hello ACS Chat!'); |
| 141 | +}); |
| 142 | + |
| 143 | +// Start the server |
| 144 | +app.listen(PORT, async () => { |
| 145 | + console.log(`Server is listening on port ${PORT}`); |
| 146 | + await createOpenAiClient(); |
| 147 | +}); |
0 commit comments