Search code examples
javascriptnode.jsredisdialogflow-es

store agent SessionsClient of dialogflow api


I'm integrating dialogflow in my chat, but i'm having a problem. I can't figure out how can i store the session with the agent

async startSession({projectId, google_app_credencials}) {
    process.env.GOOGLE_APPLICATION_CREDENTIALS = google_app_credencials;
    const sessionId = uuid.v4();
    const sessionClient = new dialogflow.SessionsClient();
    const sessionPath = await sessionClient.projectAgentSessionPath(projectId, sessionId)
    await sessionClient.initialize();

    return {
        sessionId: sessionId,
        sessionClient: sessionClient,
        sessionPath: sessionPath,
    };
}
async sendMessageAndGetResponse(message, {sessionPath, sessionClient}) {
    const request = {
        session: sessionPath,
        queryInput: {
            text: {
                text: message,
                languageCode: 'pt-BR',
            },
        },
    };

    const responses = await sessionClient.detectIntent(request);
    const result = responses[0].queryResult;
    return {
        response: result.fulfillmentText,
        fields: result.parameters.fields,

    }
}

I need the return of startSession in every call of sendMessageAndGetResponse and i need to store then e my nodejs server. but my attempts of store SessionsClient in redis failed. Now i wanna know if there is a way of re establish the connection with the agente just with the SessionPath in the future calls.

//attempt to save in redis

let dialogflowBot = {
    projectId: dialogflow.project_name,
    google_app_credencials:  DialogflowHelper.getCredentialsPath(dialogflow)
}
dialogflowBot.bot = await DialogflowHelper.startSession(dialogflowBot);
redisClient.set(filaChat.id_registro, JSON.stringify(dialogflowBot));

//error: Converting circular structure to JSON

//Can't save the sessionClient

how can i save the SessionClient for call him again later, or save just the SessionPath for re establish the connection again?


Solution

  • I solved this just saving the SessionId and passing this same id in future calls instead of generating a new one

    async reestablishSession({projectId, google_app_credentials, sessionId}) {
        process.env.GOOGLE_APPLICATION_CREDENTIALS = google_app_credentials;
        const sessionClient = new dialogflow.SessionsClient();
        const sessionPath = await sessionClient.projectAgentSessionPath(projectId, sessionId)
        await sessionClient.initialize();
        return {
            sessionId: sessionId,
            sessionClient: sessionClient,
            sessionPath: sessionPath,
        };
    }