Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: generateChatMessage #18

Merged
merged 1 commit into from
Dec 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions firebase.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,9 @@
"pubsub": {
"port": 8085
},
"storage": {
"port": 9199
},
"eventarc": {
"port": 9299
},
"dataconnect": {
"port": 9399
},
"tasks": {
"port": 9499
},
Expand Down
39 changes: 39 additions & 0 deletions functions/prompts/chat.prompt
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
---
model: googleai/gemini-1.5-flash-latest
config:
temperature: 0.7
input:
schema:
messages(array):
createdAt: string
isUser: boolean
text: string
output:
format: json
schema:
response: string
---

You are an advanced AI assistant. Your role is to provide helpful and accurate responses to user queries based on the chat history provided.

Please generate the optimal response to the user's current question using the following chat history:

Chat History:
{{#each messages}}
- Created At: {{createdAt}}
- Is User: {{isUser}}
- Text: {{text}}
{{/each}}

When generating your response, please adhere to these guidelines:
1. Maintain context by referencing the provided chat history.
2. Provide accurate and relevant information based on the available data.
3. Suggest additional actions when appropriate.
4. Analyze the user's sentiment from their messages and respond empathetically.

Your goal is to generate friendly and effective responses that enhance user satisfaction while leveraging the chat history.

Remember to format your response as a JSON object with the following structure:
{
"response": "Your detailed response here",
}
64 changes: 64 additions & 0 deletions functions/src/genkit-functions/generateChatMessage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { prompt } from '@genkit-ai/dotprompt'
import { firebaseAuth } from '@genkit-ai/firebase/auth'
import * as genkitFunctions from '@genkit-ai/firebase/functions'
import { Timestamp } from 'firebase-admin/firestore'
import * as z from 'zod'
import { db, googleAIapiKey } from '../config/firebase'

const chatInputSchema = z.object({
messages: z.array(
z.object({
createdAt: z.string(),
isUser: z.boolean(),
text: z.string(),
})
),
})

export const generateChatMessage = genkitFunctions.onFlow(
{
name: `generateChatMessage`,
httpsOptions: {
cors: true,
secrets: [googleAIapiKey],
},
inputSchema: z.object({
userId: z.string(),
chatId: z.string(),
}),
authPolicy: firebaseAuth((user) => {
if (user.firebase?.sign_in_provider !== `anonymous`) {
throw new Error(`Only anonymously authenticated users can access this function`)
}
}),
},
async (input) => {
try {
const chatDoc = await db.collection(`chats`).doc(input.chatId).get()

if (!chatDoc.exists) throw new Error(`Chat document not found`)

const messagesSnapshot = await chatDoc.ref.collection(`messages`).get()

const messages = messagesSnapshot.docs.map((doc) => ({
createdAt: doc.data().createdAt.toDate().toString(),
isUser: doc.data().isUser,
text: doc.data().text,
}))

const chatbotPrompt = await prompt<z.infer<typeof chatInputSchema>>(`chat`)
const result = await chatbotPrompt.generate({ input: { messages } })

await chatDoc.ref.collection(`messages`).add({
createdAt: Timestamp.now(),
isUser: false,
text: result.output().response,
})

return result.output()
} catch (error) {
console.error(`Error in generateChatMessage:`, error)
throw error
}
}
)
1 change: 1 addition & 0 deletions functions/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export { analyzeStorageImage } from './genkit-functions/analyzeStorageImage'
export { analyzeWebContents } from './genkit-functions/analyzeWebContents'
export { anonymousFirestoreChatbot } from './genkit-functions/anonymousFirestoreChatbot'
export { generateChatMessage } from './genkit-functions/generateChatMessage'
export { generateImage } from './genkit-functions/generateImage'
export { noAuthFunction } from './genkit-functions/noAuthFunction'
Loading