Skip to content

Commit

Permalink
Added: Function for Extracting message from json
Browse files Browse the repository at this point in the history
  • Loading branch information
shreyvishal committed Mar 27, 2024
1 parent 32cbb07 commit 35ee204
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
28 changes: 28 additions & 0 deletions services/AI.js
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,34 @@ class AI {
}
return response;
}

async get_message_from_beckn_response(json_response) {
const openai_messages = [
{
role: 'system',
content: `You must validate this JSON object structure ${JSON.stringify(json_response)}. If JSON object is empty return a response in JSON object format {success:false, message:Empty JSON}. And if the JSON is invalid you should create an error message and set that in the message key of JSON object {success:false}. If its valid then create a meaningful text message containing all the information present in this json ${JSON.stringify(json_response)} based on the action description in the responses array of the json and return the message `,
},
]
let response = {
action: null,
response: null,
}
try {
const completion = await openai.chat.completions.create({
messages: openai_messages,
model: process.env.OPENAI_MODEL_ID,
temperature: 0,
response_format: { type: 'json_object' },
})
response = JSON.parse(completion.choices[0].message.content)
if (!response.success) {
throw new Error(response.message || 'Invalid JSON')
}
} catch (e) {
logger.error(e)
}
return response
}
}

export default AI;
15 changes: 14 additions & 1 deletion tests/unit/services/ai.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,4 +137,17 @@ describe('Test cases for services/ai/get_beckn_request_from_text()', () => {
expect(response.data.body.message.order.billing).to.have.property('email')
expect(response.data.body.message.order.billing).to.have.property('phone')
});
});
});


describe('Test cases for services/ai/get_message_from_beckn_response()', () => {
it('Should test get_message_from_beckn_response() and throw response with success false for empty object', async () => {
const response = await ai.get_message_from_beckn_response({})
expect(response.success).to.equal(false)
expect(response.message).to.equal('Empty JSON')
})
it('Should test get_message_from_beckn_response() return some message with success true', async () => {
const response = await ai.get_message_from_beckn_response(on_init)
expect(response.success).to.equal(true)
})
})

0 comments on commit 35ee204

Please sign in to comment.