/n8n-tutorials

How to send user metadata along with prompts to Gemini from n8n?

Learn how to send user metadata with prompts to Gemini from n8n by setting up an HTTP request node, configuring authentication, dynamic payloads, error handling, and security best practices.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free consultation

How to send user metadata along with prompts to Gemini from n8n?

To send user metadata along with prompts to Gemini from n8n, you'll need to set up an HTTP request node that includes the user metadata in the API call payload. You'll need to format your API request with both the prompt text and the user metadata object in the JSON body, authenticate with your API key, and configure the proper endpoints for the Gemini API.

 

Step 1: Set Up a New Workflow in n8n

 

First, let's create a new workflow in n8n:

  1. Log in to your n8n instance.
  2. Click on the "Workflows" section in the sidebar.
  3. Click "Create New Workflow" button.
  4. Give your workflow a descriptive name, such as "Gemini API with User Metadata".

 

Step 2: Add a Trigger Node

 

You need a trigger to start your workflow:

  1. Click on the "+" button to add a new node.
  2. Select a trigger node that fits your use case. Common options include:
    • Manual Trigger: For testing or manual execution
    • Webhook: To receive incoming HTTP requests
    • Schedule Trigger: For time-based execution
  3. For this tutorial, let's use a "Manual Trigger" node for simplicity.

 

Step 3: Add HTTP Request Node

 

Now, let's add an HTTP Request node to communicate with the Gemini API:

  1. Click on the "+" button after your trigger node.
  2. Search for "HTTP Request" and select it.
  3. Configure the HTTP Request node with the following settings:
    • Authentication: "Header Auth"
    • Method: "POST"
    • URL: "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent"
    • Headers: Add a header with name "Content-Type" and value "application/json"

 

Step 4: Configure API Key Authentication

 

To authenticate with the Gemini API:

  1. In the HTTP Request node, go to the "Authentication" tab.
  2. For "Authentication Type", select "Query/Header Auth".
  3. Add your API key as a parameter:
    • Name: "key"
    • Value: "YOUR_GEMINI_API\_KEY"
    • Add To: "Query"

For better security, consider using n8n credentials or environment variables to store your API key rather than hardcoding it.

 

Step 5: Prepare the Payload with User Metadata

 

Now, let's structure the request body to include both the prompt and user metadata:

  1. In the HTTP Request node, go to the "Request Body" tab.
  2. Select "JSON" as the Body Content Type.
  3. Enter a JSON structure that includes both the content and user metadata:

{
  "contents": [
    {
      "parts": [
        {
          "text": "Your prompt text here"
        }
      ]
    }
  ],
  "generationConfig": {
    "temperature": 0.7,
    "maxOutputTokens": 1024
  },
  "safetySettings": [
    {
      "category": "HARM_CATEGORY_HARASSMENT",
      "threshold": "BLOCK_MEDIUM_AND\_ABOVE"
    }
  ],
  "userMetadata": {
    "userId": "user-123",
    "userLocation": "New York",
    "userLanguage": "en-US",
    "customData": {
      "subscription": "premium",
      "lastLogin": "2023-06-15T14:30:00Z"
    }
  }
}

 

Step 6: Make the Request Dynamic

 

Let's modify the request to use dynamic data:

  1. In the HTTP Request node, click on the "Expression Editor" button next to the JSON input.
  2. Replace the static values with expressions that reference data from previous nodes:

{
  "contents": [
    {
      "parts": [
        {
          "text": "{{$json.promptText}}"
        }
      ]
    }
  ],
  "generationConfig": {
    "temperature": {{$json.temperature || 0.7}},
    "maxOutputTokens": {{$json.maxTokens || 1024}}
  },
  "safetySettings": [
    {
      "category": "HARM_CATEGORY_HARASSMENT",
      "threshold": "BLOCK_MEDIUM_AND\_ABOVE"
    }
  ],
  "userMetadata": {
    "userId": "{{$json.userId}}",
    "userLocation": "{{$json.userLocation}}",
    "userLanguage": "{{$json.userLanguage}}",
    "customData": {{$json.customData || "{}"}}
  }
}

 

Step 7: Add a Set Node to Provide Input Data

 

To feed data into the HTTP Request node:

  1. Add a "Set" node between your trigger and HTTP Request node.
  2. Configure it with the following key-value pairs:

{
  "promptText": "Write a short story about an adventure in space",
  "temperature": 0.8,
  "maxTokens": 2048,
  "userId": "user-456",
  "userLocation": "Berlin",
  "userLanguage": "de-DE",
  "customData": {
    "subscription": "premium",
    "userPreferences": {
      "genre": "sci-fi",
      "complexity": "advanced"
    }
  }
}

 

Step 8: Add Error Handling

 

Let's add error handling to the workflow:

  1. Connect the output of the HTTP Request node to an "IF" node.
  2. Configure the IF node with the condition: {{$json.statusCode}} >= 400
  3. If the condition is true (error occurred):
    • Connect to an "Error Trigger" node
    • Configure error handling as needed
  4. If the condition is false (success):
    • Connect to nodes that process the Gemini response

 

Step 9: Process the Gemini Response

 

To extract and process the Gemini API response:

  1. Add a "Set" node after the success path of the IF node.
  2. Configure it to extract the relevant parts of the response:

{
  "generatedText": "{{$json.body.candidates[0].content.parts[0].text}}",
  "safetyRatings": "{{$json.body.candidates[0].safetyRatings}}",
  "finishReason": "{{$json.body.candidates[0].finishReason}}",
  "rawResponse": "{{$json.body}}"
}

 

Step 10: Test the Workflow

 

Now, let's test our workflow:

  1. Save the workflow by clicking the "Save" button.
  2. Click the "Execute Workflow" button to run it.
  3. Check the output of each node to verify that:
    • The request is properly formatted with user metadata
    • The API response is received and processed correctly

 

Step 11: Create a Reusable Workflow

 

To make this workflow reusable:

  1. Convert your workflow to a subworkflow:
    • Go to Workflow Settings
    • Enable "Make this workflow available as a subworkflow"
  2. Define clear input and output parameters for your subworkflow.
  3. Document what metadata fields are supported and expected.

 

Step 12: Set Up Proper Error Logging

 

Enhance your error handling:

  1. Add a "Function" node in the error path that formats error messages.
  2. Configure it with code like:

// Format error message
const errorDetails = {
  statusCode: $input.item.json.statusCode,
  statusMessage: $input.item.json.statusMessage,
  errorMessage: $input.item.json.body?.error?.message || "Unknown error",
  timestamp: new Date().toISOString()
};

// Return formatted error
return {
  error: errorDetails,
  originalInput: $input.item.json.options?.body || {}
};
  1. Connect this to notification nodes or database nodes to log errors.

 

Step 13: Implement Retry Logic

 

Add retry capability for API call failures:

  1. In the HTTP Request node settings, enable "Retry on Fail".
  2. Set "Max Tries" to an appropriate number (like 3).
  3. Configure "Retry Wait Time" (e.g., 1000ms).

 

Step 14: Add Support for Different Gemini Models

 

Make your workflow flexible for different Gemini models:

  1. Modify your Set node to include a model parameter:

{
  "model": "gemini-pro",
  "promptText": "Write a short story about an adventure in space",
  // other parameters as before
}
  1. Update the HTTP Request URL to use this parameter:

https://generativelanguage.googleapis.com/v1beta/models/{{$json.model}}:generateContent

 

Step 15: Implement Security Best Practices

 

Enhance security for your workflow:

  1. Store sensitive information (like API keys) in n8n credentials:
    • Go to Settings → Credentials
    • Create a new credential of type "Generic API"
    • Store your API key there
  2. Reference credentials in your HTTP Request node instead of hardcoding values.
  3. Implement input validation before sending data to the API.

 

Final Notes

 

When working with the Gemini API and user metadata:

  • Always ensure you're compliant with privacy regulations when collecting and sending user metadata.
  • Use meaningful metadata that can help improve the AI responses.
  • Test thoroughly with different user profiles to ensure the metadata is influencing the responses as expected.
  • Monitor your API usage to stay within quotas and rate limits.
  • Keep your implementation up-to-date with Gemini API changes, as metadata handling may evolve.

By following this tutorial, you've created a workflow in n8n that can send user metadata along with prompts to the Gemini API, allowing for more personalized and context-aware AI responses.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022