Skip to content

Commit

Permalink
chore: wip
Browse files Browse the repository at this point in the history
Signed-off-by: sarthakjdev <[email protected]>
  • Loading branch information
sarthakjdev committed Jul 14, 2024
1 parent e914c25 commit a42d511
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 90 deletions.
48 changes: 24 additions & 24 deletions apps/wapi-ai-chatbot/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,39 +4,39 @@ import { askAi } from './utils/gpt'
import { cacheData, computeCacheKey, getCachedData } from './utils/cache'

async function init() {
try {
whatsappClient.on('Ready', () => {
console.log('Client is ready')
})
try {
whatsappClient.on('Ready', () => {
console.log('Client is ready')
})

whatsappClient.on('Error', error => {
console.error('Error', error.message)
})
whatsappClient.on('Error', error => {
console.error('Error', error.message)
})

whatsappClient.on('TextMessage', async (event: TextMessageEvent) => {
const aiResponse = await askAi(event.text.data.text, event.context.from)
await event.reply({
message: new TextMessage({
text: aiResponse
})
})
})
whatsappClient.on('TextMessage', async (event: TextMessageEvent) => {
const aiResponse = await askAi(event.text.data.text, event.context.from)
await event.reply({
message: new TextMessage({
text: aiResponse
})
})
})

whatsappClient.initiate()
} catch (error) {
console.error(error)
// ! TODO: you may prefer to send a notification to your slack channel or email here
}
whatsappClient.initiate()
} catch (error) {
console.error(error)
// ! TODO: you may prefer to send a notification to your slack channel or email here
}
}

init().catch(error => console.error(error))

process.on('unhandledRejection', error => {
console.error('unhandledRejection', error)
process.exit(1)
console.error('unhandledRejection', error)
process.exit(1)
})

process.on('uncaughtException', error => {
console.error('uncaughtException', error)
process.exit(1)
console.error('uncaughtException', error)
process.exit(1)
})
22 changes: 11 additions & 11 deletions apps/wapi-ai-chatbot/src/utils/cache.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
import { caching } from 'cache-manager'

const cacheStore = caching({
store: 'memory'
store: 'memory'
})

export async function cacheData(params: { key: string; data: any; ttl?: number }) {
const { key, ttl, data } = params
await cacheStore.set(key, data, { ...(ttl ? { ttl: ttl } : {}) })
const { key, ttl, data } = params
await cacheStore.set(key, data, { ...(ttl ? { ttl: ttl } : {}) })
}

export async function getCachedData<T>(key: string): Promise<T> {
const response = await cacheStore.get(key)
console.log(response)
return response as T
const response = await cacheStore.get(key)
console.log(response)
return response as T
}

export function computeCacheKey(params: { id: string; context: string }) {
return `${params.id}-${params.context}`
return `${params.id}-${params.context}`
}

export function getConversationContextCacheKey(phoneNumber: string) {
return computeCacheKey({
id: phoneNumber,
context: 'conversation'
})
return computeCacheKey({
id: phoneNumber,
context: 'conversation'
})
}
108 changes: 53 additions & 55 deletions apps/wapi-ai-chatbot/src/utils/gpt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,35 +7,34 @@ const organizationId = process.env.OPEN_AI_ORG_ID
const projectId = process.env.OPEN_AI_PROJECT_ID

if (!openAiApiKey || !organizationId || !projectId) {
throw new Error('OPEN_AI_API_KEY not defined!')
throw new Error('OPEN_AI_API_KEY not defined!')
}

const OpenApiClient = new OpenAI({
apiKey: openAiApiKey,
project: projectId,
organization: organizationId
apiKey: openAiApiKey,
project: projectId,
organization: organizationId
})


export async function askAi(message: string, fromPhoneNumber: string): Promise<string> {
try {
const contextCacheKey = getConversationContextCacheKey(fromPhoneNumber)
const context = await getCachedData<ConversationMessageType[]>(contextCacheKey)
try {
const contextCacheKey = getConversationContextCacheKey(fromPhoneNumber)
const context = await getCachedData<ConversationMessageType[]>(contextCacheKey)

let response = 'Sorry, I am not able to understand that.'
const responseCacheKey = computeCacheKey({
context: 'response_cache',
id: message.trim()
})
const cachedResponse = await getCachedData<string>(responseCacheKey)
if (cachedResponse) {
response = cachedResponse
} else {
const chatCompletion = await OpenApiClient.chat.completions.create({
messages: [
{
role: 'system',
content: `You are an intelligent assistant helping a user with their queries. You can provide information, answer questions, and help the user complete tasks.
let response = 'Sorry, I am not able to understand that.'
const responseCacheKey = computeCacheKey({
context: 'response_cache',
id: message.trim()
})
const cachedResponse = await getCachedData<string>(responseCacheKey)
if (cachedResponse) {
response = cachedResponse
} else {
const chatCompletion = await OpenApiClient.chat.completions.create({
messages: [
{
role: 'system',
content: `You are an intelligent assistant helping a user with their queries. You can provide information, answer questions, and help the user complete tasks.
You are a developer relation engineer for a product named as Wapi.js.
Wapi.js is an SDK to build chat bots and to integrate WhatsApp API with your application very easily.
The SDK is authored by Sarthak Jain having github at https://github.com/sarthakjdev and is an open-source SDk which is free to use.
Expand All @@ -44,38 +43,37 @@ export async function askAi(message: string, fromPhoneNumber: string): Promise<s
Also, you can reveal your identity, ack like a human, and provide information about the product.
Never ever accept that you are an AI or a chatbot or an intelligent assistant.
`
},
...(context ? context : []),
{
role: 'user',
content: message
}
],
model: 'gpt-4'
})
console.log(JSON.stringify({ chatCompletion }))
const aiResponse = chatCompletion.choices[0].message.content
if (aiResponse) response = aiResponse
}

await cacheData({
key: contextCacheKey,
data: [
...(context ? context : []),
{
role: AiConversationRoleEnum.User,
content: message
},
{
role: AiConversationRoleEnum.Ai,
content: response
},
},
...(context ? context : []),
{
role: 'user',
content: message
}
],
model: 'gpt-4'
})
console.log(JSON.stringify({ chatCompletion }))
const aiResponse = chatCompletion.choices[0].message.content
if (aiResponse) response = aiResponse
}

]
})
return response
} catch (error) {
console.log({ error })
return 'Sorry, I am not able to understand that.'
}
await cacheData({
key: contextCacheKey,
data: [
...(context ? context : []),
{
role: AiConversationRoleEnum.User,
content: message
},
{
role: AiConversationRoleEnum.Ai,
content: response
}
]
})
return response
} catch (error) {
console.log({ error })
return 'Sorry, I am not able to understand that.'
}
}

0 comments on commit a42d511

Please sign in to comment.