Spaces:
Sleeping
Sleeping
| 'use server'; | |
| /** | |
| * @fileOverview A Genkit flow for generating chatbot responses. | |
| * | |
| * - generateChatbotResponse - A function that generates chatbot responses. | |
| * - GenerateChatbotResponseInput - The input type for the generateChatbotResponse function. | |
| * - GenerateChatbotResponseOutput - The return type for the generateChatbotResponse function. | |
| */ | |
| import {ai} from '@/ai/genkit'; | |
| import {z} from 'genkit'; | |
| import fs from 'fs'; | |
| import path from 'path'; | |
| const systemInstructionsPath = path.join( | |
| process.cwd(), | |
| 'src', | |
| 'ai', | |
| 'flows', | |
| 'chatbot_system_instructions.txt' | |
| ); | |
| const systemInstructions = fs.readFileSync(systemInstructionsPath, 'utf-8'); | |
| const GenerateChatbotResponseInputSchema = z.object({ | |
| message: z.string().describe('The user message to respond to.'), | |
| chatHistory: z | |
| .array(z.object({role: z.enum(['user', 'assistant']), content: z.string()})) | |
| .optional() | |
| .describe('The chat history to maintain context.'), | |
| photoDataUri: z | |
| .string() | |
| .optional() | |
| .describe( | |
| "A photo, as a data URI that must include a MIME type and use Base64 encoding. Expected format: 'data:<mimetype>;base64,<encoded_data>'." | |
| ), | |
| }); | |
| export type GenerateChatbotResponseInput = z.infer< | |
| typeof GenerateChatbotResponseInputSchema | |
| >; | |
| const GenerateChatbotResponseOutputSchema = z.object({ | |
| response: z.string().describe('The chatbot response.'), | |
| }); | |
| export type GenerateChatbotResponseOutput = z.infer< | |
| typeof GenerateChatbotResponseOutputSchema | |
| >; | |
| export async function generateChatbotResponse( | |
| input: GenerateChatbotResponseInput | |
| ): Promise<GenerateChatbotResponseOutput> { | |
| return generateChatbotResponseFlow(input); | |
| } | |
| const prompt = ai.definePrompt({ | |
| name: 'generateChatbotResponsePrompt', | |
| system: systemInstructions, | |
| input: {schema: GenerateChatbotResponseInputSchema}, | |
| output: {schema: GenerateChatbotResponseOutputSchema}, | |
| prompt: `Here's the chat history (if any): | |
| {{#each chatHistory}} | |
| {{role}}: {{{content}}} | |
| {{/each}} | |
| {{#if photoDataUri}} | |
| [User has uploaded an image, analyze it and answer based on that and the user message.] | |
| Photo: {{media url=photoDataUri}} | |
| {{/if}} | |
| User message: {{{message}}} | |
| `, | |
| }); | |
| const generateChatbotResponseFlow = ai.defineFlow( | |
| { | |
| name: 'generateChatbotResponseFlow', | |
| inputSchema: GenerateChatbotResponseInputSchema, | |
| outputSchema: GenerateChatbotResponseOutputSchema, | |
| }, | |
| async (input) => { | |
| const {output} = await prompt(input); | |
| return output!; | |
| } | |
| ); | |