# Integration Guide: Grocify Chat โ†’ AI Chatbot Main This guide explains how to integrate the Grocify Chat Agent into the `ai-chatbot-main` Next.js application. --- ## ๐ŸŽฏ Integration Options ### Option 1: Microservice Architecture (Recommended) Deploy Grocify Chat as a separate FastAPI service and communicate via REST API. **Pros:** - Clear separation of concerns - Independent scaling - Easy to update/maintain - Can use different tech stacks **Cons:** - Network latency - Need to manage two deployments ### Option 2: Embedded Python in Next.js Run Python directly in Next.js API routes using a child process. **Pros:** - Single deployment - No network overhead **Cons:** - Complex setup - Harder to scale - Mixing tech stacks --- ## ๐Ÿš€ Implementation: Option 1 (Microservice) ### Step 1: Deploy Grocify Chat #### Local Development ```bash # Terminal 1: Run Grocify Chat cd grocifychat uvicorn app:app --reload --port 8000 # Terminal 2: Run ai-chatbot-main cd .. pnpm dev ``` #### Production (HuggingFace Spaces) 1. Deploy Grocify Chat to HuggingFace Spaces 2. Get the public URL: `https://huggingface.co/spaces/YOUR_USERNAME/grocify-chat` ### Step 2: Create API Client in Next.js **File: `lib/grocify-client.ts`** ```typescript interface GrocifyMessage { user_message: string; session_id?: string; user_id?: string; locale?: string; timezone?: string; auth_state?: Record; } interface GrocifyResponse { session_id: string; response: { reply_text: string; confidence: number; sources: Array<{ id: string; title?: string; location: string; }>; actions: Array<{ tool_name: string; tool_input: Record; }>; structured_response?: StructuredResponse; escalation?: EscalationInfo; }; timestamp: string; } type StructuredResponse = | ProductCarousel | OrderCard | QuickReplies | PromotionCard; interface ProductCarousel { type: 'product_carousel'; items: Array<{ id: string; title: string; price: number; currency: string; image?: string; cta: string; url?: string; }>; } interface OrderCard { type: 'order_card'; order_id: string; status: string; eta?: string; tracking_url?: string; } export class GrocifyClient { private baseUrl: string; constructor(baseUrl?: string) { this.baseUrl = baseUrl || process.env.GROCIFY_API_URL || 'http://localhost:8000'; } async sendMessage(message: GrocifyMessage): Promise { const response = await fetch(`${this.baseUrl}/chat`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-API-Key': process.env.GROCIFY_API_KEY || '', }, body: JSON.stringify(message), }); if (!response.ok) { throw new Error(`Grocify API error: ${response.statusText}`); } return await response.json(); } async getSession(sessionId: string) { const response = await fetch(`${this.baseUrl}/session/${sessionId}`, { headers: { 'X-API-Key': process.env.GROCIFY_API_KEY || '', }, }); if (!response.ok) { throw new Error(`Session not found: ${sessionId}`); } return await response.json(); } async deleteSession(sessionId: string) { await fetch(`${this.baseUrl}/session/${sessionId}`, { method: 'DELETE', headers: { 'X-API-Key': process.env.GROCIFY_API_KEY || '', }, }); } } export const grocifyClient = new GrocifyClient(); ``` ### Step 3: Create Next.js API Route **File: `app/api/grocify/route.ts`** ```typescript import { NextRequest, NextResponse } from 'next/server'; import { grocifyClient } from '@/lib/grocify-client'; import { auth } from '@/app/(auth)/auth'; export async function POST(req: NextRequest) { try { const session = await auth(); const body = await req.json(); // Add user context if authenticated const grocifyMessage = { ...body, user_id: session?.user?.id, auth_state: session ? { authenticated: true } : undefined, }; const response = await grocifyClient.sendMessage(grocifyMessage); return NextResponse.json(response); } catch (error) { console.error('Grocify API error:', error); return NextResponse.json( { error: 'Failed to process message' }, { status: 500 } ); } } ``` ### Step 4: Create React Component **File: `components/grocify-chat.tsx`** ```typescript 'use client'; import { useState, useEffect } from 'react'; import { useChat } from 'ai/react'; import { ProductCarousel } from './product-carousel'; import { OrderCard } from './order-card'; export function GrocifyChat() { const [sessionId, setSessionId] = useState(); const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({ api: '/api/grocify', body: { session_id: sessionId, locale: 'en-IN', timezone: 'Asia/Kolkata', }, onResponse: (response) => { const data = response.json(); if (data.session_id) { setSessionId(data.session_id); } }, }); return (
{messages.map((message) => (
{message.content}
{/* Render structured responses */} {message.structured_response && ( )} {/* Show sources */} {message.sources && message.sources.length > 0 && (
Sources: {message.sources.map(s => s.title).join(', ')}
)}
))}
); } function StructuredResponseRenderer({ data }: { data: any }) { if (data.type === 'product_carousel') { return ; } if (data.type === 'order_card') { return ; } // Add other structured response types return null; } ``` ### Step 5: Create UI Components **File: `components/product-carousel.tsx`** ```typescript import { Card } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; interface ProductItem { id: string; title: string; price: number; currency: string; image?: string; cta: string; url?: string; } export function ProductCarousel({ items }: { items: ProductItem[] }) { return (
{items.map((item) => ( {item.image && ( {item.title} )}

{item.title}

{item.currency === 'INR' ? 'โ‚น' : item.currency}{item.price}

))}
); } ``` **File: `components/order-card.tsx`** ```typescript import { Card } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; interface OrderCardProps { order_id: string; status: string; eta?: string; tracking_url?: string; } export function OrderCard({ order_id, status, eta, tracking_url }: OrderCardProps) { return (

Order ID

{order_id}

Status

{status}

{eta && (

Expected Delivery

{new Date(eta).toLocaleDateString()}

)} {tracking_url && ( )}
); } ``` ### Step 6: Environment Configuration **File: `.env.local` (in ai-chatbot-main)** ```env # Grocify Chat Integration GROCIFY_API_URL=http://localhost:8000 # Or production: https://your-username-grocify-chat.hf.space # Optional: API key for authentication GROCIFY_API_KEY=your_api_key_here ``` ### Step 7: Add Route in Next.js **File: `app/grocify/page.tsx`** ```typescript import { GrocifyChat } from '@/components/grocify-chat'; export default function GrocifyPage() { return (

Grocify Shopping Assistant

); } ``` --- ## ๐Ÿ”ง Advanced Features ### Streaming Responses (Future) ```typescript // When streaming is implemented in Grocify async function* streamGrocifyResponse(message: string) { const response = await fetch(`${GROCIFY_URL}/chat/stream`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ user_message: message }), }); const reader = response.body?.getReader(); const decoder = new TextDecoder(); while (true) { const { done, value } = await reader!.read(); if (done) break; const chunk = decoder.decode(value); yield chunk; } } ``` ### Voice Integration ```typescript // Add voice input support import { useSpeechRecognition } from 'react-speech-recognition'; export function VoiceGrocifyChat() { const { transcript, listening, startListening, stopListening } = useSpeechRecognition(); const handleVoiceInput = async () => { startListening(); // When done, send transcript to Grocify await sendMessage(transcript); }; // Rest of component... } ``` --- ## ๐Ÿ“Š Monitoring & Analytics Track usage and performance: ```typescript // Add analytics tracking export async function sendMessageWithAnalytics(message: string) { const startTime = Date.now(); try { const response = await grocifyClient.sendMessage({ user_message: message }); // Track success analytics.track('grocify_message_sent', { confidence: response.response.confidence, has_structured_response: !!response.response.structured_response, has_escalation: !!response.response.escalation, response_time: Date.now() - startTime, }); return response; } catch (error) { // Track error analytics.track('grocify_error', { error_message: error.message, response_time: Date.now() - startTime, }); throw error; } } ``` --- ## ๐Ÿงช Testing Integration ```typescript // Test file: __tests__/grocify-integration.test.ts import { grocifyClient } from '@/lib/grocify-client'; describe('Grocify Integration', () => { it('should send message and receive response', async () => { const response = await grocifyClient.sendMessage({ user_message: 'Find gifts under 2000', locale: 'en-IN', }); expect(response.response.reply_text).toBeDefined(); expect(response.response.confidence).toBeGreaterThan(0); }); it('should handle product search', async () => { const response = await grocifyClient.sendMessage({ user_message: 'Show organic products', locale: 'en-IN', }); expect(response.response.structured_response?.type).toBe('product_carousel'); }); }); ``` --- ## ๐ŸŽจ Styling Integration Match your app's theme: ```typescript // Use your existing design system import { cn } from '@/lib/utils'; export function GrocifyMessage({ message }: { message: Message }) { return (
{message.content}
); } ``` --- ## ๐Ÿš€ Deployment Checklist - [ ] Deploy Grocify Chat to HuggingFace Spaces - [ ] Add GROCIFY_API_URL to Next.js environment variables - [ ] Test API connectivity - [ ] Implement error handling - [ ] Add loading states - [ ] Set up monitoring - [ ] Configure CORS if needed - [ ] Add rate limiting - [ ] Test all structured response types - [ ] Implement escalation UI flow --- ## ๐Ÿ“ž Support For integration issues, contact the Grocify Chat team or open an issue on GitHub.