Skip to content

Commit

Permalink
Merge branch 'dev' of github.com:AgrI-Mitra/bff
Browse files Browse the repository at this point in the history
  • Loading branch information
Amruth-Vamshi committed Feb 9, 2024
2 parents 87106d5 + 4ad08de commit e5604ad
Show file tree
Hide file tree
Showing 8 changed files with 118 additions and 40 deletions.
6 changes: 1 addition & 5 deletions .github/workflows/build-and-push.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ name: Build and Push Docker Image
on:
push:
branches:
- dev
- main

env:
Expand Down Expand Up @@ -44,8 +45,3 @@ jobs:
cache-to: type=gha,mode=max
tags: ${{ env.DOCKER_REGISTRY }}/${{ steps.lower-repo.outputs.repository }}:${{env.DOCKER_IMAGE_TAG}}
labels: org.opencontainers.image.source=https://github.com/${{steps.lower-repo.outputs.repository}}

- name: Invoke deployment hook
uses: distributhor/workflow-webhook@v3
env:
webhook_url: ${{ secrets.WEBHOOK_URL }}
23 changes: 13 additions & 10 deletions src/app.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { interpret } from "xstate";
import { Language } from "./language";
import { ConfigService } from "@nestjs/config";
import { AiToolsService } from "./modules/aiTools/ai-tools.service";
import { formatStringsToTable, wordToNumber } from "./common/utils";
import { formatStringsToTable, removeLinks, wordToNumber } from "./common/utils";
import { ConversationService } from "./modules/conversation/conversation.service";
import { PrismaService } from "./global-services/prisma.service";
import { CustomLogger } from "./common/logger";
Expand Down Expand Up @@ -995,19 +995,22 @@ export class AppController {
this.monitoringService.incrementTotalSessionsInEnglishCount();
break;
}
messageType = "final_response"
let resArray = result.text.split("\n")
let compareText = result.textInEnglish.split('\n')
if(compareText[compareText.length-1].slice(0,12)=="Registration"){
textToaudio = ""
} else {
textToaudio = resArray.pop()
messageType = botFlowService.state.context.queryType == "convo" ? "convo_response" : "final_response"
if(botFlowService.state.context.isWadhwaniResponse == 'false'){
let resArray = result.text.split("\n")
let compareText = result.textInEnglish.split('\n')
if(compareText[compareText.length-1].slice(0,12)=="Registration"){
textToaudio = ""
} else {
textToaudio = resArray.pop()
}
// verboseLogger("Array to convert",resArray)
result.text = `${formatStringsToTable(resArray)}\n${textToaudio}`
}
// verboseLogger("Array to convert",resArray)
result.text = `${formatStringsToTable(resArray)}\n${textToaudio}`
}
// verboseLogger("textToaudio =",textToaudio)
let audioStartTime = Date.now();
textToaudio = removeLinks(textToaudio)
result['audio'] = await this.aiToolsService.textToSpeech(textToaudio,isNumber ? Language.en : prompt.inputLanguage)
if(result['audio']['error']){
await this.telemetryService.capture({
Expand Down
2 changes: 1 addition & 1 deletion src/common/kisanPortalErrors.json
Original file line number Diff line number Diff line change
Expand Up @@ -191,4 +191,4 @@
"text": "Dear {{farmer_name}}, I have checked your account and found that you received all the instalments till now from your PM KISAN registration date {{Reg_Date (DD-MM-YYYY)}}. You will receive your next instalment payment soon in your Aadhaar seeded bank account."
}

}
}
8 changes: 8 additions & 0 deletions src/common/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,4 +211,12 @@ export const wordToNumber = (input,type='benId') => {
return number + "th";
}
}
}

export const removeLinks = (inputString) => {
// Define a regular expression pattern for identifying links
var linkPattern = /http[s]?:\/\/(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+/g;
// Use the replace() method to replace all links with an empty string
var resultString = inputString.replace(linkPattern, '');
return resultString;
}
46 changes: 39 additions & 7 deletions src/modules/aiTools/ai-tools.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ import { MonitoringService } from '../monitoring/monitoring.service';
const fetch = require('../../common/fetch');
const nodefetch = require('node-fetch');
const { Headers } = require('node-fetch');
const path = require('path');
const filePath = path.resolve(__dirname, '../../common/en.json');
const engMessage = require(filePath);

@Injectable()
export class AiToolsService {
constructor(
Expand Down Expand Up @@ -219,14 +223,21 @@ export class AiToolsService {
async textClassification(text: string) {
try{
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
let body = {
text: text
}
let response: any = await fetch(`${this.configService.get("HUGGINGFACE_TEXT_CLASSIFICATION_BASE_URL")}`, {
myHeaders.append("accept", "application/json");
myHeaders.append("X-API-Key", this.configService.get("WADHWANI_API_KEY"));
// let body = {
// text: text
// }
// let response: any = await fetch(`${this.configService.get("HUGGINGFACE_TEXT_CLASSIFICATION_BASE_URL")}`, {
// headers: myHeaders,
// "body": JSON.stringify(body),
// "method": "POST",
// "mode": "cors",
// "credentials": "omit"
// });
let response: any = await fetch(`${this.configService.get("WADHWANI_BASE_URL")}/detect_query_intent?query=${text}`, {
headers: myHeaders,
"body": JSON.stringify(body),
"method": "POST",
"method": "GET",
"mode": "cors",
"credentials": "omit"
});
Expand All @@ -240,6 +251,27 @@ export class AiToolsService {
}
}

async getResponseViaWadhwani(text: string) {
try{
var myHeaders = new Headers();
myHeaders.append("accept", "application/json");
myHeaders.append("X-API-Key", this.configService.get("WADHWANI_API_KEY"));
let response: any = await fetch(`${this.configService.get("WADHWANI_BASE_URL")}/get_bot_response?query=${text}`, {
headers: myHeaders,
"method": "GET",
"mode": "cors",
"credentials": "omit"
});
response = (await response.text()).replace(/^\"|\"$/g, '')
return response
} catch(error){
console.log(error)
return {
error
}
}
}

async getBhashiniConfig(task,config) {
const cacheKey = `getBhashiniConfig:${JSON.stringify({ task, config })}`;

Expand Down
2 changes: 1 addition & 1 deletion src/xstate/prompt/prompt.gaurds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ export const promptGuards = {

ifInvalidClassifier: (_,event) => event.data == "invalid",

ifConvoStarterOrEnder: (_,event) => event.data == "convo_starter" || event.data == "convo_ender"
ifConvoStarterOrEnder: (_,event) => event.data == "convo"

}
46 changes: 38 additions & 8 deletions src/xstate/prompt/prompt.machine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -785,7 +785,8 @@ export const botFlowMachine3:any =
lastAadhaarDigits:'',
state:'onGoing',
userId:'',
isOTPVerified: false
isOTPVerified: false,
isWadhwaniResponse: "false"
},
states: {
checkStateAndJump: {
Expand Down Expand Up @@ -877,29 +878,29 @@ export const botFlowMachine3:any =
onDone: [
{
cond: "ifConvoStarterOrEnder",
target: "getUserQuestion",
target: "wadhwaniClassifier",
actions: [
assign({
response: () => engMessage["message.convoStarter"],
type:"pause"
queryType: (_,event) => event.data,
isWadhwaniResponse: "true"
})
]
},
{
cond: "ifInvalidClassifier",
target: "getUserQuestion",
target: "wadhwaniClassifier",
actions: [
assign({
response: () => engMessage["message.invalid_question"],
type:"pause"
isWadhwaniResponse: "true"
})
]
},
{
target: 'checkIfOTPHasBeenVerified',
actions: [
assign({
queryType: (_,event) => {console.log(`assigning queryType = ${event.data}`); return event.data}
queryType: (_,event) => event.data,
isWadhwaniResponse: "false"
})
]
}
Expand All @@ -915,6 +916,35 @@ export const botFlowMachine3:any =
}
}
},
wadhwaniClassifier: {
invoke: {
src: "wadhwaniClassifier",
onDone: {
target: 'endFlow',
actions: [
assign({
response: (_, event) => event.data,
userAadhaarNumber: "",
lastAadhaarDigits: "",
isOTPVerified: false,
type: ''
})
]
},
onError: {
target: 'error',
actions: [
assign({
userAadhaarNumber: "",
lastAadhaarDigits: "",
isOTPVerified: false,
error: (_, event) => event.data.message,
type: ''
})
]
}
}
},
checkIfOTPHasBeenVerified: {
invoke: {
src: "getInput",
Expand Down
25 changes: 17 additions & 8 deletions src/xstate/prompt/prompt.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,13 @@ export class PromptServices {
try{
let response: any = await this.aiToolsService.textClassification(context.query)
if (response.error) throw new Error(`${response.error}, please try again.`)
if (response == "LABEL_2") {
this.monitoringService.incrementUntrainedQueryCount()
if (response == `"Invalid"`) return "convo"
if (response == `"convo_starter"`) return "convo"
if (response == `"convo_ender"`) return "convo"
if (response == `"Installment not received"`) return "payment"
else {
return "invalid"
}
if (response == "LABEL_1") return "payment"
if (response == "LABEL_0") return "payment"
if (response == "LABEL_3") return "convo_starter"
if (response == "LABEL_4") return "convo_ender"
return response;
} catch (error){
return Promise.reject(error)
}
Expand Down Expand Up @@ -198,14 +196,25 @@ export class PromptServices {
return `${userDetails}${userErrors.join("\n")}`
}

async wadhwaniClassifier (context) {
try{
let response: any = await this.aiToolsService.getResponseViaWadhwani(context.query)
if (response.error) throw new Error(`${response.error}, please try again.`)
return response;
} catch (error){
return Promise.reject(error)
}
}

allFunctions() {
return {
getInput: this.getInput.bind(this),
questionClassifier: this.questionClassifier.bind(this),
logError: this.logError.bind(this),
validateAadhaarNumber: this.validateAadhaarNumber.bind(this),
validateOTP: this.validateOTP.bind(this),
fetchUserData: this.fetchUserData.bind(this)
fetchUserData: this.fetchUserData.bind(this),
wadhwaniClassifier: this.wadhwaniClassifier.bind(this),
}
}

Expand Down

0 comments on commit e5604ad

Please sign in to comment.