ThinkOV2 / INTEGRATION_GUIDE.md
Ayush-003's picture
Upload 28 files
9be2851 verified
|
Raw History Blame Contribute Delete
13.9 kB

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

# 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

interface GrocifyMessage {
  user_message: string;
  session_id?: string;
  user_id?: string;
  locale?: string;
  timezone?: string;
  auth_state?: Record<string, any>;
}

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<string, any>;
    }>;
    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<GrocifyResponse> {
    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

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

'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<string>();
  
  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 (
    <div className="flex flex-col h-full">
      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        {messages.map((message) => (
          <div key={message.id}>
            <div className={`message ${message.role}`}>
              {message.content}
            </div>
            
            {/* Render structured responses */}
            {message.structured_response && (
              <StructuredResponseRenderer 
                data={message.structured_response} 
              />
            )}
            
            {/* Show sources */}
            {message.sources && message.sources.length > 0 && (
              <div className="sources">
                <small>Sources: {message.sources.map(s => s.title).join(', ')}</small>
              </div>
            )}
          </div>
        ))}
      </div>
      
      <form onSubmit={handleSubmit} className="p-4 border-t">
        <input
          value={input}
          onChange={handleInputChange}
          placeholder="Ask about products, orders, or promotions..."
          disabled={isLoading}
          className="w-full p-2 border rounded"
        />
      </form>
    </div>
  );
}

function StructuredResponseRenderer({ data }: { data: any }) {
  if (data.type === 'product_carousel') {
    return <ProductCarousel items={data.items} />;
  }
  
  if (data.type === 'order_card') {
    return <OrderCard {...data} />;
  }
  
  // Add other structured response types
  return null;
}

Step 5: Create UI Components

File: components/product-carousel.tsx

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 (
    <div className="flex gap-4 overflow-x-auto py-4">
      {items.map((item) => (
        <Card key={item.id} className="min-w-[250px] p-4">
          {item.image && (
            <img 
              src={item.image} 
              alt={item.title}
              className="w-full h-40 object-cover rounded mb-2"
            />
          )}
          <h3 className="font-semibold">{item.title}</h3>
          <p className="text-lg font-bold">
            {item.currency === 'INR' ? 'β‚Ή' : item.currency}{item.price}
          </p>
          <Button 
            className="w-full mt-2"
            onClick={() => window.open(item.url, '_blank')}
          >
            {item.cta}
          </Button>
        </Card>
      ))}
    </div>
  );
}

File: components/order-card.tsx

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 (
    <Card className="p-4">
      <div className="flex justify-between items-start">
        <div>
          <p className="text-sm text-muted-foreground">Order ID</p>
          <p className="font-semibold">{order_id}</p>
        </div>
        <div className="text-right">
          <p className="text-sm text-muted-foreground">Status</p>
          <p className="font-semibold text-green-600">{status}</p>
        </div>
      </div>
      
      {eta && (
        <div className="mt-2">
          <p className="text-sm text-muted-foreground">Expected Delivery</p>
          <p>{new Date(eta).toLocaleDateString()}</p>
        </div>
      )}
      
      {tracking_url && (
        <Button className="w-full mt-4" asChild>
          <a href={tracking_url} target="_blank" rel="noopener noreferrer">
            Track Order
          </a>
        </Button>
      )}
    </Card>
  );
}

Step 6: Environment Configuration

File: .env.local (in ai-chatbot-main)

# 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

import { GrocifyChat } from '@/components/grocify-chat';

export default function GrocifyPage() {
  return (
    <div className="container mx-auto h-screen">
      <h1 className="text-2xl font-bold p-4">Grocify Shopping Assistant</h1>
      <GrocifyChat />
    </div>
  );
}

πŸ”§ Advanced Features

Streaming Responses (Future)

// 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

// 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:

// 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

// 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:

// Use your existing design system
import { cn } from '@/lib/utils';

export function GrocifyMessage({ message }: { message: Message }) {
  return (
    <div className={cn(
      'rounded-lg p-4',
      message.role === 'user' ? 'bg-primary text-primary-foreground' : 'bg-muted'
    )}>
      {message.content}
    </div>
  );
}

πŸš€ 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.