Implement Facebook-style comment suggestions using Gemini API

💬
engineering
Posted on February 5, 2025

As someone who enjoys experimenting with design and technology, I love finding ways to enhance user experiences. Previously, I implemented a comment suggestion feature on my website, inspired by Facebook’s smart replies. While it was fun and users enjoyed using it, the comments were static, randomly pulled from predefined positive and negative arrays. Over time, they started to feel repetitive and spam-like.

Post Content Image

The Upgrade: AI-Generated Contextual Comments

This weekend, I decided to level up this feature using AI. Instead of static responses, I integrated the Gemini API to dynamically generate contextually relevant comment suggestions based on each blog post's content. Now, every set of suggestions feels fresh, engaging, and aligned with the article it appears under.

The Challenge: Crafting the Perfect Prompt

Getting AI to generate the right kind of comments wasn’t straightforward. I needed the suggestions to be:

  • Short and concise (limited to 10 words).
  • Fun and engaging, with a friendly tone.
  • Diverse in sentiment, ensuring that some comments reflect constructive feedback.
  • Language-specific, incorporating trendy phrases in both English and Vietnamese.
  • Context-aware, so the comments match the article's subject.

After several iterations, I refined the following prompt:

The Implementation

With the prompt refined, I add an API route to fetch suggestions dynamically to my Next.js website. The server-side function:

  • Retrieves the page URL.
  • Calls the Gemini API with the prompt.
  • Caches the response for 31 days to optimize performance.
  • Returns the AI-generated comments in JSON format.

Using the Gemini Node SDK (@google/generative-ai)

To integrate the Gemini API, I used the official Node.js SDK, @google/generative-ai. Here’s how to set it up:

  1. Install the SDK:
  2. Import and configure the Gemini model:
  3. Fetch AI-generated comment suggestions:

The API Endpoint

The API endpoint handles requests efficiently:

The Results

With this upgrade, the comments feel more natural, engaging, and interactive. Users are responding positively to the AI-generated suggestions, and the experience is far more dynamic than before.

Post Content Image
Post Content Image
Post Content Image

This project was a great exercise in prompt engineering and AI-powered UX improvements, making user interactions feel more intuitive and engaging. Excited to keep refining it further!

If you found this helpful, consider supporting my work

Buy me a coffee

Give your reaction

Or wanna share your thoughts?

Suggestion